]> code.delx.au - gnu-emacs/blob - lispintro/emacs-lisp-intro.txt
Update for Texinfo version 4.2
[gnu-emacs] / lispintro / emacs-lisp-intro.txt
1 START-INFO-DIR-ENTRY
2 * Emacs Lisp Intro: (eintr).
3 A simple introduction to Emacs Lisp programming.
4 END-INFO-DIR-ENTRY
5
6 Short Contents
7 **************
8
9 An Introduction to Programming in Emacs Lisp
10 Preface
11 List Processing
12 Practicing Evaluation
13 How To Write Function Definitions
14 A Few Buffer-Related Functions
15 A Few More Complex Functions
16 Narrowing and Widening
17 `car', `cdr', `cons': Fundamental Functions
18 Cutting and Storing Text
19 How Lists are Implemented
20 Yanking Text Back
21 Loops and Recursion
22 Regular Expression Searches
23 Counting: Repetition and Regexps
24 Counting Words in a `defun'
25 Readying a Graph
26 Your `.emacs' File
27 Debugging
28 Conclusion
29 The `the-the' Function
30 Handling the Kill Ring
31 A Graph with Labelled Axes
32 GNU Free Documentation License
33 Index
34 About the Author
35
36
37 Table of Contents
38 *****************
39
40
41 An Introduction to Programming in Emacs Lisp
42
43 Preface
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
51 List 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
82 Practicing 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
90 How 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
118 A 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
132 A 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
153 Narrowing 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
171 Cutting 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
197 How Lists are Implemented
198 Lists diagrammed
199 Symbols as a Chest of Drawers
200 Exercise
201
202 Yanking Text Back
203 Kill Ring Overview
204 The `kill-ring-yank-pointer' Variable
205 Exercises with `yank' and `nthcdr'
206
207 Loops 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
239 Regular 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
259 Counting: 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
267 Counting 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
284 Readying 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
291 Your `.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
308 Debugging
309 `debug'
310 `debug-on-entry'
311 `debug-on-quit' and `(debug)'
312 The `edebug' Source Level Debugger
313 Debugging Exercises
314
315 Conclusion
316
317 The `the-the' Function
318
319 Handling 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
333 A 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
354 GNU Free Documentation License
355
356 Index
357
358 About the Author
359
360
361 An Introduction to Programming in Emacs Lisp
362 ********************************************
363
364 This is an introduction to `Programming in Emacs Lisp', for people
365 who are not programmers.
366
367 Edition 2.07, 2002 Aug 23
368
369 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002
370 Free Software Foundation, Inc.
371
372
373 Published by the Free Software Foundation, Inc.
374 59 Temple Place, Suite 330
375 Boston, MA 02111-1307 USA
376 Edition 2.07, 2002 Aug 23
377
378 ISBN 1-882114-43-4
379
380 Permission is granted to copy, distribute and/or modify this document
381 under the terms of the GNU Free Documentation License, Version 1.1 or
382 any later version published by the Free Software Foundation; there
383 being no Invariant Section, with the Front-Cover Texts being "A GNU
384 Manual", and with the Back-Cover Texts as in (a) below. A copy of
385 the license is included in the section entitled "GNU Free
386 Documentation License".
387
388 (a) The FSF's Back-Cover Text is: "You have freedom to copy and
389 modify this GNU Manual, like GNU software. Copies published by the
390 Free Software Foundation raise funds for GNU development."
391 This master menu first lists each chapter and index; then it lists
392 every node in every chapter.
393
394 Preface
395 *******
396
397 Most of the GNU Emacs integrated environment is written in the
398 programming language called Emacs Lisp. The code written in this
399 programming language is the software--the sets of instructions--that
400 tell the computer what to do when you give it commands. Emacs is
401 designed so that you can write new code in Emacs Lisp and easily
402 install it as an extension to the editor.
403
404 (GNU Emacs is sometimes called an "extensible editor", but it does
405 much more than provide editing capabilities. It is better to refer to
406 Emacs as an "extensible computing environment". However, that phrase
407 is quite a mouthful. It is easier to refer to Emacs simply as an
408 editor. Moreover, everything you do in Emacs--find the Mayan date
409 and phases of the moon, simplify polynomials, debug code, manage
410 files, read letters, write books--all these activities are kinds of
411 editing in the most general sense of the word.)
412
413 Why Study Emacs Lisp?
414 =====================
415
416 Although Emacs Lisp is usually thought of in association only with
417 Emacs, it is a full computer programming language. You can use Emacs
418 Lisp as you would any other programming language.
419
420 Perhaps you want to understand programming; perhaps you want to extend
421 Emacs; or perhaps you want to become a programmer. This introduction
422 to Emacs Lisp is designed to get you started: to guide you in
423 learning the fundamentals of programming, and more importantly, to
424 show you how you can teach yourself to go further.
425
426 On Reading this Text
427 ====================
428
429 All through this document, you will see little sample programs you can
430 run inside of Emacs. If you read this document in Info inside of GNU
431 Emacs, you can run the programs as they appear. (This is easy to do
432 and is explained when the examples are presented.) Alternatively,
433 you can read this introduction as a printed book while sitting beside
434 a computer running Emacs. (This is what I like to do; I like printed
435 books.) If you don't have a running Emacs beside you, you can still
436 read this book, but in this case, it is best to treat it as a novel
437 or as a travel guide to a country not yet visited: interesting, but
438 not the same as being there.
439
440 Much of this introduction is dedicated to walk-throughs or guided
441 tours of code used in GNU Emacs. These tours are designed for two
442 purposes: first, to give you familiarity with real, working code
443 (code you use every day); and, second, to give you familiarity with
444 the way Emacs works. It is interesting to see how a working
445 environment is implemented. Also, I hope that you will pick up the
446 habit of browsing through source code. You can learn from it and
447 mine it for ideas. Having GNU Emacs is like having a dragon's cave
448 of treasures.
449
450 In addition to learning about Emacs as an editor and Emacs Lisp as a
451 programming language, the examples and guided tours will give you an
452 opportunity to get acquainted with Emacs as a Lisp programming
453 environment. GNU Emacs supports programming and provides tools that
454 you will want to become comfortable using, such as `M-.' (the key
455 which invokes the `find-tag' command). You will also learn about
456 buffers and other objects that are part of the environment. Learning
457 about these features of Emacs is like learning new routes around your
458 home town.
459
460 Finally, I hope to convey some of the skills for using Emacs to learn
461 aspects of programming that you don't know. You can often use Emacs
462 to help you understand what puzzles you or to find out how to do
463 something new. This self-reliance is not only a pleasure, but an
464 advantage.
465
466 For Whom This is Written
467 ========================
468
469 This text is written as an elementary introduction for people who are
470 not programmers. If you are a programmer, you may not be satisfied
471 with this primer. The reason is that you may have become expert at
472 reading reference manuals and be put off by the way this text is
473 organized.
474
475 An 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
488 This introduction is not written for this person!
489
490 Firstly, I try to say everything at least three times: first, to
491 introduce it; second, to show it in context; and third, to show it in
492 a different context, or to review it.
493
494 Secondly, I hardly ever put all the information about a subject in one
495 place, much less in one paragraph. To my way of thinking, that
496 imposes too heavy a burden on the reader. Instead I try to explain
497 only what you need to know at the time. (Sometimes I include a
498 little extra information so you won't be surprised later when the
499 additional information is formally introduced.)
500
501 When you read this text, you are not expected to learn everything the
502 first time. Frequently, you need only make, as it were, a `nodding
503 acquaintance' with some of the items mentioned. My hope is that I
504 have structured the text and given you enough hints that you will be
505 alert to what is important, and concentrate on it.
506
507 You will need to "dive into" some paragraphs; there is no other way
508 to read them. But I have tried to keep down the number of such
509 paragraphs. This book is intended as an approachable hill, rather
510 than as a daunting mountain.
511
512 This introduction to `Programming in Emacs Lisp' has a companion
513 document, *Note The GNU Emacs Lisp Reference Manual: (elisp)Top. The
514 reference manual has more detail than this introduction. In the
515 reference manual, all the information about one topic is concentrated
516 in one place. You should turn to it if you are like the programmer
517 quoted above. And, of course, after you have read this
518 `Introduction', you will find the `Reference Manual' useful when you
519 are writing your own programs.
520
521 Lisp History
522 ============
523
524 Lisp was first developed in the late 1950s at the Massachusetts
525 Institute of Technology for research in artificial intelligence. The
526 great power of the Lisp language makes it superior for other purposes
527 as well, such as writing editor commands and integrated environments.
528
529 GNU Emacs Lisp is largely inspired by Maclisp, which was written at
530 MIT in the 1960s. It is somewhat inspired by Common Lisp, which
531 became a standard in the 1980s. However, Emacs Lisp is much simpler
532 than Common Lisp. (The standard Emacs distribution contains an
533 optional extensions file, `cl.el', that adds many Common Lisp
534 features to Emacs Lisp.)
535
536 A Note for Novices
537 ==================
538
539 If you don't know GNU Emacs, you can still read this document
540 profitably. However, I recommend you learn Emacs, if only to learn to
541 move around your computer screen. You can teach yourself how to use
542 Emacs with the on-line tutorial. To use it, type `C-h t'. (This
543 means you press and release the <CTRL> key and the `h' at the same
544 time, and then press and release `t'.)
545
546 Also, I often refer to one of Emacs' standard commands by listing the
547 keys which you press to invoke the command and then giving the name of
548 the command in parentheses, like this: `M-C-\' (`indent-region').
549 What this means is that the `indent-region' command is customarily
550 invoked by typing `M-C-\'. (You can, if you wish, change the keys
551 that are typed to invoke the command; this is called "rebinding".
552 *Note Keymaps: Keymaps.) The abbreviation `M-C-\' means that you
553 type your <META> key, <CTRL> key and <\> key all at the same time.
554 (On many modern keyboards the <META> key is labelled <ALT>.)
555 Sometimes a combination like this is called a keychord, since it is
556 similar to the way you play a chord on a piano. If your keyboard does
557 not have a <META> key, the <ESC> key prefix is used in place of it.
558 In this case, `M-C-\' means that you press and release your <ESC> key
559 and then type the <CTRL> key and the <\> key at the same time. But
560 usually `M-C-\' means press the <CTRL> key along with the key that is
561 labelled <ALT> and, at the same time, press the <\> key.
562
563 In addition to typing a lone keychord, you can prefix what you type
564 with `C-u', which is called the `universal argument'. The `C-u'
565 keychord passes an argument to the subsequent command. Thus, to
566 indent a region of plain text by 6 spaces, mark the region, and then
567 type `C-u 6 M-C-\'. (If you do not specify a number, Emacs either
568 passes the number 4 to the command or otherwise runs the command
569 differently than it would otherwise.) *Note Numeric Arguments:
570 (emacs)Arguments.
571
572 If you are reading this in Info using GNU Emacs, you can read through
573 this whole document just by pressing the space bar, <SPC>. (To learn
574 about Info, type `C-h i' and then select Info.)
575
576 A note on terminology: when I use the word Lisp alone, I often am
577 referring to the various dialects of Lisp in general, but when I speak
578 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
579
580 Thank You
581 =========
582
583 My thanks to all who helped me with this book. My especial thanks to
584 Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
585 Randy Smith, Richard M. Stallman, and Melissa Weisshaus. My thanks
586 also go to both Philip Johnson and David Stampe for their patient
587 encouragement. My mistakes are my own.
588
589 Robert J. Chassell
590
591 List Processing
592 ***************
593
594 To the untutored eye, Lisp is a strange programming language. In Lisp
595 code there are parentheses everywhere. Some people even claim that
596 the name stands for `Lots of Isolated Silly Parentheses'. But the
597 claim is unwarranted. Lisp stands for LISt Processing, and the
598 programming language handles _lists_ (and lists of lists) by putting
599 them between parentheses. The parentheses mark the boundaries of the
600 list. Sometimes a list is preceded by a single apostrophe or
601 quotation mark, `''. Lists are the basis of Lisp.
602
603 Lisp Lists
604 ==========
605
606 In Lisp, a list looks like this: `'(rose violet daisy buttercup)'.
607 This list is preceded by a single apostrophe. It could just as well
608 be written as follows, which looks more like the kind of list you are
609 likely to be familiar with:
610
611 '(rose
612 violet
613 daisy
614 buttercup)
615
616 The elements of this list are the names of the four different flowers,
617 separated from each other by whitespace and surrounded by parentheses,
618 like flowers in a field with a stone wall around them.
619
620 Numbers, Lists inside of Lists
621 ------------------------------
622
623 Lists can also have numbers in them, as in this list: `(+ 2 2)'.
624 This list has a plus-sign, `+', followed by two `2's, each separated
625 by whitespace.
626
627 In Lisp, both data and programs are represented the same way; that is,
628 they are both lists of words, numbers, or other lists, separated by
629 whitespace and surrounded by parentheses. (Since a program looks like
630 data, one program may easily serve as data for another; this is a very
631 powerful feature of Lisp.) (Incidentally, these two parenthetical
632 remarks are _not_ Lisp lists, because they contain `;' and `.' as
633 punctuation marks.)
634
635 Here is another list, this time with a list inside of it:
636
637 '(this list has (a list inside of it))
638
639 The components of this list are the words `this', `list', `has', and
640 the list `(a list inside of it)'. The interior list is made up of
641 the words `a', `list', `inside', `of', `it'.
642
643 Lisp Atoms
644 ----------
645
646 In Lisp, what we have been calling words are called "atoms". This
647 term comes from the historical meaning of the word atom, which means
648 `indivisible'. As far as Lisp is concerned, the words we have been
649 using in the lists cannot be divided into any smaller parts and still
650 mean the same thing as part of a program; likewise with numbers and
651 single character symbols like `+'. On the other hand, unlike an
652 atom, a list can be split into parts. (*Note `car' `cdr' & `cons'
653 Fundamental Functions: car cdr & cons.)
654
655 In a list, atoms are separated from each other by whitespace. They
656 can be right next to a parenthesis.
657
658 Technically speaking, a list in Lisp consists of parentheses
659 surrounding atoms separated by whitespace or surrounding other lists
660 or surrounding both atoms and other lists. A list can have just one
661 atom in it or have nothing in it at all. A list with nothing in it
662 looks like this: `()', and is called the "empty list". Unlike
663 anything else, an empty list is considered both an atom and a list at
664 the same time.
665
666 The 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
669 representation, or to the atom or list as it is held internally in the
670 computer. Often, people use the term "expression" indiscriminately.
671 (Also, in many texts, the word "form" is used as a synonym for
672 expression.)
673
674 Incidentally, the atoms that make up our universe were named such when
675 they were thought to be indivisible; but it has been found that
676 physical atoms are not indivisible. Parts can split off an atom or
677 it can fission into two parts of roughly equal size. Physical atoms
678 were named prematurely, before their truer nature was found. In
679 Lisp, certain kinds of atom, such as an array, can be separated into
680 parts; but the mechanism for doing this is different from the
681 mechanism for splitting a list. As far as list operations are
682 concerned, the atoms of a list are unsplittable.
683
684 As in English, the meanings of the component letters of a Lisp atom
685 are different from the meaning the letters make as a word. For
686 example, the word for the South American sloth, the `ai', is
687 completely different from the two words, `a', and `i'.
688
689 There are many kinds of atom in nature but only a few in Lisp: for
690 example, "numbers", such as 37, 511, or 1729, and "symbols", such as
691 `+', `foo', or `forward-line'. The words we have listed in the
692 examples above are all symbols. In everyday Lisp conversation, the
693 word "atom" is not often used, because programmers usually try to be
694 more specific about what kind of atom they are dealing with. Lisp
695 programming is mostly about symbols (and sometimes numbers) within
696 lists. (Incidentally, the preceding three word parenthetical remark
697 is a proper list in Lisp, since it consists of atoms, which in this
698 case are symbols, separated by whitespace and enclosed by
699 parentheses, without any non-Lisp punctuation.)
700
701 In addition, text between double quotation marks--even sentences or
702 paragraphs--is an atom. Here is an example:
703
704 '(this list includes "text between quotation marks.")
705
706 In Lisp, all of the quoted text including the punctuation mark and the
707 blank 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
709 is used for messages that a computer can print for a human to read.
710 Strings are a different kind of atom than numbers or symbols and are
711 used differently.
712
713 Whitespace in Lists
714 -------------------
715
716 The amount of whitespace in a list does not matter. From the point
717 of view of the Lisp language,
718
719 '(this list
720 looks like this)
721
722 is exactly the same as this:
723
724 '(this list looks like this)
725
726 Both examples show what to Lisp is the same list, the list made up of
727 the symbols `this', `list', `looks', `like', and `this' in that order.
728
729 Extra whitespace and newlines are designed to make a list more
730 readable by humans. When Lisp reads the expression, it gets rid of
731 all the extra whitespace (but it needs to have at least one space
732 between atoms in order to tell them apart.)
733
734 Odd as it seems, the examples we have seen cover almost all of what
735 Lisp lists look like! Every other list in Lisp looks more or less
736 like one of these examples, except that the list may be longer and
737 more complex. In brief, a list is between parentheses, a string is
738 between quotation marks, a symbol looks like a word, and a number
739 looks like a number. (For certain situations, square brackets, dots
740 and a few other special characters may be used; however, we will go
741 quite far without them.)
742
743 GNU Emacs Helps You Type Lists
744 ------------------------------
745
746 When you type a Lisp expression in GNU Emacs using either Lisp
747 Interaction mode or Emacs Lisp mode, you have available to you several
748 commands to format the Lisp expression so it is easy to read. For
749 example, pressing the <TAB> key automatically indents the line the
750 cursor is on by the right amount. A command to properly indent the
751 code in a region is customarily bound to `M-C-\'. Indentation is
752 designed so that you can see which elements of a list belong to which
753 list--elements of a sub-list are indented more than the elements of
754 the enclosing list.
755
756 In addition, when you type a closing parenthesis, Emacs momentarily
757 jumps the cursor back to the matching opening parenthesis, so you can
758 see which one it is. This is very useful, since every list you type
759 in Lisp must have its closing parenthesis match its opening
760 parenthesis. (*Note Major Modes: (emacs)Major Modes, for more
761 information about Emacs' modes.)
762
763 Run a Program
764 =============
765
766 A 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
768 of three things: do nothing except return to you the list itself; send
769 you an error message; or, treat the first symbol in the list as a
770 command to do something. (Usually, of course, it is the last of these
771 three things that you really want!)
772
773 The single apostrophe, `'', that I put in front of some of the
774 example lists in preceding sections is called a "quote"; when it
775 precedes a list, it tells Lisp to do nothing with the list, other than
776 take it as it is written. But if there is no quote preceding a list,
777 the first item of the list is special: it is a command for the
778 computer to obey. (In Lisp, these commands are called _functions_.)
779 The list `(+ 2 2)' shown above did not have a quote in front of it,
780 so Lisp understands that the `+' is an instruction to do something
781 with the rest of the list: add the numbers that follow.
782
783 If you are reading this inside of GNU Emacs in Info, here is how you
784 can evaluate such a list: place your cursor immediately after the
785 right hand parenthesis of the following list and then type `C-x C-e':
786
787 (+ 2 2)
788
789 You will see the number `4' appear in the echo area. (In the jargon,
790 what you have just done is "evaluate the list." The echo area is the
791 line at the bottom of the screen that displays or "echoes" text.)
792 Now try the same thing with a quoted list: place the cursor right
793 after the following list and type `C-x C-e':
794
795 '(this is a quoted list)
796
797 You will see `(this is a quoted list)' appear in the echo area.
798
799 In both cases, what you are doing is giving a command to the program
800 inside of GNU Emacs called the "Lisp interpreter"--giving the
801 interpreter a command to evaluate the expression. The name of the
802 Lisp interpreter comes from the word for the task done by a human who
803 comes up with the meaning of an expression--who "interprets" it.
804
805 You can also evaluate an atom that is not part of a list--one that is
806 not surrounded by parentheses; again, the Lisp interpreter translates
807 from the humanly readable expression to the language of the computer.
808 But before discussing this (*note Variables::), we will discuss what
809 the Lisp interpreter does when you make an error.
810
811 Generate an Error Message
812 =========================
813
814 Partly so you won't worry if you do it accidentally, we will now give
815 a command to the Lisp interpreter that generates an error message.
816 This is a harmless activity; and indeed, we will often try to generate
817 error messages intentionally. Once you understand the jargon, error
818 messages can be informative. Instead of being called "error"
819 messages, they should be called "help" messages. They are like
820 signposts to a traveller in a strange country; deciphering them can be
821 hard, but once understood, they can point the way.
822
823 The error message is generated by a built-in GNU Emacs debugger. We
824 will `enter the debugger'. You get out of the debugger by typing `q'.
825
826 What we will do is evaluate a list that is not quoted and does not
827 have a meaningful command as its first element. Here is a list almost
828 exactly the same as the one we just used, but without the single-quote
829 in front of it. Position the cursor right after it and type `C-x
830 C-e':
831
832 (this is an unquoted list)
833
834 What you see depends on which version of Emacs you are running. GNU
835 Emacs version 21 provides more information than version 20 and before.
836 First, the more recent result of generating an error; then the
837 earlier, version 20 result.
838
839 In GNU Emacs version 21, a `*Backtrace*' window will open up and you
840 will 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
851 Your cursor will be in this window (you may have to wait a few seconds
852 before it becomes visible). To quit the debugger and make the
853 debugger window go away, type:
854
855 q
856
857 Please type `q' right now, so you become confident that you can get
858 out of the debugger. Then, type `C-x C-e' again to re-enter it.
859
860 Based on what we already know, we can almost read this error message.
861
862 You read the `*Backtrace*' buffer from the bottom up; it tells you
863 what Emacs did. When you typed `C-x C-e', you made an interactive
864 call to the command `eval-last-sexp'. `eval' is an abbreviation for
865 `evaluate' and `sexp' is an abbreviation for `symbolic expression'.
866 The command means `evaluate last symbolic expression', which is the
867 expression just before your cursor.
868
869 Each line above tells you what the Lisp interpreter evaluated next.
870 The most recent action is at the top. The buffer is called the
871 `*Backtrace*' buffer because it enables you to track Emacs backwards.
872
873 At the top of the `*Backtrace*' buffer, you see the line:
874
875 Debugger entered--Lisp error: (void-function this)
876
877 The Lisp interpreter tried to evaluate the first atom of the list, the
878 word `this'. It is this action that generated the error message
879 `void-function this'.
880
881 The message contains the words `void-function' and `this'.
882
883 The word `function' was mentioned once before. It is a very
884 important 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
886 computer to do something.
887
888 Now we can begin to understand the error message: `void-function
889 this'. The function (that is, the word `this') does not have a
890 definition of any set of instructions for the computer to carry out.
891
892 The slightly odd word, `void-function', is designed to cover the way
893 Emacs Lisp is implemented, which is that when a symbol does not have
894 a function definition attached to it, the place that should contain
895 the instructions is `void'.
896
897 On the other hand, since we were able to add 2 plus 2 successfully, by
898 evaluating `(+ 2 2)', we can infer that the symbol `+' must have a
899 set of instructions for the computer to obey and those instructions
900 must be to add the numbers that follow the `+'.
901
902 In GNU Emacs version 20, and in earlier versions, you will see only
903 one line of error message; it will appear in the echo area and look
904 like 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
909 blink. This is just a device to get your attention.) The message
910 goes away as soon as you type another key, even just to move the
911 cursor.
912
913 We know the meaning of the word `Symbol'. It refers to the first
914 atom of the list, the word `this'. The word `function' refers to the
915 instructions that tell the computer what to do. (Technically, the
916 symbol tells the computer where to find the instructions, but this is
917 a complication we can ignore for the moment.)
918
919 The error message can be understood: `Symbol's function definition is
920 void: this'. The symbol (that is, the word `this') lacks
921 instructions for the computer to carry out.
922
923 Symbol Names and Function Definitions
924 =====================================
925
926 We can articulate another characteristic of Lisp based on what we have
927 discussed so far--an important characteristic: a symbol, like `+', is
928 not itself the set of instructions for the computer to carry out.
929 Instead, the symbol is used, perhaps temporarily, as a way of
930 locating the definition or set of instructions. What we see is the
931 name through which the instructions can be found. Names of people
932 work the same way. I can be referred to as `Bob'; however, I am not
933 the letters `B', `o', `b' but am the consciousness consistently
934 associated with a particular life-form. The name is not me, but it
935 can be used to refer to me.
936
937 In Lisp, one set of instructions can be attached to several names.
938 For example, the computer instructions for adding numbers can be
939 linked to the symbol `plus' as well as to the symbol `+' (and are in
940 some dialects of Lisp). Among humans, I can be referred to as
941 `Robert' as well as `Bob' and by other words as well.
942
943 On the other hand, a symbol can have only one function definition
944 attached to it at a time. Otherwise, the computer would be confused
945 as to which definition to use. If this were the case among people,
946 only one person in the world could be named `Bob'. However, the
947 function definition to which the name refers can be changed readily.
948 (*Note Install a Function Definition: Install.)
949
950 Since Emacs Lisp is large, it is customary to name symbols in a way
951 that identifies the part of Emacs to which the function belongs.
952 Thus, all the names for functions that deal with Texinfo start with
953 `texinfo-' and those for functions that deal with reading mail start
954 with `rmail-'.
955
956 The Lisp Interpreter
957 ====================
958
959 Based on what we have seen, we can now start to figure out what the
960 Lisp interpreter does when we command it to evaluate a list. First,
961 it looks to see whether there is a quote before the list; if there
962 is, the interpreter just gives us the list. On the other hand, if
963 there is no quote, the interpreter looks at the first element in the
964 list and sees whether it has a function definition. If it does, the
965 interpreter carries out the instructions in the function definition.
966 Otherwise, the interpreter prints an error message.
967
968 This is how Lisp works. Simple. There are added complications which
969 we will get to in a minute, but these are the fundamentals. Of
970 course, to write Lisp programs, you need to know how to write
971 function definitions and attach them to names, and how to do this
972 without confusing either yourself or the computer.
973
974 Complications
975 -------------
976
977 Now, for the first complication. In addition to lists, the Lisp
978 interpreter can evaluate a symbol that is not quoted and does not have
979 parentheses around it. The Lisp interpreter will attempt to determine
980 the symbol's value as a "variable". This situation is described in
981 the section on variables. (*Note Variables::.)
982
983 The second complication occurs because some functions are unusual and
984 do not work in the usual manner. Those that don't are called "special
985 forms". They are used for special jobs, like defining a function, and
986 there are not many of them. In the next few chapters, you will be
987 introduced to several of the more important special forms.
988
989 The third and final complication is this: if the function that the
990 Lisp interpreter is looking at is not a special form, and if it is
991 part of a list, the Lisp interpreter looks to see whether the list
992 has a list inside of it. If there is an inner list, the Lisp
993 interpreter first figures out what it should do with the inside list,
994 and then it works on the outside list. If there is yet another list
995 embedded inside the inner list, it works on that one first, and so
996 on. It always works on the innermost list first. The interpreter
997 works on the innermost list first, to evaluate the result of that
998 list. The result may be used by the enclosing expression.
999
1000 Otherwise, the interpreter works left to right, from one expression to
1001 the next.
1002
1003 Byte Compiling
1004 --------------
1005
1006 One other aspect of interpreting: the Lisp interpreter is able to
1007 interpret two kinds of entity: humanly readable code, on which we will
1008 focus exclusively, and specially processed code, called "byte
1009 compiled" code, which is not humanly readable. Byte compiled code
1010 runs faster than humanly readable code.
1011
1012 You can transform humanly readable code into byte compiled code by
1013 running one of the compile commands such as `byte-compile-file'.
1014 Byte compiled code is usually stored in a file that ends with a
1015 `.elc' extension rather than a `.el' extension. You will see both
1016 kinds of file in the `emacs/lisp' directory; the files to read are
1017 those with `.el' extensions.
1018
1019 As a practical matter, for most things you might do to customize or
1020 extend Emacs, you do not need to byte compile; and I will not discuss
1021 the topic here. *Note Byte Compilation: (elisp)Byte Compilation, for
1022 a full description of byte compilation.
1023
1024 Evaluation
1025 ==========
1026
1027 When the Lisp interpreter works on an expression, the term for the
1028 activity is called "evaluation". We say that the interpreter
1029 `evaluates the expression'. I've used this term several times before.
1030 The word comes from its use in everyday language, `to ascertain the
1031 value or amount of; to appraise', according to `Webster's New
1032 Collegiate Dictionary'.
1033
1034 After evaluating an expression, the Lisp interpreter will most likely
1035 "return" the value that the computer produces by carrying out the
1036 instructions it found in the function definition, or perhaps it will
1037 give up on that function and produce an error message. (The
1038 interpreter may also find itself tossed, so to speak, to a different
1039 function or it may attempt to repeat continually what it is doing for
1040 ever and ever in what is called an `infinite loop'. These actions
1041 are less common; and we can ignore them.) Most frequently, the
1042 interpreter returns a value.
1043
1044 At the same time the interpreter returns a value, it may do something
1045 else as well, such as move a cursor or copy a file; this other kind of
1046 action is called a "side effect". Actions that we humans think are
1047 important, such as printing results, are often "side effects" to the
1048 Lisp interpreter. The jargon can sound peculiar, but it turns out
1049 that it is fairly easy to learn to use side effects.
1050
1051 In summary, evaluating a symbolic expression most commonly causes the
1052 Lisp interpreter to return a value and perhaps carry out a side
1053 effect; or else produce an error.
1054
1055 Evaluating Inner Lists
1056 ----------------------
1057
1058 If evaluation applies to a list that is inside another list, the outer
1059 list may use the value returned by the first evaluation as information
1060 when the outer list is evaluated. This explains why inner expressions
1061 are evaluated first: the values they return are used by the outer
1062 expressions.
1063
1064 We can investigate this process by evaluating another addition
1065 example. Place your cursor after the following expression and type
1066 `C-x C-e':
1067
1068 (+ 2 (+ 3 3))
1069
1070 The number 8 will appear in the echo area.
1071
1072 What happens is that the Lisp interpreter first evaluates the inner
1073 expression, `(+ 3 3)', for which the value 6 is returned; then it
1074 evaluates the outer expression as if it were written `(+ 2 6)', which
1075 returns the value 8. Since there are no more enclosing expressions to
1076 evaluate, the interpreter prints that value in the echo area.
1077
1078 Now it is easy to understand the name of the command invoked by the
1079 keystrokes `C-x C-e': the name is `eval-last-sexp'. The letters
1080 `sexp' are an abbreviation for `symbolic expression', and `eval' is
1081 an abbreviation for `evaluate'. The command means `evaluate last
1082 symbolic expression'.
1083
1084 As an experiment, you can try evaluating the expression by putting the
1085 cursor at the beginning of the next line immediately following the
1086 expression, or inside the expression.
1087
1088 Here is another copy of the expression:
1089
1090 (+ 2 (+ 3 3))
1091
1092 If you place the cursor at the beginning of the blank line that
1093 immediately follows the expression and type `C-x C-e', you will still
1094 get the value 8 printed in the echo area. Now try putting the cursor
1095 inside the expression. If you put it right after the next to last
1096 parenthesis (so it appears to sit on top of the last parenthesis),
1097 you will get a 6 printed in the echo area! This is because the
1098 command evaluates the expression `(+ 3 3)'.
1099
1100 Now put the cursor immediately after a number. Type `C-x C-e' and
1101 you will get the number itself. In Lisp, if you evaluate a number,
1102 you get the number itself--this is how numbers differ from symbols.
1103 If you evaluate a list starting with a symbol like `+', you will get a
1104 value returned that is the result of the computer carrying out the
1105 instructions in the function definition attached to that name. If a
1106 symbol by itself is evaluated, something different happens, as we will
1107 see in the next section.
1108
1109 Variables
1110 =========
1111
1112 In Emacs Lisp, a symbol can have a value attached to it just as it can
1113 have a function definition attached to it. The two are different.
1114 The function definition is a set of instructions that a computer will
1115 obey. A value, on the other hand, is something, such as number or a
1116 name, that can vary (which is why such a symbol is called a variable).
1117 The value of a symbol can be any expression in Lisp, such as a symbol,
1118 number, list, or string. A symbol that has a value is often called a
1119 "variable".
1120
1121 A symbol can have both a function definition and a value attached to
1122 it at the same time. Or it can have just one or the other. The two
1123 are separate. This is somewhat similar to the way the name Cambridge
1124 can refer to the city in Massachusetts and have some information
1125 attached to the name as well, such as "great programming center".
1126
1127 Another way to think about this is to imagine a symbol as being a
1128 chest of drawers. The function definition is put in one drawer, the
1129 value in another, and so on. What is put in the drawer holding the
1130 value can be changed without affecting the contents of the drawer
1131 holding the function definition, and vice-versa.
1132
1133 `fill-column', an Example Variable
1134 ----------------------------------
1135
1136 The variable `fill-column' illustrates a symbol with a value attached
1137 to it: in every GNU Emacs buffer, this symbol is set to some value,
1138 usually 72 or 70, but sometimes to some other value. To find the
1139 value of this symbol, evaluate it by itself. If you are reading this
1140 in Info inside of GNU Emacs, you can do this by putting the cursor
1141 after the symbol and typing `C-x C-e':
1142
1143 fill-column
1144
1145 After I typed `C-x C-e', Emacs printed the number 72 in my echo area.
1146 This is the value for which `fill-column' is set for me as I write
1147 this. It may be different for you in your Info buffer. Notice that
1148 the value returned as a variable is printed in exactly the same way
1149 as the value returned by a function carrying out its instructions.
1150 From the point of view of the Lisp interpreter, a value returned is a
1151 value returned. What kind of expression it came from ceases to
1152 matter once the value is known.
1153
1154 A symbol can have any value attached to it or, to use the jargon, we
1155 can "bind" the variable to a value: to a number, such as 72; to a
1156 string, `"such as this"'; to a list, such as `(spruce pine oak)'; we
1157 can even bind a variable to a function definition.
1158
1159 A symbol can be bound to a value in several ways. *Note Setting the
1160 Value of a Variable: set & setq, for information about one way to do
1161 this.
1162
1163 Error Message for a Symbol Without a Function
1164 ---------------------------------------------
1165
1166 When we evaluated `fill-column' to find its value as a variable, we
1167 did not place parentheses around the word. This is because we did
1168 not intend to use it as a function name.
1169
1170 If `fill-column' were the first or only element of a list, the Lisp
1171 interpreter would attempt to find the function definition attached to
1172 it. But `fill-column' has no function definition. Try evaluating
1173 this:
1174
1175 (fill-column)
1176
1177 In GNU Emacs version 21, you will create a `*Backtrace*' buffer that
1178 says:
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,
1190 type `q' in the `*Backtrace*' buffer.)
1191
1192 In GNU Emacs 20 and before, you will produce an error message that
1193 says:
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
1198 another key.)
1199
1200 Error Message for a Symbol Without a Value
1201 ------------------------------------------
1202
1203 If you attempt to evaluate a symbol that does not have a value bound
1204 to it, you will receive an error message. You can see this by
1205 experimenting with our 2 plus 2 addition. In the following
1206 expression, put your cursor right after the `+', before the first
1207 number 2, type `C-x C-e':
1208
1209 (+ 2 2)
1210
1211 In 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
1222 typing `q' in the `*Backtrace*' buffer.)
1223
1224 This backtrace is different from the very first error message we saw,
1225 which said, `Debugger entered--Lisp error: (void-function this)'. In
1226 this case, the function does not have a value as a variable; while in
1227 the other error message, the function (the word `this') did not have
1228 a definition.
1229
1230 In this experiment with the `+', what we did was cause the Lisp
1231 interpreter to evaluate the `+' and look for the value of the
1232 variable instead of the function definition. We did this by placing
1233 the cursor right after the symbol rather than after the parenthesis
1234 of the enclosing list as we did before. As a consequence, the Lisp
1235 interpreter evaluated the preceding s-expression, which in this case
1236 was the `+' by itself.
1237
1238 Since `+' does not have a value bound to it, just the function
1239 definition, the error message reported that the symbol's value as a
1240 variable was void.
1241
1242 In GNU Emacs version 20 and before, your error message will say:
1243
1244 Symbol's value as variable is void: +
1245
1246 The meaning is the same as in GNU Emacs 21.
1247
1248 Arguments
1249 =========
1250
1251 To see how information is passed to functions, let's look again at
1252 our old standby, the addition of two plus two. In Lisp, this is
1253 written as follows:
1254
1255 (+ 2 2)
1256
1257 If you evaluate this expression, the number 4 will appear in your echo
1258 area. What the Lisp interpreter does is add the numbers that follow
1259 the `+'.
1260
1261 The numbers added by `+' are called the "arguments" of the function
1262 `+'. These numbers are the information that is given to or "passed"
1263 to the function.
1264
1265 The word `argument' comes from the way it is used in mathematics and
1266 does not refer to a disputation between two people; instead it refers
1267 to the information presented to the function, in this case, to the
1268 `+'. In Lisp, the arguments to a function are the atoms or lists
1269 that follow the function. The values returned by the evaluation of
1270 these atoms or lists are passed to the function. Different functions
1271 require different numbers of arguments; some functions require none at
1272 all.(1)
1273
1274 ---------- Footnotes ----------
1275
1276 (1) It is curious to track the path by which the word `argument' came
1277 to have two different meanings, one in mathematics and the other in
1278 everyday English. According to the `Oxford English Dictionary', the
1279 word derives from the Latin for `to make clear, prove'; thus it came
1280 to mean, by one thread of derivation, `the evidence offered as
1281 proof', which is to say, `the information offered', which led to its
1282 meaning in Lisp. But in the other thread of derivation, it came to
1283 mean `to assert in a manner against which others may make counter
1284 assertions', which led to the meaning of the word as a disputation.
1285 (Note here that the English word has two different definitions
1286 attached to it at the same time. By contrast, in Emacs Lisp, a
1287 symbol cannot have two different function definitions at the same
1288 time.)
1289
1290 Arguments' Data Types
1291 ---------------------
1292
1293 The type of data that should be passed to a function depends on what
1294 kind of information it uses. The arguments to a function such as `+'
1295 must have values that are numbers, since `+' adds numbers. Other
1296 functions use different kinds of data for their arguments.
1297
1298 For example, the `concat' function links together or unites two or
1299 more strings of text to produce a string. The arguments are strings.
1300 Concatenating the two character strings `abc', `def' produces the
1301 single string `abcdef'. This can be seen by evaluating the following:
1302
1303 (concat "abc" "def")
1304
1305 The value produced by evaluating this expression is `"abcdef"'.
1306
1307 A function such as `substring' uses both a string and numbers as
1308 arguments. The function returns a part of the string, a substring of
1309 the first argument. This function takes three arguments. Its first
1310 argument is the string of characters, the second and third arguments
1311 are numbers that indicate the beginning and end of the substring. The
1312 numbers are a count of the number of characters (including spaces and
1313 punctuations) from the beginning of the string.
1314
1315 For example, if you evaluate the following:
1316
1317 (substring "The quick brown fox jumped." 16 19)
1318
1319 you will see `"fox"' appear in the echo area. The arguments are the
1320 string and the two numbers.
1321
1322 Note that the string passed to `substring' is a single atom even
1323 though it is made up of several words separated by spaces. Lisp
1324 counts everything between the two quotation marks as part of the
1325 string, including the spaces. You can think of the `substring'
1326 function as a kind of `atom smasher' since it takes an otherwise
1327 indivisible atom and extracts a part. However, `substring' is only
1328 able to extract a substring from an argument that is a string, not
1329 from another type of atom such as a number or symbol.
1330
1331 An Argument as the Value of a Variable or List
1332 ----------------------------------------------
1333
1334 An argument can be a symbol that returns a value when it is evaluated.
1335 For example, when the symbol `fill-column' by itself is evaluated, it
1336 returns a number. This number can be used in an addition.
1337
1338 Position the cursor after the following expression and type `C-x C-e':
1339
1340 (+ 2 fill-column)
1341
1342 The 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
1346 As we have just seen, an argument can be a symbol that returns a value
1347 when evaluated. In addition, an argument can be a list that returns a
1348 value when it is evaluated. For example, in the following expression,
1349 the 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
1354 If you evaluate this expression--and if, as with my Emacs,
1355 `fill-column' evaluates to 72--`"The 74 red foxes."' will appear in
1356 the echo area. (Note that you must put spaces after the word `The'
1357 and before the word `red' so they will appear in the final string.
1358 The function `number-to-string' converts the integer that the
1359 addition function returns to a string. `number-to-string' is also
1360 known as `int-to-string'.)
1361
1362 Variable Number of Arguments
1363 ----------------------------
1364
1365 Some functions, such as `concat', `+' or `*', take any number of
1366 arguments. (The `*' is the symbol for multiplication.) This can be
1367 seen by evaluating each of the following expressions in the usual
1368 way. What you will see in the echo area is printed in this text
1369 after `=>', which you may read as `evaluates to'.
1370
1371 In the first set, the functions have no arguments:
1372
1373 (+) => 0
1374
1375 (*) => 1
1376
1377 In this set, the functions have one argument each:
1378
1379 (+ 3) => 3
1380
1381 (* 3) => 3
1382
1383 In this set, the functions have three arguments each:
1384
1385 (+ 3 4 5) => 12
1386
1387 (* 3 4 5) => 60
1388
1389 Using the Wrong Type Object as an Argument
1390 ------------------------------------------
1391
1392 When a function is passed an argument of the wrong type, the Lisp
1393 interpreter produces an error message. For example, the `+' function
1394 expects the values of its arguments to be numbers. As an experiment
1395 we can pass it the quoted symbol `hello' instead of a number.
1396 Position the cursor after the following expression and type `C-x C-e':
1397
1398 (+ 2 'hello)
1399
1400 When you do this you will generate an error message. What has
1401 happened 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',
1403 not a number. Only numbers can be added. So `+' could not carry out
1404 its addition.
1405
1406 In GNU Emacs version 21, you will create and enter a `*Backtrace*'
1407 buffer 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
1419 As usual, the error message tries to be helpful and makes sense after
1420 you learn how to read it.
1421
1422 The 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
1425 argument the `+' expected.
1426
1427 The symbol `number-or-marker-p' says that the Lisp interpreter is
1428 trying to determine whether the information presented it (the value of
1429 the argument) is a number or a marker (a special object representing a
1430 buffer position). What it does is test to see whether the `+' is
1431 being given numbers to add. It also tests to see whether the
1432 argument is something called a marker, which is a specific feature of
1433 Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
1434 When the mark is set with the `C-@' or `C-<SPC>' command, its
1435 position is kept as a marker. The mark can be considered a
1436 number--the number of characters the location is from the beginning
1437 of the buffer.) In Emacs Lisp, `+' can be used to add the numeric
1438 value of marker positions as numbers.
1439
1440 The `p' of `number-or-marker-p' is the embodiment of a practice
1441 started in the early days of Lisp programming. The `p' stands for
1442 `predicate'. In the jargon used by the early Lisp researchers, a
1443 predicate refers to a function to determine whether some property is
1444 true or false. So the `p' tells us that `number-or-marker-p' is the
1445 name of a function that determines whether it is true or false that
1446 the argument supplied is a number or a marker. Other Lisp symbols
1447 that end in `p' include `zerop', a function that tests whether its
1448 argument has the value of zero, and `listp', a function that tests
1449 whether its argument is a list.
1450
1451 Finally, the last part of the error message is the symbol `hello'.
1452 This is the value of the argument that was passed to `+'. If the
1453 addition had been passed the correct type of object, the value passed
1454 would 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
1457 In GNU Emacs version 20 and before, the echo area displays an error
1458 message that says:
1459
1460 Wrong type argument: number-or-marker-p, hello
1461
1462 This says, in different words, the same as the top line of the
1463 `*Backtrace*' buffer.
1464
1465 The `message' Function
1466 ----------------------
1467
1468 Like `+', the `message' function takes a variable number of
1469 arguments. It is used to send messages to the user and is so useful
1470 that we will describe it here.
1471
1472 A message is printed in the echo area. For example, you can print a
1473 message in your echo area by evaluating the following list:
1474
1475 (message "This message appears in the echo area!")
1476
1477 The whole string between double quotation marks is a single argument
1478 and is printed in toto. (Note that in this example, the message
1479 itself will appear in the echo area within double quotes; that is
1480 because you see the value returned by the `message' function. In
1481 most uses of `message' in programs that you write, the text will be
1482 printed 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
1484 example of this.)
1485
1486 However, 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
1488 argument that follows the string. It evaluates the second argument
1489 and prints the value at the location in the string where the `%s' is.
1490
1491 You can see this by positioning the cursor after the following
1492 expression and typing `C-x C-e':
1493
1494 (message "The name of this buffer is: %s." (buffer-name))
1495
1496 In Info, `"The name of this buffer is: *info*."' will appear in the
1497 echo area. The function `buffer-name' returns the name of the buffer
1498 as a string, which the `message' function inserts in place of `%s'.
1499
1500 To print a value as an integer, use `%d' in the same way as `%s'.
1501 For example, to print a message in the echo area that states the
1502 value of the `fill-column', evaluate the following:
1503
1504 (message "The value of fill-column is %d." fill-column)
1505
1506 On my system, when I evaluate this list, `"The value of fill-column
1507 is 72."' appears in my echo area(1).
1508
1509 If there is more than one `%s' in the quoted string, the value of the
1510 first argument following the quoted string is printed at the location
1511 of the first `%s' and the value of the second argument is printed at
1512 the location of the second `%s', and so on.
1513
1514 For example, if you evaluate the following,
1515
1516 (message "There are %d %s in the office!"
1517 (- fill-column 14) "pink elephants")
1518
1519 a rather whimsical message will appear in your echo area. On my
1520 system it says, `"There are 58 pink elephants in the office!"'.
1521
1522 The expression `(- fill-column 14)' is evaluated and the resulting
1523 number is inserted in place of the `%d'; and the string in double
1524 quotes, `"pink elephants"', is treated as a single argument and
1525 inserted in place of the `%s'. (That is to say, a string between
1526 double quotes evaluates to itself, like a number.)
1527
1528 Finally, here is a somewhat complex example that not only illustrates
1529 the computation of a number, but also shows how you can use an
1530 expression within an expression to generate the text that is
1531 substituted 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
1540 In this example, `message' has three arguments: the string, `"He saw
1541 %d %s"', the expression, `(- fill-column 32)', and the expression
1542 beginning with the function `concat'. The value resulting from the
1543 evaluation of `(- fill-column 32)' is inserted in place of the `%d';
1544 and the value returned by the expression beginning with `concat' is
1545 inserted in place of the `%s'.
1546
1547 When I evaluate the expression, the message `"He saw 38 red foxes
1548 leaping."' appears in my echo area.
1549
1550 ---------- Footnotes ----------
1551
1552 (1) Actually, you can use `%s' to print a number. It is
1553 non-specific. `%d' prints only the part of a number left of a
1554 decimal point, and not anything that is not a number.
1555
1556 Setting the Value of a Variable
1557 ===============================
1558
1559 There are several ways by which a variable can be given a value. One
1560 of 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
1562 this process is to "bind" a variable to a value.)
1563
1564 The following sections not only describe how `set' and `setq' work
1565 but also illustrate how arguments are passed.
1566
1567 Using `set'
1568 -----------
1569
1570 To set the value of the symbol `flowers' to the list `'(rose violet
1571 daisy buttercup)', evaluate the following expression by positioning
1572 the cursor after the expression and typing `C-x C-e'.
1573
1574 (set 'flowers '(rose violet daisy buttercup))
1575
1576 The list `(rose violet daisy buttercup)' will appear in the echo
1577 area. This is what is _returned_ by the `set' function. As a side
1578 effect, the symbol `flowers' is bound to the list ; that is, the
1579 symbol `flowers', which can be viewed as a variable, is given the
1580 list as its value. (This process, by the way, illustrates how a side
1581 effect to the Lisp interpreter, setting the value, can be the primary
1582 effect that we humans are interested in. This is because every Lisp
1583 function must return a value if it does not get an error, but it will
1584 only have a side effect if it is designed to have one.)
1585
1586 After evaluating the `set' expression, you can evaluate the symbol
1587 `flowers' and it will return the value you just set. Here is the
1588 symbol. Place your cursor after it and type `C-x C-e'.
1589
1590 flowers
1591
1592 When you evaluate `flowers', the list `(rose violet daisy buttercup)'
1593 appears in the echo area.
1594
1595 Incidentally, if you evaluate `'flowers', the variable with a quote
1596 in front of it, what you will see in the echo area is the symbol
1597 itself, `flowers'. Here is the quoted symbol, so you can try this:
1598
1599 'flowers
1600
1601 Note also, that when you use `set', you need to quote both arguments
1602 to `set', unless you want them evaluated. Since we do not want
1603 either argument evaluated, neither the variable `flowers' nor the
1604 list `(rose violet daisy buttercup)', both are quoted. (When you use
1605 `set' without quoting its first argument, the first argument is
1606 evaluated before anything else is done. If you did this and
1607 `flowers' did not have a value already, you would get an error
1608 message that the `Symbol's value as variable is void'; on the other
1609 hand, if `flowers' did return a value after it was evaluated, the
1610 `set' would attempt to set the value that was returned. There are
1611 situations where this is the right thing for the function to do; but
1612 such situations are rare.)
1613
1614 Using `setq'
1615 ------------
1616
1617 As a practical matter, you almost always quote the first argument to
1618 `set'. The combination of `set' and a quoted first argument is so
1619 common that it has its own name: the special form `setq'. This
1620 special form is just like `set' except that the first argument is
1621 quoted automatically, so you don't need to type the quote mark
1622 yourself. Also, as an added convenience, `setq' permits you to set
1623 several different variables to different values, all in one
1624 expression.
1625
1626 To set the value of the variable `carnivores' to the list `'(lion
1627 tiger leopard)' using `setq', the following expression is used:
1628
1629 (setq carnivores '(lion tiger leopard))
1630
1631 This is exactly the same as using `set' except the first argument is
1632 automatically quoted by `setq'. (The `q' in `setq' means `quote'.)
1633
1634 With `set', the expression would look like this:
1635
1636 (set 'carnivores '(lion tiger leopard))
1637
1638 Also, `setq' can be used to assign different values to different
1639 variables. The first argument is bound to the value of the second
1640 argument, the third argument is bound to the value of the fourth
1641 argument, and so on. For example, you could use the following to
1642 assign a list of trees to the symbol `trees' and a list of herbivores
1643 to 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
1649 not have fit on a page; and humans find it easier to read nicely
1650 formatted lists.)
1651
1652 Although I have been using the term `assign', there is another way of
1653 thinking about the workings of `set' and `setq'; and that is to say
1654 that `set' and `setq' make the symbol _point_ to the list. This
1655 latter way of thinking is very common and in forthcoming chapters we
1656 shall come upon at least one symbol that has `pointer' as part of its
1657 name. The name is chosen because the symbol has a value,
1658 specifically a list, attached to it; or, expressed another way, the
1659 symbol is set to "point" to the list.
1660
1661 Counting
1662 --------
1663
1664 Here is an example that shows how to use `setq' in a counter. You
1665 might use this to count how many times a part of your program repeats
1666 itself. First set a variable to zero; then add one to the number each
1667 time the program repeats itself. To do this, you need a variable that
1668 serves as a counter, and two expressions: an initial `setq'
1669 expression that sets the counter variable to zero; and a second
1670 `setq' expression that increments the counter each time it is
1671 evaluated.
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
1680 Definition: Change a defun.)
1681
1682 If 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
1685 evaluate the second expression, the incrementer, `(setq counter (+
1686 counter 1))', the counter will get the value 1. So if you again
1687 evaluate `counter', the number `1' will appear in the echo area.
1688 Each time you evaluate the second expression, the value of the
1689 counter will be incremented.
1690
1691 When you evaluate the incrementer, `(setq counter (+ counter 1))',
1692 the Lisp interpreter first evaluates the innermost list; this is the
1693 addition. In order to evaluate this list, it must evaluate the
1694 variable `counter' and the number `1'. When it evaluates the variable
1695 `counter', it receives its current value. It passes this value and
1696 the number `1' to the `+' which adds them together. The sum is then
1697 returned as the value of the inner list and passed to the `setq'
1698 which sets the variable `counter' to this new value. Thus, the value
1699 of the variable, `counter', is changed.
1700
1701 Summary
1702 =======
1703
1704 Learning Lisp is like climbing a hill in which the first part is the
1705 steepest. You have now climbed the most difficult part; what remains
1706 becomes easier as you progress onwards.
1707
1708 In 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
1746 Exercises
1747 =========
1748
1749 A 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
1762 Practicing Evaluation
1763 *********************
1764
1765 Before learning how to write a function definition in Emacs Lisp, it
1766 is useful to spend a little time evaluating various expressions that
1767 have already been written. These expressions will be lists with the
1768 functions as their first (and often only) element. Since some of the
1769 functions associated with buffers are both simple and interesting, we
1770 will start with those. In this section, we will evaluate a few of
1771 these. In another section, we will study the code of several other
1772 buffer-related functions, to see how they were written.
1773
1774 How to Evaluate
1775 ===============
1776
1777 Whenever you give an editing command to Emacs Lisp, such as the
1778 command to move the cursor or to scroll the screen, you are evaluating
1779 an expression, the first element of which is a function. This is how
1780 Emacs works.
1781
1782 When you type keys, you cause the Lisp interpreter to evaluate an
1783 expression and that is how you get your results. Even typing plain
1784 text involves evaluating an Emacs Lisp function, in this case, one
1785 that uses `self-insert-command', which simply inserts the character
1786 you typed. The functions you evaluate by typing keystrokes are called
1787 "interactive" functions, or "commands"; how you make a function
1788 interactive will be illustrated in the chapter on how to write
1789 function definitions. *Note Making a Function Interactive:
1790 Interactive.
1791
1792 In addition to typing keyboard commands, we have seen a second way to
1793 evaluate an expression: by positioning the cursor after a list and
1794 typing `C-x C-e'. This is what we will do in the rest of this
1795 section. There are other ways to evaluate an expression as well;
1796 these will be described as we come to them.
1797
1798 Besides being used for practicing evaluation, the functions shown in
1799 the next few sections are important in their own right. A study of
1800 these functions makes clear the distinction between buffers and
1801 files, how to switch to a buffer, and how to determine a location
1802 within it.
1803
1804 Buffer Names
1805 ============
1806
1807 The two functions, `buffer-name' and `buffer-file-name', show the
1808 difference between a file and a buffer. When you evaluate the
1809 following expression, `(buffer-name)', the name of the buffer appears
1810 in the echo area. When you evaluate `(buffer-file-name)', the name
1811 of the file to which the buffer refers appears in the echo area.
1812 Usually, the name returned by `(buffer-name)' is the same as the name
1813 of the file to which it refers, and the name returned by
1814 `(buffer-file-name)' is the full path-name of the file.
1815
1816 A file and a buffer are two different entities. A file is information
1817 recorded permanently in the computer (unless you delete it). A
1818 buffer, on the other hand, is information inside of Emacs that will
1819 vanish at the end of the editing session (or when you kill the
1820 buffer). Usually, a buffer contains information that you have copied
1821 from a file; we say the buffer is "visiting" that file. This copy is
1822 what you work on and modify. Changes to the buffer do not change the
1823 file, until you save the buffer. When you save the buffer, the
1824 buffer is copied to the file and is thus saved permanently.
1825
1826 If you are reading this in Info inside of GNU Emacs, you can evaluate
1827 each of the following expressions by positioning the cursor after it
1828 and typing `C-x C-e'.
1829
1830 (buffer-name)
1831
1832 (buffer-file-name)
1833
1834 When I do this, `"introduction.texinfo"' is the value returned by
1835 evaluating `(buffer-name)', and
1836 `"/gnu/work/intro/introduction.texinfo"' is the value returned by
1837 evaluating `(buffer-file-name)'. The former is the name of the
1838 buffer and the latter is the name of the file. (In the expressions,
1839 the parentheses tell the Lisp interpreter to treat `buffer-name' and
1840 `buffer-file-name' as functions; without the parentheses, the
1841 interpreter would attempt to evaluate the symbols as variables.
1842 *Note Variables::.)
1843
1844 In spite of the distinction between files and buffers, you will often
1845 find that people refer to a file when they mean a buffer and
1846 vice-versa. Indeed, most people say, "I am editing a file," rather
1847 than saying, "I am editing a buffer which I will soon save to a
1848 file." It is almost always clear from context what people mean.
1849 When dealing with computer programs, however, it is important to keep
1850 the distinction in mind, since the computer is not as smart as a
1851 person.
1852
1853 The word `buffer', by the way, comes from the meaning of the word as a
1854 cushion that deadens the force of a collision. In early computers, a
1855 buffer cushioned the interaction between files and the computer's
1856 central processing unit. The drums or tapes that held a file and the
1857 central processing unit were pieces of equipment that were very
1858 different from each other, working at their own speeds, in spurts.
1859 The buffer made it possible for them to work together effectively.
1860 Eventually, the buffer grew from being an intermediary, a temporary
1861 holding place, to being the place where work is done. This
1862 transformation is rather like that of a small seaport that grew into a
1863 great city: once it was merely the place where cargo was warehoused
1864 temporarily before being loaded onto ships; then it became a business
1865 and cultural center in its own right.
1866
1867 Not all buffers are associated with files. For example, when you
1868 start an Emacs session by typing the command `emacs' alone, without
1869 naming any files, Emacs will start with the `*scratch*' buffer on the
1870 screen. This buffer is not visiting any file. Similarly, a `*Help*'
1871 buffer is not associated with any file.
1872
1873 If you switch to the `*scratch*' buffer, type `(buffer-name)',
1874 position the cursor after it, and type `C-x C-e' to evaluate the
1875 expression, the name `"*scratch*"' is returned and will appear in the
1876 echo area. `"*scratch*"' is the name of the buffer. However, if you
1877 type `(buffer-file-name)' in the `*scratch*' buffer and evaluate
1878 that, `nil' will appear in the echo area. `nil' is from the Latin
1879 word for `nothing'; in this case, it means that the `*scratch*'
1880 buffer is not associated with any file. (In Lisp, `nil' is also used
1881 to mean `false' and is a synonym for the empty list, `()'.)
1882
1883 Incidentally, if you are in the `*scratch*' buffer and want the value
1884 returned by an expression to appear in the `*scratch*' buffer itself
1885 rather than in the echo area, type `C-u C-x C-e' instead of `C-x
1886 C-e'. This causes the value returned to appear after the expression.
1887 The buffer will look like this:
1888
1889 (buffer-name)"*scratch*"
1890
1891 You cannot do this in Info since Info is read-only and it will not
1892 allow you to change the contents of the buffer. But you can do this
1893 in any buffer you can edit; and when you write code or documentation
1894 (such as this book), this feature is very useful.
1895
1896 Getting Buffers
1897 ===============
1898
1899 The `buffer-name' function returns the _name_ of the buffer; to get
1900 the buffer _itself_, a different function is needed: the
1901 `current-buffer' function. If you use this function in code, what
1902 you get is the buffer itself.
1903
1904 A name and the object or entity to which the name refers are different
1905 from each other. You are not your name. You are a person to whom
1906 others refer by name. If you ask to speak to George and someone
1907 hands you a card with the letters `G', `e', `o', `r', `g', and `e'
1908 written on it, you might be amused, but you would not be satisfied.
1909 You do not want to speak to the name, but to the person to whom the
1910 name 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,
1912 you need to use a function such as `current-buffer'.
1913
1914 However, there is a slight complication: if you evaluate
1915 `current-buffer' in an expression on its own, as we will do here,
1916 what you see is a printed representation of the name of the buffer
1917 without the contents of the buffer. Emacs works this way for two
1918 reasons: the buffer may be thousands of lines long--too long to be
1919 conveniently displayed; and, another buffer may have the same contents
1920 but a different name, and it is important to distinguish between them.
1921
1922 Here is an expression containing the function:
1923
1924 (current-buffer)
1925
1926 If you evaluate the expression in the usual way, `#<buffer *info*>'
1927 appears in the echo area. The special format indicates that the
1928 buffer itself is being returned, rather than just its name.
1929
1930 Incidentally, while you can type a number or symbol into a program,
1931 you cannot do that with the printed representation of a buffer: the
1932 only way to get a buffer itself is with a function such as
1933 `current-buffer'.
1934
1935 A related function is `other-buffer'. This returns the most recently
1936 selected buffer other than the one you are in currently. If you have
1937 recently switched back and forth from the `*scratch*' buffer,
1938 `other-buffer' will return that buffer.
1939
1940 You can see this by evaluating the expression:
1941
1942 (other-buffer)
1943
1944 You should see `#<buffer *scratch*>' appear in the echo area, or the
1945 name 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
1950 is visible to you in another window, `other-buffer' will choose the
1951 most recent buffer that you cannot see; this is a subtlety that I
1952 often forget.
1953
1954 Switching Buffers
1955 =================
1956
1957 The `other-buffer' function actually provides a buffer when it is
1958 used as an argument to a function that requires one. We can see this
1959 by using `other-buffer' and `switch-to-buffer' to switch to a
1960 different buffer.
1961
1962 But first, a brief introduction to the `switch-to-buffer' function.
1963 When you switched back and forth from Info to the `*scratch*' buffer
1964 to evaluate `(buffer-name)', you most likely typed `C-x b' and then
1965 typed `*scratch*'(1) when prompted in the minibuffer for the name of
1966 the buffer to which you wanted to switch. The keystrokes, `C-x b',
1967 cause the Lisp interpreter to evaluate the interactive function
1968 `switch-to-buffer'. As we said before, this is how Emacs works:
1969 different keystrokes call or run different functions. For example,
1970 `C-f' calls `forward-char', `M-e' calls `forward-sentence', and so on.
1971
1972 By writing `switch-to-buffer' in an expression, and giving it a
1973 buffer to switch to, we can switch buffers just the way `C-x b' does.
1974
1975 Here is the Lisp expression:
1976
1977 (switch-to-buffer (other-buffer))
1978
1979 The symbol `switch-to-buffer' is the first element of the list, so
1980 the Lisp interpreter will treat it as a function and carry out the
1981 instructions that are attached to it. But before doing that, the
1982 interpreter will note that `other-buffer' is inside parentheses and
1983 work on that symbol first. `other-buffer' is the first (and in this
1984 case, the only) element of this list, so the Lisp interpreter calls
1985 or runs the function. It returns another buffer. Next, the
1986 interpreter runs `switch-to-buffer', passing to it, as an argument,
1987 the other buffer, which is what Emacs will switch to. If you are
1988 reading this in Info, try this now. Evaluate the expression. (To
1989 get back, type `C-x b <RET>'.)(2)
1990
1991 In the programming examples in later sections of this document, you
1992 will see the function `set-buffer' more often than
1993 `switch-to-buffer'. This is because of a difference between computer
1994 programs and humans: humans have eyes and expect to see the buffer on
1995 which they are working on their computer terminals. This is so
1996 obvious, it almost goes without saying. However, programs do not
1997 have eyes. When a computer program works on a buffer, that buffer
1998 does not need to be visible on the screen.
1999
2000 `switch-to-buffer' is designed for humans and does two different
2001 things: it switches the buffer to which Emacs' attention is directed;
2002 and 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
2004 attention of the computer program to a different buffer. The buffer
2005 on the screen remains unchanged (of course, normally nothing happens
2006 there until the command finishes running).
2007
2008 Also, we have just introduced another jargon term, the word "call".
2009 When you evaluate a list in which the first symbol is a function, you
2010 are calling that function. The use of the term comes from the notion
2011 of 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
2013 call him or her.
2014
2015 ---------- Footnotes ----------
2016
2017 (1) Or rather, to save typing, you probably typed just part of the
2018 name, such as `*sc', and then pressed your `TAB' key to cause it to
2019 expand to the full name; and then typed your `RET' key.
2020
2021 (2) Remember, this expression will move you to your most recent other
2022 buffer that you cannot see. If you really want to go to your most
2023 recently selected buffer, even if you can still see it, you need to
2024 evaluate the following more complex expression:
2025
2026 (switch-to-buffer (other-buffer (current-buffer) t))
2027
2028 In this case, the first argument to `other-buffer' tells it which
2029 buffer to skip--the current one--and the second argument tells
2030 `other-buffer' it is OK to switch to a visible buffer. In regular
2031 use, `switch-to-buffer' takes you to an invisible window since you
2032 would most likely use `C-x o' (`other-window') to go to another
2033 visible buffer.
2034
2035 Buffer Size and the Location of Point
2036 =====================================
2037
2038 Finally, let's look at several rather simple functions,
2039 `buffer-size', `point', `point-min', and `point-max'. These give
2040 information about the size of a buffer and the location of point
2041 within it.
2042
2043 The function `buffer-size' tells you the size of the current buffer;
2044 that is, the function returns a count of the number of characters in
2045 the buffer.
2046
2047 (buffer-size)
2048
2049 You can evaluate this in the usual way, by positioning the cursor
2050 after the expression and typing `C-x C-e'.
2051
2052 In Emacs, the current position of the cursor is called "point". The
2053 expression `(point)' returns a number that tells you where the cursor
2054 is located as a count of the number of characters from the beginning
2055 of the buffer up to point.
2056
2057 You can see the character count for point in this buffer by evaluating
2058 the following expression in the usual way:
2059
2060 (point)
2061
2062 As I write this, the value of `point' is 65724. The `point' function
2063 is frequently used in some of the examples later in this book.
2064
2065 The value of point depends, of course, on its location within the
2066 buffer. If you evaluate point in this spot, the number will be
2067 larger:
2068
2069 (point)
2070
2071 For me, the value of point in this location is 66043, which means that
2072 there are 319 characters (including spaces) between the two
2073 expressions.
2074
2075 The function `point-min' is somewhat similar to `point', but it
2076 returns the value of the minimum permissible value of point in the
2077 current buffer. This is the number 1 unless "narrowing" is in
2078 effect. (Narrowing is a mechanism whereby you can restrict yourself,
2079 or a program, to operations on just a part of a buffer. *Note
2080 Narrowing and Widening: Narrowing & Widening.) Likewise, the
2081 function `point-max' returns the value of the maximum permissible
2082 value of point in the current buffer.
2083
2084 Exercise
2085 ========
2086
2087 Find a file with which you are working and move towards its middle.
2088 Find its buffer name, file name, length, and your position in the
2089 file.
2090
2091 How To Write Function Definitions
2092 *********************************
2093
2094 When the Lisp interpreter evaluates a list, it looks to see whether
2095 the first symbol on the list has a function definition attached to
2096 it; or, put another way, whether the symbol points to a function
2097 definition. If it does, the computer carries out the instructions in
2098 the definition. A symbol that has a function definition is called,
2099 simply, a function (although, properly speaking, the definition is
2100 the function and the symbol refers to it.)
2101
2102 An Aside about Primitive Functions
2103 ==================================
2104
2105 All functions are defined in terms of other functions, except for a
2106 few "primitive" functions that are written in the C programming
2107 language. When you write functions' definitions, you will write them
2108 in Emacs Lisp and use other functions as your building blocks. Some
2109 of the functions you will use will themselves be written in Emacs
2110 Lisp (perhaps by you) and some will be primitives written in C. The
2111 primitive functions are used exactly like those written in Emacs Lisp
2112 and behave like them. They are written in C so we can easily run GNU
2113 Emacs on any computer that has sufficient power and can run C.
2114
2115 Let me re-emphasize this: when you write code in Emacs Lisp, you do
2116 not distinguish between the use of functions written in C and the use
2117 of functions written in Emacs Lisp. The difference is irrelevant. I
2118 mention the distinction only because it is interesting to know.
2119 Indeed, unless you investigate, you won't know whether an
2120 already-written function is written in Emacs Lisp or C.
2121
2122 The `defun' Special Form
2123 ========================
2124
2125 In Lisp, a symbol such as `mark-whole-buffer' has code attached to it
2126 that tells the computer what to do when the function is called. This
2127 code is called the "function definition" and is created by evaluating
2128 a Lisp expression that starts with the symbol `defun' (which is an
2129 abbreviation for _define function_). Because `defun' does not
2130 evaluate its arguments in the usual way, it is called a "special
2131 form".
2132
2133 In subsequent sections, we will look at function definitions from the
2134 Emacs source code, such as `mark-whole-buffer'. In this section, we
2135 will describe a simple function definition so you can see how it
2136 looks. This function definition uses arithmetic because it makes for
2137 a simple example. Some people dislike examples using arithmetic;
2138 however, if you are such a person, do not despair. Hardly any of the
2139 code we will study in the remainder of this introduction involves
2140 arithmetic or mathematics. The examples mostly involve text in one
2141 way or another.
2142
2143 A 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
2162 It is helpful to think of the five parts of a function definition as
2163 being 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
2170 As an example, here is the code for a function that multiplies its
2171 argument by 7. (This example is not interactive. *Note Making a
2172 Function Interactive: Interactive, for that information.)
2173
2174 (defun multiply-by-seven (number)
2175 "Multiply NUMBER by seven."
2176 (* 7 number))
2177
2178 This definition begins with a parenthesis and the symbol `defun',
2179 followed by the name of the function.
2180
2181 The name of the function is followed by a list that contains the
2182 arguments that will be passed to the function. This list is called
2183 the "argument list". In this example, the list has only one element,
2184 the symbol, `number'. When the function is used, the symbol will be
2185 bound to the value that is used as the argument to the function.
2186
2187 Instead of choosing the word `number' for the name of the argument, I
2188 could have picked any other name. For example, I could have chosen
2189 the word `multiplicand'. I picked the word `number' because it tells
2190 what kind of value is intended for this slot; but I could just as
2191 well have chosen the word `multiplicand' to indicate the role that the
2192 value placed in this slot will play in the workings of the function.
2193 I could have called it `foogle', but that would have been a bad
2194 choice because it would not tell humans what it means. The choice of
2195 name is up to the programmer and should be chosen to make the meaning
2196 of the function clear.
2197
2198 Indeed, you can choose any name you wish for a symbol in an argument
2199 list, even the name of a symbol used in some other function: the name
2200 you use in an argument list is private to that particular definition.
2201 In that definition, the name refers to a different entity than any use
2202 of the same name outside the function definition. Suppose you have a
2203 nick-name `Shorty' in your family; when your family members refer to
2204 `Shorty', they mean you. But outside your family, in a movie, for
2205 example, the name `Shorty' refers to someone else. Because a name in
2206 an argument list is private to the function definition, you can
2207 change the value of such a symbol inside the body of a function
2208 without changing its value outside the function. The effect is
2209 similar to that produced by a `let' expression. (*Note `let': let.)
2210
2211 The argument list is followed by the documentation string that
2212 describes the function. This is what you see when you type `C-h f'
2213 and the name of a function. Incidentally, when you write a
2214 documentation string like this, you should make the first line a
2215 complete sentence since some commands, such as `apropos', print only
2216 the first line of a multi-line documentation string. Also, you
2217 should not indent the second line of a documentation string, if you
2218 have one, because that looks odd when you use `C-h f'
2219 (`describe-function'). The documentation string is optional, but it
2220 is so useful, it should be included in almost every function you
2221 write.
2222
2223 The third line of the example consists of the body of the function
2224 definition. (Most functions' definitions, of course, are longer than
2225 this.) In this function, the body is the list, `(* 7 number)', which
2226 says to multiply the value of NUMBER by 7. (In Emacs Lisp, `*' is
2227 the function for multiplication, just as `+' is the function for
2228 addition.)
2229
2230 When you use the `multiply-by-seven' function, the argument `number'
2231 evaluates to the actual number you want used. Here is an example
2232 that shows how `multiply-by-seven' is used; but don't try to evaluate
2233 this yet!
2234
2235 (multiply-by-seven 3)
2236
2237 The symbol `number', specified in the function definition in the next
2238 section, is given or "bound to" the value 3 in the actual use of the
2239 function. Note that although `number' was inside parentheses in the
2240 function definition, the argument passed to the `multiply-by-seven'
2241 function is not in parentheses. The parentheses are written in the
2242 function definition so the computer can figure out where the argument
2243 list ends and the rest of the function definition begins.
2244
2245 If 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
2247 definition, but not yet told the computer about the definition--we
2248 have not yet installed (or `loaded') the function definition in Emacs.
2249 Installing a function is the process that tells the Lisp interpreter
2250 the definition of the function. Installation is described in the next
2251 section.
2252
2253 Install a Function Definition
2254 =============================
2255
2256 If you are reading this inside of Info in Emacs, you can try out the
2257 `multiply-by-seven' function by first evaluating the function
2258 definition and then evaluating `(multiply-by-seven 3)'. A copy of
2259 the function definition follows. Place the cursor after the last
2260 parenthesis of the function definition and type `C-x C-e'. When you
2261 do this, `multiply-by-seven' will appear in the echo area. (What
2262 this means is that when a function definition is evaluated, the value
2263 it returns is the name of the defined function.) At the same time,
2264 this action installs the function definition.
2265
2266 (defun multiply-by-seven (number)
2267 "Multiply NUMBER by seven."
2268 (* 7 number))
2269
2270 By evaluating this `defun', you have just installed
2271 `multiply-by-seven' in Emacs. The function is now just as much a
2272 part of Emacs as `forward-word' or any other editing function you
2273 use. (`multiply-by-seven' will stay installed until you quit Emacs.
2274 To reload code automatically whenever you start Emacs, see *Note
2275 Installing Code Permanently: Permanent Installation.)
2276
2277 The effect of installation
2278 --------------------------
2279
2280 You can see the effect of installing `multiply-by-seven' by
2281 evaluating the following sample. Place the cursor after the following
2282 expression and type `C-x C-e'. The number 21 will appear in the echo
2283 area.
2284
2285 (multiply-by-seven 3)
2286
2287 If 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
2290 on 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
2297 Change a Function Definition
2298 ----------------------------
2299
2300 If you want to change the code in `multiply-by-seven', just rewrite
2301 it. To install the new version in place of the old one, evaluate the
2302 function definition again. This is how you modify code in Emacs. It
2303 is very simple.
2304
2305 As an example, you can change the `multiply-by-seven' function to add
2306 the number to itself seven times instead of multiplying the number by
2307 seven. It produces the same answer, but by a different path. At the
2308 same time, we will add a comment to the code; a comment is text that
2309 the Lisp interpreter ignores, but that a human reader may find useful
2310 or 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
2316 The comment follows a semicolon, `;'. In Lisp, everything on a line
2317 that follows a semicolon is a comment. The end of the line is the
2318 end of the comment. To stretch a comment over two or more lines,
2319 begin each line with a semicolon.
2320
2321 *Note Beginning a `.emacs' File: Beginning a .emacs File, and *Note
2322 Comments: (elisp)Comments, for more about comments.
2323
2324 You can install this version of the `multiply-by-seven' function by
2325 evaluating it in the same way you evaluated the first function: place
2326 the cursor after the last parenthesis and type `C-x C-e'.
2327
2328 In summary, this is how you write code in Emacs Lisp: you write a
2329 function; install it; test it; and then make fixes or enhancements and
2330 install it again.
2331
2332 Make a Function Interactive
2333 ===========================
2334
2335 You make a function interactive by placing a list that begins with
2336 the special form `interactive' immediately after the documentation.
2337 A user can invoke an interactive function by typing `M-x' and then
2338 the name of the function; or by typing the keys to which it is bound,
2339 for example, by typing `C-n' for `next-line' or `C-x h' for
2340 `mark-whole-buffer'.
2341
2342 Interestingly, when you call an interactive function interactively,
2343 the value returned is not automatically displayed in the echo area.
2344 This is because you often call an interactive function for its side
2345 effects, such as moving forward by a word or line, and not for the
2346 value returned. If the returned value were displayed in the echo area
2347 each time you typed a key, it would be very distracting.
2348
2349 An Interactive `multiply-by-seven', An Overview
2350 -----------------------------------------------
2351
2352 Both the use of the special form `interactive' and one way to display
2353 a value in the echo area can be illustrated by creating an
2354 interactive version of `multiply-by-seven'.
2355
2356 Here 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
2363 You 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.
2365 Then, you can use this code by typing `C-u' and a number and then
2366 typing `M-x multiply-by-seven' and pressing <RET>. The phrase `The
2367 result is ...' followed by the product will appear in the echo area.
2368
2369 Speaking more generally, you invoke a function like this in either of
2370 two 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
2379 Both the examples just mentioned work identically to move point
2380 forward three sentences. (Since `multiply-by-seven' is not bound to
2381 a 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
2384 to a key.)
2385
2386 A 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'
2389 without a number, it defaults to 4).
2390
2391 An Interactive `multiply-by-seven'
2392 ----------------------------------
2393
2394 Let's look at the use of the special form `interactive' and then at
2395 the function `message' in the interactive version of
2396 `multiply-by-seven'. You will recall that the function definition
2397 looks 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
2404 In this function, the expression, `(interactive "p")', is a list of
2405 two elements. The `"p"' tells Emacs to pass the prefix argument to
2406 the function and use its value for the argument of the function.
2407
2408 The argument will be a number. This means that the symbol `number'
2409 will be bound to a number in the line:
2410
2411 (message "The result is %d" (* 7 number))
2412
2413 For example, if your prefix argument is 5, the Lisp interpreter will
2414 evaluate 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
2419 expression yourself.) First, the interpreter will evaluate the inner
2420 list, which is `(* 7 5)'. This returns a value of 35. Next, it will
2421 evaluate the outer list, passing the values of the second and
2422 subsequent elements of the list to the function `message'.
2423
2424 As we have seen, `message' is an Emacs Lisp function especially
2425 designed for sending a one line message to a user. (*Note The
2426 `message' function: message.) In summary, the `message' function
2427 prints its first argument in the echo area as is, except for
2428 occurrences of `%d', `%s', or `%c'. When it sees one of these
2429 control sequences, the function looks to the second and subsequent
2430 arguments and prints the value of the argument in the location in the
2431 string where the control sequence is located.
2432
2433 In the interactive `multiply-by-seven' function, the control string
2434 is `%d', which requires a number, and the value returned by
2435 evaluating `(* 7 5)' is the number 35. Consequently, the number 35
2436 is 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
2439 message is printed without quotes, but when you call `message', the
2440 text is printed in double quotes. This is because the value returned
2441 by `message' is what appears in the echo area when you evaluate an
2442 expression whose first element is `message'; but when embedded in a
2443 function, `message' prints the text as a side effect without quotes.)
2444
2445 Different Options for `interactive'
2446 ===================================
2447
2448 In the example, `multiply-by-seven' used `"p"' as the argument to
2449 `interactive'. This argument told Emacs to interpret your typing
2450 either `C-u' followed by a number or <META> followed by a number as a
2451 command to pass that number to the function as its argument. Emacs
2452 has more than twenty characters predefined for use with
2453 `interactive'. In almost every case, one of these options will
2454 enable you to pass the right information interactively to a function.
2455 (*Note Code Characters for `interactive': (elisp)Interactive Codes.)
2456
2457 For example, the character `r' causes Emacs to pass the beginning and
2458 end of the region (the current values of point and mark) to the
2459 function as two separate arguments. It is used as follows:
2460
2461 (interactive "r")
2462
2463 On the other hand, a `B' tells Emacs to ask for the name of a buffer
2464 that will be passed to the function. When it sees a `B', Emacs will
2465 ask for the name by prompting the user in the minibuffer, using a
2466 string that follows the `B', as in `"BAppend to buffer: "'. Not only
2467 will Emacs prompt for the name, but Emacs will complete the name if
2468 you type enough of it and press <TAB>.
2469
2470 A function with two or more arguments can have information passed to
2471 each argument by adding parts to the string that follows
2472 `interactive'. When you do this, the information is passed to each
2473 argument in the same order it is specified in the `interactive' list.
2474 In the string, each part is separated from the next part by a `\n',
2475 which is a newline. For example, you could follow `"BAppend to
2476 buffer: "' with a `\n') and an `r'. This would cause Emacs to pass
2477 the values of point and mark to the function as well as prompt you
2478 for the buffer--three arguments in all.
2479
2480 In this case, the function definition would look like the following,
2481 where `buffer', `start', and `end' are the symbols to which
2482 `interactive' binds the buffer and the current values of the
2483 beginning 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
2491 are prompted. The `append-to-buffer' function looks exactly like
2492 this. *Note The Definition of `append-to-buffer': append-to-buffer.)
2493
2494 If a function does not have arguments, then `interactive' does not
2495 require any. Such a function contains the simple expression
2496 `(interactive)'. The `mark-whole-buffer' function is like this.
2497
2498 Alternatively, if the special letter-codes are not right for your
2499 application, you can pass your own arguments to `interactive' as a
2500 list. *Note Using `Interactive': (elisp)interactive, for more
2501 information about this advanced technique.
2502
2503 Install Code Permanently
2504 ========================
2505
2506 When you install a function definition by evaluating it, it will stay
2507 installed until you quit Emacs. The next time you start a new session
2508 of Emacs, the function will not be installed unless you evaluate the
2509 function definition again.
2510
2511 At some point, you may want to have code installed automatically
2512 whenever you start a new session of Emacs. There are several ways of
2513 doing 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
2532 Finally, if you have code that everyone who uses Emacs may want, you
2533 can post it on a computer network or send a copy to the Free Software
2534 Foundation. (When you do this, please license the code and its
2535 documentation under a license that permits other people to run, copy,
2536 study, modify, and redistribute the code and which protects you from
2537 having your work taken from you.) If you send a copy of your code to
2538 the Free Software Foundation, and properly protect yourself and
2539 others, it may be included in the next release of Emacs. In large
2540 part, this is how Emacs has grown over the past years, by donations.
2541
2542 `let'
2543 =====
2544
2545 The `let' expression is a special form in Lisp that you will need to
2546 use in most function definitions.
2547
2548 `let' is used to attach or bind a symbol to a value in such a way
2549 that the Lisp interpreter will not confuse the variable with a
2550 variable of the same name that is not part of the function.
2551
2552 To understand why the `let' special form is necessary, consider the
2553 situation in which you own a home that you generally refer to as `the
2554 house', as in the sentence, "The house needs painting." If you are
2555 visiting a friend and your host refers to `the house', he is likely
2556 to be referring to _his_ house, not yours, that is, to a different
2557 house.
2558
2559 If your friend is referring to his house and you think he is referring
2560 to your house, you may be in for some confusion. The same thing could
2561 happen in Lisp if a variable that is used inside of one function has
2562 the same name as a variable that is used inside of another function,
2563 and the two are not intended to refer to the same value. The `let'
2564 special form prevents this kind of confusion.
2565
2566 `let' Prevents Confusion
2567 ------------------------
2568
2569 The `let' special form prevents confusion. `let' creates a name for
2570 a "local variable" that overshadows any use of the same name outside
2571 the `let' expression. This is like understanding that whenever your
2572 host refers to `the house', he means his house, not yours. (Symbols
2573 used in argument lists work the same way. *Note The `defun' Special
2574 Form: defun.)
2575
2576 Local variables created by a `let' expression retain their value
2577 _only_ within the `let' expression itself (and within expressions
2578 called within the `let' expression); the local variables have no
2579 effect outside the `let' expression.
2580
2581 Another way to think about `let' is that it is like a `setq' that is
2582 temporary and local. The values set by `let' are automatically
2583 undone when the `let' is finished. The setting only affects
2584 expressions that are inside the bounds of the `let' expression. In
2585 computer science jargon, we would say "the binding of a symbol is
2586 visible only in functions called in the `let' form; in Emacs Lisp,
2587 scoping is dynamic, not lexical."
2588
2589 `let' can create more than one variable at once. Also, `let' gives
2590 each variable it creates an initial value, either a value specified
2591 by you, or `nil'. (In the jargon, this is called `binding the
2592 variable to the value'.) After `let' has created and bound the
2593 variables, it executes the code in the body of the `let', and returns
2594 the value of the last expression in the body, as the value of the
2595 whole `let' expression. (`Execute' is a jargon term that means to
2596 evaluate a list; it comes from the use of the word meaning `to give
2597 practical effect to' (`Oxford English Dictionary'). Since you
2598 evaluate an expression to perform an action, `execute' has evolved as
2599 a synonym to `evaluate'.)
2600
2601 The Parts of a `let' Expression
2602 -------------------------------
2603
2604 A `let' expression is a list of three parts. The first part is the
2605 symbol `let'. The second part is a list, called a "varlist", each
2606 element of which is either a symbol by itself or a two-element list,
2607 the first element of which is a symbol. The third part of the `let'
2608 expression is the body of the `let'. The body usually consists of
2609 one or more lists.
2610
2611 A template for a `let' expression looks like this:
2612
2613 (let VARLIST BODY...)
2614
2615 The symbols in the varlist are the variables that are given initial
2616 values by the `let' special form. Symbols by themselves are given
2617 the initial value of `nil'; and each symbol that is the first element
2618 of a two-element list is bound to the value that is returned when the
2619 Lisp interpreter evaluates the second element.
2620
2621 Thus, a varlist might look like this: `(thread (needles 3))'. In
2622 this case, in a `let' expression, Emacs binds the symbol `thread' to
2623 an initial value of `nil', and binds the symbol `needles' to an
2624 initial value of 3.
2625
2626 When you write a `let' expression, what you do is put the appropriate
2627 expressions in the slots of the `let' expression template.
2628
2629 If the varlist is composed of two-element lists, as is often the case,
2630 the template for the `let' expression looks like this:
2631
2632 (let ((VARIABLE VALUE)
2633 (VARIABLE VALUE)
2634 ...)
2635 BODY...)
2636
2637 Sample `let' Expression
2638 -----------------------
2639
2640 The following expression creates and gives initial values to the two
2641 variables `zebra' and `tiger'. The body of the `let' expression is a
2642 list 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
2649 Here, the varlist is `((zebra 'stripes) (tiger 'fierce))'.
2650
2651 The two variables are `zebra' and `tiger'. Each variable is the
2652 first element of a two-element list and each value is the second
2653 element of its two-element list. In the varlist, Emacs binds the
2654 variable `zebra' to the value `stripes', and binds the variable
2655 `tiger' to the value `fierce'. In this example, both values are
2656 symbols preceded by a quote. The values could just as well have been
2657 another list or a string. The body of the `let' follows after the
2658 list holding the variables. In this example, the body is a list that
2659 uses the `message' function to print a string in the echo area.
2660
2661 You may evaluate the example in the usual fashion, by placing the
2662 cursor after the last parenthesis and typing `C-x C-e'. When you do
2663 this, the following will appear in the echo area:
2664
2665 "One kind of animal has stripes and another is fierce."
2666
2667 As we have seen before, the `message' function prints its first
2668 argument, 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
2670 the variable `tiger' is printed at the location of the second `%s'.
2671
2672 Uninitialized Variables in a `let' Statement
2673 --------------------------------------------
2674
2675 If you do not bind the variables in a `let' statement to specific
2676 initial values, they will automatically be bound to an initial value
2677 of `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
2687 Here, the varlist is `((birch 3) pine fir (oak 'some))'.
2688
2689 If you evaluate this expression in the usual way, the following will
2690 appear in your echo area:
2691
2692 "Here are 3 variables with nil, nil, and some value."
2693
2694 In this example, Emacs binds the symbol `birch' to the number 3,
2695 binds the symbols `pine' and `fir' to `nil', and binds the symbol
2696 `oak' to the value `some'.
2697
2698 Note that in the first part of the `let', the variables `pine' and
2699 `fir' stand alone as atoms that are not surrounded by parentheses;
2700 this 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)'.
2702 Similarly, `birch' is bound to the number 3 and so is in a list with
2703 that number. (Since a number evaluates to itself, the number does
2704 not need to be quoted. Also, the number is printed in the message
2705 using a `%d' rather than a `%s'.) The four variables as a group are
2706 put into a list to delimit them from the body of the `let'.
2707
2708 The `if' Special Form
2709 =====================
2710
2711 A third special form, in addition to `defun' and `let', is the
2712 conditional `if'. This form is used to instruct the computer to make
2713 decisions. You can write function definitions without using `if',
2714 but it is used often enough, and is important enough, to be included
2715 here. It is used, for example, in the code for the function
2716 `beginning-of-buffer'.
2717
2718 The basic idea behind an `if', is that "_if_ a test is true, _then_
2719 an expression is evaluated." If the test is not true, the expression
2720 is 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
2726 An `if' expression written in Lisp does not use the word `then'; the
2727 test and the action are the second and third elements of the list
2728 whose first element is `if'. Nonetheless, the test part of an `if'
2729 expression is often called the "if-part" and the second argument is
2730 often called the "then-part".
2731
2732 Also, when an `if' expression is written, the true-or-false-test is
2733 usually written on the same line as the symbol `if', but the action
2734 to carry out if the test is true, the "then-part", is written on the
2735 second and subsequent lines. This makes the `if' expression easier
2736 to read.
2737
2738 (if TRUE-OR-FALSE-TEST
2739 ACTION-TO-CARRY-OUT-IF-TEST-IS-TRUE)
2740
2741 The true-or-false-test will be an expression that is evaluated by the
2742 Lisp interpreter.
2743
2744 Here is an example that you can evaluate in the usual manner. The
2745 test is whether the number 5 is greater than the number 4. Since it
2746 is, 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
2752 its second argument and returns true if it is.)
2753
2754 Of course, in actual use, the test in an `if' expression will not be
2755 fixed for all time as it is by the expression `(> 5 4)'. Instead, at
2756 least one of the variables used in the test will be bound to a value
2757 that is not known ahead of time. (If the value were known ahead of
2758 time, we would not need to run the test!)
2759
2760 For example, the value may be bound to an argument of a function
2761 definition. In the following function definition, the character of
2762 the animal is a value that is passed to the function. If the value
2763 bound to `characteristic' is `fierce', then the message, `It's a
2764 tiger!' 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
2773 If you are reading this inside of GNU Emacs, you can evaluate the
2774 function definition in the usual way to install it in Emacs, and then
2775 you can evaluate the following two expressions to see the results:
2776
2777 (type-of-animal 'fierce)
2778
2779 (type-of-animal 'zebra)
2780
2781 When you evaluate `(type-of-animal 'fierce)', you will see the
2782 following message printed in the echo area: `"It's a tiger!"'; and
2783 when you evaluate `(type-of-animal 'zebra)' you will see `nil'
2784 printed in the echo area.
2785
2786 The `type-of-animal' Function in Detail
2787 ---------------------------------------
2788
2789 Let's look at the `type-of-animal' function in detail.
2790
2791 The function definition for `type-of-animal' was written by filling
2792 the slots of two templates, one for a function definition as a whole,
2793 and a second for an `if' expression.
2794
2795 The template for every function that is not interactive is:
2796
2797 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
2798 "DOCUMENTATION..."
2799 BODY...)
2800
2801 The 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
2809 The name of function is `type-of-animal'; it is passed the value of
2810 one argument. The argument list is followed by a multi-line
2811 documentation string. The documentation string is included in the
2812 example because it is a good habit to write documentation string for
2813 every function definition. The body of the function definition
2814 consists of the `if' expression.
2815
2816 The 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
2821 In the `type-of-animal' function, the code for the `if' looks like
2822 this:
2823
2824 (if (equal characteristic 'fierce)
2825 (message "It's a tiger!")))
2826
2827 Here, the true-or-false-test is the expression:
2828
2829 (equal characteristic 'fierce)
2830
2831 In Lisp, `equal' is a function that determines whether its first
2832 argument is equal to its second argument. The second argument is the
2833 quoted symbol `'fierce' and the first argument is the value of the
2834 symbol `characteristic'--in other words, the argument passed to this
2835 function.
2836
2837 In the first exercise of `type-of-animal', the argument `fierce' is
2838 passed to `type-of-animal'. Since `fierce' is equal to `fierce', the
2839 expression, `(equal characteristic 'fierce)', returns a value of
2840 true. When this happens, the `if' evaluates the second argument or
2841 then-part of the `if': `(message "It's tiger!")'.
2842
2843 On the other hand, in the second exercise of `type-of-animal', the
2844 argument `zebra' is passed to `type-of-animal'. `zebra' is not equal
2845 to `fierce', so the then-part is not evaluated and `nil' is returned
2846 by the `if' expression.
2847
2848 If-then-else Expressions
2849 ========================
2850
2851 An `if' expression may have an optional third argument, called the
2852 "else-part", for the case when the true-or-false-test returns false.
2853 When this happens, the second argument or then-part of the overall
2854 `if' expression is _not_ evaluated, but the third or else-part _is_
2855 evaluated. You might think of this as the cloudy day alternative for
2856 the decision `if it is warm and sunny, then go to the beach, else
2857 read a book!".
2858
2859 The 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
2861 else-part is usually written to start on a line of its own and is
2862 indented 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
2868 For example, the following `if' expression prints the message `4 is
2869 not 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
2875 Note that the different levels of indentation make it easy to
2876 distinguish the then-part from the else-part. (GNU Emacs has several
2877 commands that automatically indent `if' expressions correctly. *Note
2878 GNU Emacs Helps You Type Lists: Typing Lists.)
2879
2880 We can extend the `type-of-animal' function to include an else-part
2881 by simply incorporating an additional part to the `if' expression.
2882
2883 You can see the consequences of doing this if you evaluate the
2884 following version of the `type-of-animal' function definition to
2885 install it and then evaluate the two subsequent expressions to pass
2886 different 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
2902 When you evaluate `(type-of-animal 'fierce)', you will see the
2903 following message printed in the echo area: `"It's a tiger!"'; but
2904 when you evaluate `(type-of-animal 'zebra)', you will see `"It's not
2905 fierce!"'.
2906
2907 (Of course, if the CHARACTERISTIC were `ferocious', the message
2908 `"It's not fierce!"' would be printed; and it would be misleading!
2909 When you write code, you need to take into account the possibility
2910 that some such argument will be tested by the `if' and write your
2911 program accordingly.)
2912
2913 Truth and Falsehood in Emacs Lisp
2914 =================================
2915
2916 There is an important aspect to the truth test in an `if' expression.
2917 So far, we have spoken of `true' and `false' as values of predicates
2918 as if they were new kinds of Emacs Lisp objects. In fact, `false' is
2919 just our old friend `nil'. Anything else--anything at all--is `true'.
2920
2921 The expression that tests for truth is interpreted as "true" if the
2922 result of evaluating it is a value that is not `nil'. In other
2923 words, the result of the test is considered true if the value
2924 returned is a number such as 47, a string such as `"hello"', or a
2925 symbol (other than `nil') such as `flowers', or a list, or even a
2926 buffer!
2927
2928 An explanation of `nil'
2929 -----------------------
2930
2931 Before illustrating a test for truth, we need an explanation of `nil'.
2932
2933 In Emacs Lisp, the symbol `nil' has two meanings. First, it means the
2934 empty list. Second, it means false and is the value returned when a
2935 true-or-false-test tests false. `nil' can be written as an empty
2936 list, `()', or as `nil'. As far as the Lisp interpreter is
2937 concerned, `()' and `nil' are the same. Humans, however, tend to use
2938 `nil' for false and `()' for the empty list.
2939
2940 In Emacs Lisp, any value that is not `nil'--is not the empty list--is
2941 considered true. This means that if an evaluation returns something
2942 that is not an empty list, an `if' expression will test true. For
2943 example, if a number is put in the slot for the test, it will be
2944 evaluated and will return itself, since that is what numbers do when
2945 evaluated. In this conditional, the `if' expression will test true.
2946 The expression tests false only when `nil', an empty list, is
2947 returned by evaluating the expression.
2948
2949 You can see this by evaluating the two expressions in the following
2950 examples.
2951
2952 In the first example, the number 4 is evaluated as the test in the
2953 `if' expression and returns itself; consequently, the then-part of
2954 the expression is evaluated and returned: `true' appears in the echo
2955 area. In the second example, the `nil' indicates false;
2956 consequently, the else-part of the expression is evaluated and
2957 returned: `false' appears in the echo area.
2958
2959 (if 4
2960 'true
2961 'false)
2962
2963 (if nil
2964 'true
2965 'false)
2966
2967 Incidentally, if some other useful value is not available for a test
2968 that returns true, then the Lisp interpreter will return the symbol
2969 `t' for true. For example, the expression `(> 5 4)' returns `t' when
2970 evaluated, as you can see by evaluating it in the usual way:
2971
2972 (> 5 4)
2973
2974 On the other hand, this function returns `nil' if the test is false.
2975
2976 (> 4 5)
2977
2978 `save-excursion'
2979 ================
2980
2981 The `save-excursion' function is the fourth and final special form
2982 that we will discuss in this chapter.
2983
2984 In Emacs Lisp programs used for editing, the `save-excursion'
2985 function is very common. It saves the location of point and mark,
2986 executes the body of the function, and then restores point and mark to
2987 their previous positions if their locations were changed. Its primary
2988 purpose is to keep the user from being surprised and disturbed by
2989 unexpected movement of point or mark.
2990
2991 Point and Mark
2992 --------------
2993
2994 Before discussing `save-excursion', however, it may be useful first
2995 to review what point and mark are in GNU Emacs. "Point" is the
2996 current location of the cursor. Wherever the cursor is, that is
2997 point. More precisely, on terminals where the cursor appears to be
2998 on top of a character, point is immediately before the character. In
2999 Emacs Lisp, point is an integer. The first character in a buffer is
3000 number one, the second is number two, and so on. The function
3001 `point' returns the current position of the cursor as a number. Each
3002 buffer has its own value for point.
3003
3004 The "mark" is another position in the buffer; its value can be set
3005 with a command such as `C-<SPC>' (`set-mark-command'). If a mark has
3006 been set, you can use the command `C-x C-x'
3007 (`exchange-point-and-mark') to cause the cursor to jump to the mark
3008 and set the mark to be the previous position of point. In addition,
3009 if you set another mark, the position of the previous mark is saved
3010 in the mark ring. Many mark positions can be saved this way. You
3011 can jump the cursor to a saved mark by typing `C-u C-<SPC>' one or
3012 more times.
3013
3014 The part of the buffer between point and mark is called "the region".
3015 Numerous commands work on the region, including `center-region',
3016 `count-lines-region', `kill-region', and `print-region'.
3017
3018 The `save-excursion' special form saves the locations of point and
3019 mark and restores those positions after the code within the body of
3020 the special form is evaluated by the Lisp interpreter. Thus, if
3021 point were in the beginning of a piece of text and some code moved
3022 point to the end of the buffer, the `save-excursion' would put point
3023 back to where it was before, after the expressions in the body of the
3024 function were evaluated.
3025
3026 In Emacs, a function frequently moves point as part of its internal
3027 workings even though a user would not expect this. For example,
3028 `count-lines-region' moves point. To prevent the user from being
3029 bothered by jumps that are both unexpected and (from the user's point
3030 of view) unnecessary, `save-excursion' is often used to keep point and
3031 mark in the location expected by the user. The use of
3032 `save-excursion' is good housekeeping.
3033
3034 To make sure the house stays clean, `save-excursion' restores the
3035 values of point and mark even if something goes wrong in the code
3036 inside 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
3039 In addition to recording the values of point and mark,
3040 `save-excursion' keeps track of the current buffer, and restores it,
3041 too. This means you can write code that will change the buffer and
3042 have `save-excursion' switch you back to the original buffer. This
3043 is how `save-excursion' is used in `append-to-buffer'. (*Note The
3044 Definition of `append-to-buffer': append-to-buffer.)
3045
3046 Template for a `save-excursion' Expression
3047 ------------------------------------------
3048
3049 The template for code using `save-excursion' is simple:
3050
3051 (save-excursion
3052 BODY...)
3053
3054 The body of the function is one or more expressions that will be
3055 evaluated in sequence by the Lisp interpreter. If there is more than
3056 one expression in the body, the value of the last one will be returned
3057 as the value of the `save-excursion' function. The other expressions
3058 in the body are evaluated only for their side effects; and
3059 `save-excursion' itself is used only for its side effect (which is
3060 restoring the positions of point and mark).
3061
3062 In more detail, the template for a `save-excursion' expression looks
3063 like 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
3072 An expression, of course, may be a symbol on its own or a list.
3073
3074 In Emacs Lisp code, a `save-excursion' expression often occurs within
3075 the body of a `let' expression. It looks like this:
3076
3077 (let VARLIST
3078 (save-excursion
3079 BODY...))
3080
3081 Review
3082 ======
3083
3084 In the last few chapters we have introduced a fair number of functions
3085 and special forms. Here they are described in brief, along with a few
3086 similar 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
3283 Exercises
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
3293 A Few Buffer-Related Functions
3294 ******************************
3295
3296 In this chapter we study in detail several of the functions used in
3297 GNU Emacs. This is called a "walk-through". These functions are
3298 used as examples of Lisp code, but are not imaginary examples; with
3299 the exception of the first, simplified function definition, these
3300 functions show the actual code used in GNU Emacs. You can learn a
3301 great deal from these definitions. The functions described here are
3302 all related to buffers. Later, we will study other functions.
3303
3304 Finding More Information
3305 ========================
3306
3307 In this walk-through, I will describe each new function as we come to
3308 it, sometimes in detail and sometimes briefly. If you are interested,
3309 you can get the full documentation of any Emacs Lisp function at any
3310 time 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
3312 by typing `C-h v' and then the name of the variable (and then <RET>).
3313
3314 In versions 20 and higher, when a function is written in Emacs Lisp,
3315 `describe-function' will also tell you the location of the function
3316 definition. If you move point over the file name and press the <RET>
3317 key, which is this case means `help-follow' rather than `return' or
3318 `enter', Emacs will take you directly to the function definition.
3319
3320 More generally, if you want to see a function in its original source
3321 file, you can use the `find-tags' function to jump to it.
3322 `find-tags' works with a wide variety of languages, not just Lisp,
3323 and 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
3325 of this document.
3326
3327 The `find-tags' function depends on `tags tables' that record the
3328 locations of the functions, variables, and other items to which
3329 `find-tags' jumps.
3330
3331 To use the `find-tags' command, type `M-.' (i.e., type the <META>
3332 key and the period key at the same time, or else type the <ESC> key
3333 and then type the period key), and then, at the prompt, type in the
3334 name of the function whose source code you want to see, such as
3335 `mark-whole-buffer', and then type <RET>. Emacs will switch buffers
3336 and display the source code for the function on your screen. To
3337 switch back to your current buffer, type `C-x b <RET>'. (On some
3338 keyboards, the <META> key is labelled <ALT>.)
3339
3340 Depending on how the initial default values of your copy of Emacs are
3341 set, you may also need to specify the location of your `tags table',
3342 which is a file called `TAGS'. For example, if you are interested in
3343 Emacs sources, the tags table you will most likely want, if it has
3344 already been created for you, will be in a subdirectory of the
3345 `/usr/local/share/emacs/' directory; thus you would use the `M-x
3346 visit-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
3349 been created, you will have to create it yourself.
3350
3351 To create a `TAGS' file in a specific directory, switch to that
3352 directory 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'
3354 as the command to execute
3355
3356 M-x compile RET etags *.el RET
3357
3358 For more information, see *Note Create Your Own `TAGS' File: etags.
3359
3360 After you become more familiar with Emacs Lisp, you will find that
3361 you will frequently use `find-tags' to navigate your way around
3362 source code; and you will create your own `TAGS' tables.
3363
3364 Incidentally, the files that contain Lisp code are conventionally
3365 called "libraries". The metaphor is derived from that of a
3366 specialized library, such as a law library or an engineering library,
3367 rather than a general library. Each library, or file, contains
3368 functions that relate to a particular topic or activity, such as
3369 `abbrev.el' for handling abbreviations and other typing shortcuts,
3370 and `help.el' for on-line help. (Sometimes several libraries provide
3371 code for a single activity, as the various `rmail...' files provide
3372 code for reading electronic mail.) In `The GNU Emacs Manual', you
3373 will see sentences such as "The `C-h p' command lets you search the
3374 standard Emacs Lisp libraries by topic keywords."
3375
3376 A Simplified `beginning-of-buffer' Definition
3377 =============================================
3378
3379 The `beginning-of-buffer' command is a good function to start with
3380 since you are likely to be familiar with it and it is easy to
3381 understand. Used as an interactive command, `beginning-of-buffer'
3382 moves the cursor to the beginning of the buffer, leaving the mark at
3383 the previous position. It is generally bound to `M-<'.
3384
3385 In this section, we will discuss a shortened version of the function
3386 that shows how it is most frequently used. This shortened function
3387 works as written, but it does not contain the code for a complex
3388 option. In another section, we will describe the entire function.
3389 (*Note Complete Definition of `beginning-of-buffer':
3390 beginning-of-buffer.)
3391
3392 Before looking at the code, let's consider what the function
3393 definition has to contain: it must include an expression that makes
3394 the function interactive so it can be called by typing `M-x
3395 beginning-of-buffer' or by typing a keychord such as `M-<'; it must
3396 include code to leave a mark at the original position in the buffer;
3397 and it must include code to move the cursor to the beginning of the
3398 buffer.
3399
3400 Here 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
3409 Like all function definitions, this definition has five parts
3410 following 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
3422 In this function definition, the argument list is empty; this means
3423 that this function does not require any arguments. (When we look at
3424 the definition for the complete function, we will see that it may be
3425 passed an optional argument.)
3426
3427 The interactive expression tells Emacs that the function is intended
3428 to be used interactively. In this example, `interactive' does not
3429 have an argument because `simplified-beginning-of-buffer' does not
3430 require one.
3431
3432 The body of the function consists of the two lines:
3433
3434 (push-mark)
3435 (goto-char (point-min))
3436
3437 The first of these lines is the expression, `(push-mark)'. When this
3438 expression is evaluated by the Lisp interpreter, it sets a mark at
3439 the current position of the cursor, wherever that may be. The
3440 position of this mark is saved in the mark ring.
3441
3442 The next line is `(goto-char (point-min))'. This expression jumps
3443 the cursor to the minimum point in the buffer, that is, to the
3444 beginning of the buffer (or to the beginning of the accessible portion
3445 of the buffer if it is narrowed. *Note Narrowing and Widening:
3446 Narrowing & Widening.)
3447
3448 The `push-mark' command sets a mark at the place where the cursor was
3449 located before it was moved to the beginning of the buffer by the
3450 `(goto-char (point-min))' expression. Consequently, you can, if you
3451 wish, go back to where you were originally by typing `C-x C-x'.
3452
3453 That is all there is to the function definition!
3454
3455 When you are reading code such as this and come upon an unfamiliar
3456 function, such as `goto-char', you can find out what it does by using
3457 the `describe-function' command. To use this command, type `C-h f'
3458 and then type in the name of the function and press <RET>. The
3459 `describe-function' command will print the function's documentation
3460 string 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
3468 or preceding the cursor, so you can save typing by positioning the
3469 cursor right over or after the function and then typing `C-h f
3470 <RET>'.)
3471
3472 The `end-of-buffer' function definition is written in the same way as
3473 the `beginning-of-buffer' definition except that the body of the
3474 function contains the expression `(goto-char (point-max))' in place
3475 of `(goto-char (point-min))'.
3476
3477 The Definition of `mark-whole-buffer'
3478 =====================================
3479
3480 The `mark-whole-buffer' function is no harder to understand than the
3481 `simplified-beginning-of-buffer' function. In this case, however, we
3482 will look at the complete function, not a shortened version.
3483
3484 The `mark-whole-buffer' function is not as commonly used as the
3485 `beginning-of-buffer' function, but is useful nonetheless: it marks a
3486 whole buffer as a region by putting point at the beginning and a mark
3487 at the end of the buffer. It is generally bound to `C-x h'.
3488
3489 An overview of `mark-whole-buffer'
3490 ----------------------------------
3491
3492 In 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
3501 Like all other functions, the `mark-whole-buffer' function fits into
3502 the 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
3509 Here is how the function works: the name of the function is
3510 `mark-whole-buffer'; it is followed by an empty argument list, `()',
3511 which means that the function does not require arguments. The
3512 documentation comes next.
3513
3514 The next line is an `(interactive)' expression that tells Emacs that
3515 the function will be used interactively. These details are similar
3516 to the `simplified-beginning-of-buffer' function described in the
3517 previous section.
3518
3519 Body of `mark-whole-buffer'
3520 ---------------------------
3521
3522 The body of the `mark-whole-buffer' function consists of three lines
3523 of code:
3524
3525 (push-mark (point))
3526 (push-mark (point-max))
3527 (goto-char (point-min))
3528
3529 The first of these lines is the expression, `(push-mark (point))'.
3530
3531 This line does exactly the same job as the first line of the body of
3532 the `simplified-beginning-of-buffer' function, which is written
3533 `(push-mark)'. In both cases, the Lisp interpreter sets a mark at
3534 the current position of the cursor.
3535
3536 I don't know why the expression in `mark-whole-buffer' is written
3537 `(push-mark (point))' and the expression in `beginning-of-buffer' is
3538 written `(push-mark)'. Perhaps whoever wrote the code did not know
3539 that the arguments for `push-mark' are optional and that if
3540 `push-mark' is not passed an argument, the function automatically
3541 sets mark at the location of point by default. Or perhaps the
3542 expression was written so as to parallel the structure of the next
3543 line. In any case, the line causes Emacs to determine the position
3544 of point and set a mark there.
3545
3546 The next line of `mark-whole-buffer' is `(push-mark (point-max)'.
3547 This expression sets a mark at the point in the buffer that has the
3548 highest number. This will be the end of the buffer (or, if the
3549 buffer is narrowed, the end of the accessible portion of the buffer.
3550 *Note Narrowing and Widening: Narrowing & Widening, for more about
3551 narrowing.) After this mark has been set, the previous mark, the one
3552 set at point, is no longer set, but Emacs remembers its position,
3553 just as all other recent marks are always remembered. This means
3554 that you can, if you wish, go back to that position by typing `C-u
3555 C-<SPC>' twice.
3556
3557 (In GNU Emacs 21, the `(push-mark (point-max)' is slightly more
3558 complicated 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
3563 the highest numbered place in the buffer that it can. However, in
3564 this version, `push-mark' has two additional arguments. The second
3565 argument to `push-mark' is `nil'. This tells the function it
3566 _should_ display a message that says `Mark set' when it pushes the
3567 mark. The third argument is `t'. This tells `push-mark' to activate
3568 the mark when Transient Mark mode is turned on. Transient Mark mode
3569 highlights the currently active region. It is usually turned off.)
3570
3571 Finally, the last line of the function is `(goto-char (point-min)))'.
3572 This is written exactly the same way as it is written in
3573 `beginning-of-buffer'. The expression moves the cursor to the
3574 minimum 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
3576 result of this, point is placed at the beginning of the buffer and
3577 mark is set at the end of the buffer. The whole buffer is,
3578 therefore, the region.
3579
3580 The Definition of `append-to-buffer'
3581 ====================================
3582
3583 The `append-to-buffer' command is very nearly as simple as the
3584 `mark-whole-buffer' command. What it does is copy the region (that
3585 is, the part of the buffer between point and mark) from the current
3586 buffer to a specified buffer.
3587
3588 An Overview of `append-to-buffer'
3589 ---------------------------------
3590
3591 The `append-to-buffer' command uses the `insert-buffer-substring'
3592 function to copy the region. `insert-buffer-substring' is described
3593 by 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
3597 buffer to which the text will go and the region that will be copied.
3598 Here 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
3613 The function can be understood by looking at it as a series of
3614 filled-in templates.
3615
3616 The outermost template is for the function definition. In this
3617 function, 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
3624 The first line of the function includes its name and three arguments.
3625 The arguments are the `buffer' to which the text will be copied, and
3626 the `start' and `end' of the region in the current buffer that will
3627 be copied.
3628
3629 The next part of the function is the documentation, which is clear and
3630 complete.
3631
3632 The `append-to-buffer' Interactive Expression
3633 ---------------------------------------------
3634
3635 Since the `append-to-buffer' function will be used interactively, the
3636 function must have an `interactive' expression. (For a review of
3637 `interactive', see *Note Making a Function Interactive: Interactive.)
3638 The expression reads as follows:
3639
3640 (interactive "BAppend to buffer: \nr")
3641
3642 This expression has an argument inside of quotation marks and that
3643 argument has two parts, separated by `\n'.
3644
3645 The first part is `BAppend to buffer: '. Here, the `B' tells Emacs
3646 to ask for the name of the buffer that will be passed to the
3647 function. Emacs will ask for the name by prompting the user in the
3648 minibuffer, using the string following the `B', which is the string
3649 `Append to buffer: '. Emacs then binds the variable `buffer' in the
3650 function's argument list to the specified buffer.
3651
3652 The newline, `\n', separates the first part of the argument from the
3653 second part. It is followed by an `r' that tells Emacs to bind the
3654 two arguments that follow the symbol `buffer' in the function's
3655 argument list (that is, `start' and `end') to the values of point and
3656 mark.
3657
3658 The Body of `append-to-buffer'
3659 ------------------------------
3660
3661 The body of the `append-to-buffer' function begins with `let'.
3662
3663 As we have seen before (*note `let': let.), the purpose of a `let'
3664 expression is to create and give initial values to one or more
3665 variables that will only be used within the body of the `let'. This
3666 means that such a variable will not be confused with any variable of
3667 the same name outside the `let' expression.
3668
3669 We can see how the `let' expression fits into the function as a whole
3670 by showing a template for `append-to-buffer' with the `let'
3671 expression 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
3679 The `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
3688 In the `append-to-buffer' function, the varlist looks like this:
3689
3690 (oldbuf (current-buffer))
3691
3692 In this part of the `let' expression, the one variable, `oldbuf', is
3693 bound to the value returned by the `(current-buffer)' expression.
3694 The variable, `oldbuf', is used to keep track of the buffer in which
3695 you are working and from which you will copy.
3696
3697 The element or elements of a varlist are surrounded by a set of
3698 parentheses so the Lisp interpreter can distinguish the varlist from
3699 the body of the `let'. As a consequence, the two-element list within
3700 the varlist is surrounded by a circumscribing set of parentheses.
3701 The line looks like this:
3702
3703 (let ((oldbuf (current-buffer)))
3704 ... )
3705
3706 The two parentheses before `oldbuf' might surprise you if you did not
3707 realize that the first parenthesis before `oldbuf' marks the boundary
3708 of the varlist and the second parenthesis marks the beginning of the
3709 two-element list, `(oldbuf (current-buffer))'.
3710
3711 `save-excursion' in `append-to-buffer'
3712 --------------------------------------
3713
3714 The body of the `let' expression in `append-to-buffer' consists of a
3715 `save-excursion' expression.
3716
3717 The `save-excursion' function saves the locations of point and mark,
3718 and restores them to those positions after the expressions in the
3719 body of the `save-excursion' complete execution. In addition,
3720 `save-excursion' keeps track of the original buffer, and restores it.
3721 This is how `save-excursion' is used in `append-to-buffer'.
3722
3723 Incidentally, it is worth noting here that a Lisp function is normally
3724 formatted so that everything that is enclosed in a multi-line spread
3725 is indented more to the right than the first symbol. In this function
3726 definition, 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
3736 This formatting convention makes it easy to see that the two lines in
3737 the body of the `save-excursion' are enclosed by the parentheses
3738 associated with `save-excursion', just as the `save-excursion' itself
3739 is 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
3746 The use of the `save-excursion' function can be viewed as a process
3747 of 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
3755 In this function, the body of the `save-excursion' contains only two
3756 expressions. The body looks like this:
3757
3758 (set-buffer (get-buffer-create buffer))
3759 (insert-buffer-substring oldbuf start end)
3760
3761 When the `append-to-buffer' function is evaluated, the two
3762 expressions in the body of the `save-excursion' are evaluated in
3763 sequence. The value of the last expression is returned as the value
3764 of the `save-excursion' function; the other expression is evaluated
3765 only for its side effects.
3766
3767 The first line in the body of the `save-excursion' uses the
3768 `set-buffer' function to change the current buffer to the one
3769 specified in the first argument to `append-to-buffer'. (Changing the
3770 buffer is the side effect; as we have said before, in Lisp, a side
3771 effect is often the primary thing we want.) The second line does the
3772 primary work of the function.
3773
3774 The `set-buffer' function changes Emacs' attention to the buffer to
3775 which the text will be copied and from which `save-excursion' will
3776 return.
3777
3778 The line looks like this:
3779
3780 (set-buffer (get-buffer-create buffer))
3781
3782 The innermost expression of this list is `(get-buffer-create
3783 buffer)'. This expression uses the `get-buffer-create' function,
3784 which either gets the named buffer, or if it does not exist, creates
3785 one with the given name. This means you can use `append-to-buffer' to
3786 put text into a buffer that did not previously exist.
3787
3788 `get-buffer-create' also keeps `set-buffer' from getting an
3789 unnecessary error: `set-buffer' needs a buffer to go to; if you were
3790 to specify a buffer that does not exist, Emacs would baulk. Since
3791 `get-buffer-create' will create a buffer if none exists, `set-buffer'
3792 is always provided with a buffer.
3793
3794 The last line of `append-to-buffer' does the work of appending the
3795 text:
3796
3797 (insert-buffer-substring oldbuf start end)
3798
3799 The `insert-buffer-substring' function copies a string _from_ the
3800 buffer specified as its first argument and inserts the string into
3801 the present buffer. In this case, the argument to
3802 `insert-buffer-substring' is the value of the variable created and
3803 bound by the `let', namely the value of `oldbuf', which was the
3804 current buffer when you gave the `append-to-buffer' command.
3805
3806 After `insert-buffer-substring' has done its work, `save-excursion'
3807 will restore the action to the original buffer and `append-to-buffer'
3808 will have done its job.
3809
3810 Written 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
3820 In summary, `append-to-buffer' works as follows: it saves the value
3821 of the current buffer in the variable called `oldbuf'. It gets the
3822 new buffer, creating one if need be, and switches Emacs to it. Using
3823 the value of `oldbuf', it inserts the region of text from the old
3824 buffer into the new buffer; and then using `save-excursion', it
3825 brings you back to your original buffer.
3826
3827 In looking at `append-to-buffer', you have explored a fairly complex
3828 function. It shows how to use `let' and `save-excursion', and how to
3829 change to and come back from another buffer. Many function
3830 definitions use `let', `save-excursion', and `set-buffer' this way.
3831
3832 Review
3833 ======
3834
3835 Here is a brief summary of the various functions discussed in this
3836 chapter.
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
3884 Exercises
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
3896 A Few More Complex Functions
3897 ****************************
3898
3899 In this chapter, we build on what we have learned in previous chapters
3900 by looking at more complex functions. The `copy-to-buffer' function
3901 illustrates use of two `save-excursion' expressions in one
3902 definition, while the `insert-buffer' function illustrates use of an
3903 asterisk in an `interactive' expression, use of `or', and the
3904 important distinction between a name and the object to which the name
3905 refers.
3906
3907 The Definition of `copy-to-buffer'
3908 ==================================
3909
3910 After understanding how `append-to-buffer' works, it is easy to
3911 understand `copy-to-buffer'. This function copies text into a
3912 buffer, but instead of adding to the second buffer, it replaces the
3913 previous 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
3920 The 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
3931 This code is similar to the code in `append-to-buffer': it is only
3932 after changing to the buffer to which the text will be copied that
3933 the definition for this function diverges from the definition for
3934 `append-to-buffer': the `copy-to-buffer' function erases the buffer's
3935 former contents. (This is what is meant by `replacement'; to replace
3936 text, Emacs erases the previous text and then inserts new text.)
3937 After erasing the previous contents of the buffer, `save-excursion'
3938 is used for a second time and the new text is inserted.
3939
3940 Why is `save-excursion' used twice? Consider again what the function
3941 does.
3942
3943 In 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
3952 The first use of `save-excursion' returns Emacs to the buffer from
3953 which the text is being copied. That is clear, and is just like its
3954 use in `append-to-buffer'. Why the second use? The reason is that
3955 `insert-buffer-substring' always leaves point at the _end_ of the
3956 region being inserted. The second `save-excursion' causes Emacs to
3957 leave point at the beginning of the text being inserted. In most
3958 circumstances, users prefer to find point at the beginning of
3959 inserted text. (Of course, the `copy-to-buffer' function returns the
3960 user to the original buffer when done--but if the user _then_
3961 switches to the copied-to buffer, point will go to the beginning of
3962 the text. Thus, this use of a second `save-excursion' is a little
3963 nicety.)
3964
3965 The Definition of `insert-buffer'
3966 =================================
3967
3968 `insert-buffer' is yet another buffer-related function. This command
3969 copies another buffer _into_ the current buffer. It is the reverse
3970 of `append-to-buffer' or `copy-to-buffer', since they copy a region
3971 of text _from_ the current buffer to another buffer.
3972
3973 In addition, this code illustrates the use of `interactive' with a
3974 buffer that might be "read-only" and the important distinction
3975 between the name of an object and the object actually referred to.
3976
3977 The Code for `insert-buffer'
3978 ----------------------------
3979
3980 Here 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
3998 As with other function definitions, you can use a template to see an
3999 outline of the function:
4000
4001 (defun insert-buffer (buffer)
4002 "DOCUMENTATION..."
4003 (interactive "*bInsert buffer: ")
4004 BODY...)
4005
4006 The Interactive Expression in `insert-buffer'
4007 ---------------------------------------------
4008
4009 In `insert-buffer', the argument to the `interactive' declaration has
4010 two parts, an asterisk, `*', and `bInsert buffer: '.
4011
4012 A Read-only Buffer
4013 ..................
4014
4015 The asterisk is for the situation when the current buffer is a
4016 read-only buffer--a buffer that cannot be modified. If
4017 `insert-buffer' is called when the current buffer is read-only, a
4018 message to this effect is printed in the echo area and the terminal
4019 may beep or blink at you; you will not be permitted to insert anything
4020 into current buffer. The asterisk does not need to be followed by a
4021 newline to separate it from the next argument.
4022
4023 `b' in an Interactive Expression
4024 ................................
4025
4026 The next argument in the interactive expression starts with a lower
4027 case `b'. (This is different from the code for `append-to-buffer',
4028 which uses an upper-case `B'. *Note The Definition of
4029 `append-to-buffer': append-to-buffer.) The lower-case `b' tells the
4030 Lisp interpreter that the argument for `insert-buffer' should be an
4031 existing buffer or else its name. (The upper-case `B' option
4032 provides for the possibility that the buffer does not exist.) Emacs
4033 will prompt you for the name of the buffer, offering you a default
4034 buffer, with name completion enabled. If the buffer does not exist,
4035 you receive a message that says "No match"; your terminal may beep at
4036 you as well.
4037
4038 The Body of the `insert-buffer' Function
4039 ----------------------------------------
4040
4041 The body of the `insert-buffer' function has two major parts: an `or'
4042 expression and a `let' expression. The purpose of the `or'
4043 expression is to ensure that the argument `buffer' is bound to a
4044 buffer and not just the name of a buffer. The body of the `let'
4045 expression contains the code which copies the other buffer into the
4046 current buffer.
4047
4048 In outline, the two expressions fit into the `insert-buffer' function
4049 like this:
4050
4051 (defun insert-buffer (buffer)
4052 "DOCUMENTATION..."
4053 (interactive "*bInsert buffer: ")
4054 (or ...
4055 ...
4056 (let (VARLIST)
4057 BODY-OF-`let'... )
4058
4059 To 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
4061 first necessary to understand the `or' function.
4062
4063 Before 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
4065 familiar.
4066
4067 `insert-buffer' With an `if' Instead of an `or'
4068 -----------------------------------------------
4069
4070 The job to be done is to make sure the value of `buffer' is a buffer
4071 itself and not the name of a buffer. If the value is the name, then
4072 the buffer itself must be got.
4073
4074 You can imagine yourself at a conference where an usher is wandering
4075 around holding a list with your name on it and looking for you: the
4076 usher is "bound" to your name, not to you; but when the usher finds
4077 you and takes your arm, the usher becomes "bound" to you.
4078
4079 In Lisp, you might describe this situation like this:
4080
4081 (if (not (holding-on-to-guest))
4082 (find-and-take-arm-of-guest))
4083
4084 We want to do the same thing with a buffer--if we do not have the
4085 buffer itself, we want to get it.
4086
4087 Using a predicate called `bufferp' that tells us whether we have a
4088 buffer (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
4093 Here, 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
4097 In the test, the function `bufferp' returns true if its argument is a
4098 buffer--but false if its argument is the name of the buffer. (The
4099 last character of the function name `bufferp' is the character `p';
4100 as we saw earlier, such use of `p' is a convention that indicates
4101 that the function is a predicate, which is a term that means that the
4102 function will determine whether some property is true or false.
4103 *Note Using the Wrong Type Object as an Argument: Wrong Type of
4104 Argument.)
4105
4106 The function `not' precedes the expression `(bufferp buffer)', so the
4107 true-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
4112 false if its argument is true. So if `(bufferp buffer)' returns
4113 true, the `not' expression returns false and vice-versa: what is "not
4114 true" is false and what is "not false" is true.
4115
4116 Using this test, the `if' expression works as follows: when the value
4117 of the variable `buffer' is actually a buffer rather then its name,
4118 the true-or-false-test returns false and the `if' expression does not
4119 evaluate the then-part. This is fine, since we do not need to do
4120 anything to the variable `buffer' if it really is a buffer.
4121
4122 On the other hand, when the value of `buffer' is not a buffer itself,
4123 but the name of a buffer, the true-or-false-test returns true and the
4124 then-part of the expression is evaluated. In this case, the
4125 then-part is `(setq buffer (get-buffer buffer))'. This expression
4126 uses the `get-buffer' function to return an actual buffer itself,
4127 given its name. The `setq' then sets the variable `buffer' to the
4128 value of the buffer itself, replacing its previous value (which was
4129 the name of the buffer).
4130
4131 The `or' in the Body
4132 --------------------
4133
4134 The purpose of the `or' expression in the `insert-buffer' function is
4135 to ensure that the argument `buffer' is bound to a buffer and not
4136 just to the name of a buffer. The previous section shows how the job
4137 could have been done using an `if' expression. However, the
4138 `insert-buffer' function actually uses `or'. To understand this, it
4139 is necessary to understand how `or' works.
4140
4141 An `or' function can have any number of arguments. It evaluates each
4142 argument in turn and returns the value of the first of its arguments
4143 that is not `nil'. Also, and this is a crucial feature of `or', it
4144 does not evaluate any subsequent arguments after returning the first
4145 non-`nil' value.
4146
4147 The `or' expression looks like this:
4148
4149 (or (bufferp buffer)
4150 (setq buffer (get-buffer buffer)))
4151
4152 The first argument to `or' is the expression `(bufferp buffer)'.
4153 This expression returns true (a non-`nil' value) if the buffer is
4154 actually a buffer, and not just the name of a buffer. In the `or'
4155 expression, if this is the case, the `or' expression returns this
4156 true value and does not evaluate the next expression--and this is fine
4157 with us, since we do not want to do anything to the value of `buffer'
4158 if it really is a buffer.
4159
4160 On the other hand, if the value of `(bufferp buffer)' is `nil', which
4161 it will be if the value of `buffer' is the name of a buffer, the Lisp
4162 interpreter evaluates the next element of the `or' expression. This
4163 is the expression `(setq buffer (get-buffer buffer))'. This
4164 expression returns a non-`nil' value, which is the value to which it
4165 sets the variable `buffer'--and this value is a buffer itself, not
4166 the name of a buffer.
4167
4168 The result of all this is that the symbol `buffer' is always bound to
4169 a buffer itself rather than to the name of a buffer. All this is
4170 necessary because the `set-buffer' function in a following line only
4171 works with a buffer itself, not with the name to a buffer.
4172
4173 Incidentally, using `or', the situation with the usher would be
4174 written like this:
4175
4176 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
4177
4178 The `let' Expression in `insert-buffer'
4179 ---------------------------------------
4180
4181 After ensuring that the variable `buffer' refers to a buffer itself
4182 and not just to the name of a buffer, the `insert-buffer function'
4183 continues with a `let' expression. This specifies three local
4184 variables, `start', `end', and `newmark' and binds them to the
4185 initial value `nil'. These variables are used inside the remainder
4186 of the `let' and temporarily hide any other occurrence of variables
4187 of the same name in Emacs until the end of the `let'.
4188
4189 The body of the `let' contains two `save-excursion' expressions.
4190 First, we will look at the inner `save-excursion' expression in
4191 detail. The expression looks like this:
4192
4193 (save-excursion
4194 (set-buffer buffer)
4195 (setq start (point-min) end (point-max)))
4196
4197 The expression `(set-buffer buffer)' changes Emacs' attention from
4198 the current buffer to the one from which the text will copied. In
4199 that buffer, the variables `start' and `end' are set to the beginning
4200 and end of the buffer, using the commands `point-min' and
4201 `point-max'. Note that we have here an illustration of how `setq' is
4202 able to set two variables in the same expression. The first argument
4203 of `setq' is set to the value of its second, and its third argument
4204 is set to the value of its fourth.
4205
4206 After the body of the inner `save-excursion' is evaluated, the
4207 `save-excursion' restores the original buffer, but `start' and `end'
4208 remain set to the values of the beginning and end of the buffer from
4209 which the text will be copied.
4210
4211 The 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
4219 The `insert-buffer-substring' function copies the text _into_ the
4220 current buffer _from_ the region indicated by `start' and `end' in
4221 `buffer'. Since the whole of the second buffer lies between `start'
4222 and `end', the whole of the second buffer is copied into the buffer
4223 you are editing. Next, the value of point, which will be at the end
4224 of the inserted text, is recorded in the variable `newmark'.
4225
4226 After the body of the outer `save-excursion' is evaluated, point and
4227 mark are relocated to their original places.
4228
4229 However, it is convenient to locate a mark at the end of the newly
4230 inserted text and locate point at its beginning. The `newmark'
4231 variable records the end of the inserted text. In the last line of
4232 the `let' expression, the `(push-mark newmark)' expression function
4233 sets a mark to this location. (The previous location of the mark is
4234 still accessible; it is recorded on the mark ring and you can go back
4235 to it with `C-u C-<SPC>'.) Meanwhile, point is located at the
4236 beginning of the inserted text, which is where it was before you
4237 called the insert function.
4238
4239 The 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
4250 Like the `append-to-buffer' function, the `insert-buffer' function
4251 uses `let', `save-excursion', and `set-buffer'. In addition, the
4252 function illustrates one way to use `or'. All these functions are
4253 building blocks that we will find and use again and again.
4254
4255 Complete Definition of `beginning-of-buffer'
4256 ============================================
4257
4258 The basic structure of the `beginning-of-buffer' function has already
4259 been discussed. (*Note A Simplified `beginning-of-buffer'
4260 Definition: simplified-beginning-of-buffer.) This section describes
4261 the complex part of the definition.
4262
4263 As previously described, when invoked without an argument,
4264 `beginning-of-buffer' moves the cursor to the beginning of the
4265 buffer, leaving the mark at the previous position. However, when the
4266 command is invoked with a number between one and ten, the function
4267 considers that number to be a fraction of the length of the buffer,
4268 measured in tenths, and Emacs moves the cursor that fraction of the
4269 way from the beginning of the buffer. Thus, you can either call this
4270 function with the key command `M-<', which will move the cursor to
4271 the beginning of the buffer, or with a key command such as `C-u 7
4272 M-<' which will move the cursor to a point 70% of the way through the
4273 buffer. If a number bigger than ten is used for the argument, it
4274 moves to the end of the buffer.
4275
4276 The `beginning-of-buffer' function can be called with or without an
4277 argument. The use of the argument is optional.
4278
4279 Optional Arguments
4280 ------------------
4281
4282 Unless told otherwise, Lisp expects that a function with an argument
4283 in its function definition will be called with a value for that
4284 argument. If that does not happen, you get an error and a message
4285 that says `Wrong number of arguments'.
4286
4287 However, optional arguments are a feature of Lisp: a "keyword" may be
4288 used to tell the Lisp interpreter that an argument is optional. The
4289 keyword is `&optional'. (The `&' in front of `optional' is part of
4290 the keyword.) In a function definition, if an argument follows the
4291 keyword `&optional', a value does not need to be passed to that
4292 argument when the function is called.
4293
4294 The first line of the function definition of `beginning-of-buffer'
4295 therefore looks like this:
4296
4297 (defun beginning-of-buffer (&optional arg)
4298
4299 In 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
4311 The function is similar to the `simplified-beginning-of-buffer'
4312 function except that the `interactive' expression has `"P"' as an
4313 argument and the `goto-char' function is followed by an if-then-else
4314 expression that figures out where to put the cursor if there is an
4315 argument.
4316
4317 The `"P"' in the `interactive' expression tells Emacs to pass a
4318 prefix argument, if there is one, to the function. A prefix argument
4319 is 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
4321 to 4).
4322
4323 The true-or-false-test of the `if' expression is simple: it is simply
4324 the argument `arg'. If `arg' has a value that is not `nil', which
4325 will be the case if `beginning-of-buffer' is called with an argument,
4326 then this true-or-false-test will return true and the then-part of
4327 the `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
4330 evaluated. The else-part is simply `point-min', and when this is the
4331 outcome, the whole `goto-char' expression is `(goto-char
4332 (point-min))', which is how we saw the `beginning-of-buffer' function
4333 in its simplified form.
4334
4335 `beginning-of-buffer' with an Argument
4336 --------------------------------------
4337
4338 When `beginning-of-buffer' is called with an argument, an expression
4339 is evaluated which calculates what value to pass to `goto-char'.
4340 This expression is rather complicated at first sight. It includes an
4341 inner `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
4351 Disentangle `beginning-of-buffer'
4352 .................................
4353
4354 Like other complex-looking expressions, the conditional expression
4355 within `beginning-of-buffer' can be disentangled by looking at it as
4356 parts of a template, in this case, the template for an if-then-else
4357 expression. 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
4363 The true-or-false-test of this inner `if' expression checks the size
4364 of the buffer. The reason for this is that the old Version 18 Emacs
4365 used numbers that are no bigger than eight million or so and in the
4366 computation that followed, the programmer feared that Emacs might try
4367 to use over-large numbers if the buffer were large. The term
4368 `overflow', mentioned in the comment, means numbers that are over
4369 large. Version 21 Emacs uses larger numbers, but this code has not
4370 been touched, if only because people now look at buffers that are far,
4371 far larger than ever before.
4372
4373 There are two cases: if the buffer is large and if it is not.
4374
4375 What happens in a large buffer
4376 ..............................
4377
4378 In `beginning-of-buffer', the inner `if' expression tests whether the
4379 size of the buffer is greater than 10,000 characters. To do this, it
4380 uses the `>' function and the `buffer-size' function.
4381
4382 The line looks like this:
4383
4384 (if (> (buffer-size) 10000)
4385
4386 When the buffer is large, the then-part of the `if' expression is
4387 evaluated. It reads like this (after formatting for easy reading):
4388
4389 (*
4390 (prefix-numeric-value arg)
4391 (/ (buffer-size) 10))
4392
4393 This expression is a multiplication, with two arguments to the
4394 function `*'.
4395
4396 The first argument is `(prefix-numeric-value arg)'. When `"P"' is
4397 used as the argument for `interactive', the value passed to the
4398 function as its argument is passed a "raw prefix argument", and not a
4399 number. (It is a number in a list.) To perform the arithmetic, a
4400 conversion is necessary, and `prefix-numeric-value' does the job.
4401
4402 The second argument is `(/ (buffer-size) 10)'. This expression
4403 divides the numeric value of the buffer by ten. This produces a
4404 number that tells how many characters make up one tenth of the buffer
4405 size. (In Lisp, `/' is used for division, just as `*' is used for
4406 multiplication.)
4407
4408 In the multiplication expression as a whole, this amount is multiplied
4409 by the value of the prefix argument--the multiplication looks like
4410 this:
4411
4412 (* NUMERIC-VALUE-OF-PREFIX-ARG
4413 NUMBER-OF-CHARACTERS-IN-ONE-TENTH-OF-THE-BUFFER)
4414
4415 If, for example, the prefix argument is `7', the one-tenth value will
4416 be multiplied by 7 to give a position 70% of the way through the
4417 buffer.
4418
4419 The 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
4425 This puts the cursor where we want it.
4426
4427 What happens in a small buffer
4428 ..............................
4429
4430 If the buffer contains fewer than 10,000 characters, a slightly
4431 different computation is performed. You might think this is not
4432 necessary, since the first computation could do the job. However, in
4433 a small buffer, the first method may not put the cursor on exactly the
4434 desired line; the second method does a better job.
4435
4436 The code looks like this:
4437
4438 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
4439
4440 This is code in which you figure out what happens by discovering how
4441 the functions are embedded in parentheses. It is easier to read if
4442 you reformat it with each expression indented more deeply than its
4443 enclosing expression:
4444
4445 (/
4446 (+ 10
4447 (*
4448 (buffer-size)
4449 (prefix-numeric-value arg)))
4450 10))
4451
4452 Looking at parentheses, we see that the innermost operation is
4453 `(prefix-numeric-value arg)', which converts the raw argument to a
4454 number. This number is multiplied by the buffer size in the following
4455 expression:
4456
4457 (* (buffer-size) (prefix-numeric-value arg)
4458
4459 This multiplication creates a number that may be larger than the size
4460 of the buffer--seven times larger if the argument is 7, for example.
4461 Ten is then added to this number and finally the large number is
4462 divided by ten to provide a value that is one character larger than
4463 the percentage position in the buffer.
4464
4465 The number that results from all this is passed to `goto-char' and
4466 the cursor is moved to that point.
4467
4468 The Complete `beginning-of-buffer'
4469 ----------------------------------
4470
4471 Here 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
4495 Except for two small points, the previous discussion shows how this
4496 function works. The first point deals with a detail in the
4497 documentation string, and the second point concerns the last line of
4498 the function.
4499
4500 In the documentation string, there is reference to an expression:
4501
4502 \(goto-char (point-min))
4503
4504 A `\' is used before the first parenthesis of this expression. This
4505 `\' tells the Lisp interpreter that the expression should be printed
4506 as shown in the documentation rather than evaluated as a symbolic
4507 expression, which is what it looks like.
4508
4509 Finally, the last line of the `beginning-of-buffer' command says to
4510 move point to the beginning of the next line if the command is
4511 invoked with an argument:
4512
4513 (if arg (forward-line 1)))
4514
4515 This puts the cursor at the beginning of the first line after the
4516 appropriate tenths position in the buffer. This is a flourish that
4517 means that the cursor is always located _at least_ the requested
4518 tenths of the way through the buffer, which is a nicety that is,
4519 perhaps, not necessary, but which, if it did not occur, would be sure
4520 to draw complaints.
4521
4522 Review
4523 ======
4524
4525 Here 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
4566 Write an interactive function with an optional argument that tests
4567 whether 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
4569 not pass an argument to the function, use 56 as a default value.
4570
4571 Narrowing and Widening
4572 **********************
4573
4574 Narrowing is a feature of Emacs that makes it possible for you to
4575 focus on a specific part of a buffer, and work without accidentally
4576 changing other parts. Narrowing is normally disabled since it can
4577 confuse novices.
4578
4579 The Advantages of Narrowing
4580 ===========================
4581
4582 With narrowing, the rest of a buffer is made invisible, as if it
4583 weren't there. This is an advantage if, for example, you want to
4584 replace a word in one part of a buffer but not in another: you narrow
4585 to the part you want and the replacement is carried out only in that
4586 section, not in the rest of the buffer. Searches will only work
4587 within a narrowed region, not outside of one, so if you are fixing a
4588 part of a document, you can keep yourself from accidentally finding
4589 parts 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
4592 However, narrowing does make the rest of the buffer invisible, which
4593 can scare people who inadvertently invoke narrowing and think they
4594 have 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
4596 should it), so people can become quite desperate if they do not know
4597 that 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
4600 Narrowing is just as useful to the Lisp interpreter as to a human.
4601 Often, an Emacs Lisp function is designed to work on just part of a
4602 buffer; or conversely, an Emacs Lisp function needs to work on all of
4603 a buffer that has been narrowed. The `what-line' function, for
4604 example, removes the narrowing from a buffer, if it has any narrowing
4605 and when it has finished its job, restores the narrowing to what it
4606 was. On the other hand, the `count-lines' function, which is called
4607 by `what-line', uses narrowing to restrict itself to just that portion
4608 of the buffer in which it is interested and then restores the previous
4609 situation.
4610
4611 The `save-restriction' Special Form
4612 ===================================
4613
4614 In Emacs Lisp, you can use the `save-restriction' special form to
4615 keep track of whatever narrowing is in effect, if any. When the Lisp
4616 interpreter meets with `save-restriction', it executes the code in
4617 the body of the `save-restriction' expression, and then undoes any
4618 changes to narrowing that the code caused. If, for example, the
4619 buffer is narrowed and the code that follows `save-restriction' gets
4620 rid of the narrowing, `save-restriction' returns the buffer to its
4621 narrowed region afterwards. In the `what-line' command, any
4622 narrowing the buffer may have is undone by the `widen' command that
4623 immediately follows the `save-restriction' command. Any original
4624 narrowing is restored just before the completion of the function.
4625
4626 The template for a `save-restriction' expression is simple:
4627
4628 (save-restriction
4629 BODY... )
4630
4631 The body of the `save-restriction' is one or more expressions that
4632 will be evaluated in sequence by the Lisp interpreter.
4633
4634 Finally, 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
4637 may fail to record narrowing in the buffer to which Emacs switches
4638 after 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
4645 In other circumstances, when not written together, the
4646 `save-excursion' and `save-restriction' special forms must be written
4647 in the order appropriate to the function.
4648
4649 For example,
4650
4651 (save-restriction
4652 (widen)
4653 (save-excursion
4654 BODY...))
4655
4656 `what-line'
4657 ===========
4658
4659 The `what-line' command tells you the number of the line in which the
4660 cursor is located. The function illustrates the use of the
4661 `save-restriction' and `save-excursion' commands. Here is the text
4662 of 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
4674 The function has a documentation line and is interactive, as you would
4675 expect. The next two lines use the functions `save-restriction' and
4676 `widen'.
4677
4678 The `save-restriction' special form notes whatever narrowing is in
4679 effect, if any, in the current buffer and restores that narrowing
4680 after the code in the body of the `save-restriction' has been
4681 evaluated.
4682
4683 The `save-restriction' special form is followed by `widen'. This
4684 function undoes any narrowing the current buffer may have had when
4685 `what-line' was called. (The narrowing that was there is the
4686 narrowing that `save-restriction' remembers.) This widening makes it
4687 possible for the line counting commands to count from the beginning
4688 of the buffer. Otherwise, they would have been limited to counting
4689 within the accessible region. Any original narrowing is restored
4690 just before the completion of the function by the `save-restriction'
4691 special form.
4692
4693 The call to `widen' is followed by `save-excursion', which saves the
4694 location of the cursor (i.e., of point) and of the mark, and restores
4695 them 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
4700 write the two `save- ...' expressions in sequence, write
4701 `save-excursion' outermost.)
4702
4703 The last two lines of the `what-line' function are functions to count
4704 the number of lines in the buffer and then print the number in the
4705 echo area.
4706
4707 (message "Line %d"
4708 (1+ (count-lines 1 (point)))))))
4709
4710 The `message' function prints a one-line message at the bottom of the
4711 Emacs screen. The first argument is inside of quotation marks and is
4712 printed as a string of characters. However, it may contain `%d',
4713 `%s', or `%c' to print arguments that follow the string. `%d' prints
4714 the argument as a decimal, so the message will say something such as
4715 `Line 243'.
4716
4717 The number that is printed in place of the `%d' is computed by the
4718 last line of the function:
4719
4720 (1+ (count-lines 1 (point)))
4721
4722 What this does is count the lines from the first position of the
4723 buffer, indicated by the `1', up to `(point)', and then add one to
4724 that number. (The `1+' function adds one to its argument.) We add
4725 one to it because line 2 has only one line before it, and
4726 `count-lines' counts only the lines _before_ the current line.
4727
4728 After `count-lines' has done its job, and the message has been
4729 printed in the echo area, the `save-excursion' restores point and
4730 mark to their original positions; and `save-restriction' restores the
4731 original narrowing, if any.
4732
4733 Exercise with Narrowing
4734 =======================
4735
4736 Write a function that will display the first 60 characters of the
4737 current buffer, even if you have narrowed the buffer to its latter
4738 half so that the first line is inaccessible. Restore point, mark,
4739 and 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
4746 In Lisp, `car', `cdr', and `cons' are fundamental functions. The
4747 `cons' function is used to construct lists, and the `car' and `cdr'
4748 functions are used to take them apart.
4749
4750 In the walk through of the `copy-region-as-kill' function, we will
4751 see `cons' as well as two variants on `cdr', namely, `setcdr' and
4752 `nthcdr'. (*Note copy-region-as-kill::.)
4753
4754 Strange Names
4755 =============
4756
4757 The name of the `cons' function is not unreasonable: it is an
4758 abbreviation of the word `construct'. The origins of the names for
4759 `car' and `cdr', on the other hand, are esoteric: `car' is an acronym
4760 from the phrase `Contents of the Address part of the Register'; and
4761 `cdr' (pronounced `could-er') is an acronym from the phrase `Contents
4762 of the Decrement part of the Register'. These phrases refer to
4763 specific pieces of hardware on the very early computer on which the
4764 original Lisp was developed. Besides being obsolete, the phrases
4765 have been completely irrelevant for more than 25 years to anyone
4766 thinking about Lisp. Nonetheless, although a few brave scholars have
4767 begun to use more reasonable names for these functions, the old terms
4768 are still in use. In particular, since the terms are used in the
4769 Emacs Lisp source code, we will use them in this introduction.
4770
4771 `car' and `cdr'
4772 ===============
4773
4774 The CAR of a list is, quite simply, the first item in the list. Thus
4775 the CAR of the list `(rose violet daisy buttercup)' is `rose'.
4776
4777 If you are reading this in Info in GNU Emacs, you can see this by
4778 evaluating the following:
4779
4780 (car '(rose violet daisy buttercup))
4781
4782 After evaluating the expression, `rose' will appear in the echo area.
4783
4784 Clearly, 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
4788 what it is. After `car' has been applied to a list, the list is
4789 still the same as it was. In the jargon, `car' is `non-destructive'.
4790 This feature turns out to be important.
4791
4792 The CDR of a list is the rest of the list, that is, the `cdr'
4793 function returns the part of the list that follows the first item.
4794 Thus, while the CAR of the list `'(rose violet daisy buttercup)' is
4795 `rose', the rest of the list, the value returned by the `cdr'
4796 function, is `(violet daisy buttercup)'.
4797
4798 You can see this by evaluating the following in the usual way:
4799
4800 (cdr '(rose violet daisy buttercup))
4801
4802 When you evaluate this, `(violet daisy buttercup)' will appear in the
4803 echo area.
4804
4805 Like `car', `cdr' does not remove any elements from the list--it just
4806 returns a report of what the second and subsequent elements are.
4807
4808 Incidentally, in the example, the list of flowers is quoted. If it
4809 were not, the Lisp interpreter would try to evaluate the list by
4810 calling `rose' as a function. In this example, we do not want to do
4811 that.
4812
4813 Clearly, a more reasonable name for `cdr' would be `rest'.
4814
4815 (There is a lesson here: when you name new functions, consider very
4816 carefully what you are doing, since you may be stuck with the names
4817 for far longer than you expect. The reason this document perpetuates
4818 these names is that the Emacs Lisp source code uses them, and if I did
4819 not use them, you would have a hard time reading the code; but do,
4820 please, try to avoid using these terms yourself. The people who come
4821 after you will be grateful to you.)
4822
4823 When `car' and `cdr' are applied to a list made up of symbols, such
4824 as the list `(pine fir oak maple)', the element of the list returned
4825 by the function `car' is the symbol `pine' without any parentheses
4826 around it. `pine' is the first element in the list. However, the
4827 CDR of the list is a list itself, `(fir oak maple)', as you can see
4828 by evaluating the following expressions in the usual way:
4829
4830 (car '(pine fir oak maple))
4831
4832 (cdr '(pine fir oak maple))
4833
4834 On the other hand, in a list of lists, the first element is itself a
4835 list. `car' returns this first element as a list. For example, the
4836 following list contains three sub-lists, a list of carnivores, a list
4837 of herbivores and a list of sea mammals:
4838
4839 (car '((lion tiger cheetah)
4840 (gazelle antelope zebra)
4841 (whale dolphin seal)))
4842
4843 In this example, the first element or CAR of the list is the list of
4844 carnivores, `(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
4851 It is worth saying again that `car' and `cdr' are
4852 non-destructive--that is, they do not modify or change lists to which
4853 they are applied. This is very important for how they are used.
4854
4855 Also, in the first chapter, in the discussion about atoms, I said that
4856 in Lisp, "certain kinds of atom, such as an array, can be separated
4857 into parts; but the mechanism for doing this is different from the
4858 mechanism for splitting a list. As far as Lisp is concerned, the
4859 atoms of a list are unsplittable." (*Note Lisp Atoms::.) The `car'
4860 and `cdr' functions are used for splitting lists and are considered
4861 fundamental to Lisp. Since they cannot split or gain access to the
4862 parts of an array, an array is considered an atom. Conversely, the
4863 other fundamental function, `cons', can put together or construct a
4864 list, but not an array. (Arrays are handled by array-specific
4865 functions. *Note Arrays: (elisp)Arrays.)
4866
4867 `cons'
4868 ======
4869
4870 The `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
4872 from the three element list, `(fir oak maple)':
4873
4874 (cons 'pine '(fir oak maple))
4875
4876 After evaluating this list, you will see
4877
4878 (pine fir oak maple)
4879
4880 appear in the echo area. `cons' causes the creation of a new list in
4881 which the element is followed by the elements of the original list.
4882
4883 We often say that ``cons' puts a new element at the beginning of a
4884 list; it attaches or pushes elements onto the list', but this
4885 phrasing can be misleading, since `cons' does not change an existing
4886 list, but creates a new one.
4887
4888 Like `car' and `cdr', `cons' is non-destructive.
4889
4890 Build a list
4891 ------------
4892
4893 `cons' must have a list to attach to.(1) You cannot start from
4894 absolutely nothing. If you are building a list, you need to provide
4895 at least an empty list at the beginning. Here is a series of `cons'
4896 expressions that build up a list of flowers. If you are reading this
4897 in Info in GNU Emacs, you can evaluate each of the expressions in the
4898 usual way; the value is printed in this text after `=>', which you
4899 may 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
4913 In the first example, the empty list is shown as `()' and a list made
4914 up of `buttercup' followed by the empty list is constructed. As you
4915 can see, the empty list is not shown in the list that was
4916 constructed. All that you see is `(buttercup)'. The empty list is
4917 not counted as an element of a list because there is nothing in an
4918 empty list. Generally speaking, an empty list is invisible.
4919
4920 The second example, `(cons 'daisy '(buttercup))' constructs a new,
4921 two element list by putting `daisy' in front of `buttercup'; and the
4922 third example constructs a three element list by putting `violet' in
4923 front of `daisy' and `buttercup'.
4924
4925 ---------- Footnotes ----------
4926
4927 (1) Actually, you can `cons' an element to an atom to produce a
4928 dotted pair. Dotted pairs are not discussed here; see *Note Dotted
4929 Pair Notation: (elisp)Dotted Pair Notation.
4930
4931 Find the Length of a List: `length'
4932 -----------------------------------
4933
4934 You can find out how many elements there are in a list by using the
4935 Lisp 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
4946 In the third example, the `cons' function is used to construct a
4947 three element list which is then passed to the `length' function as
4948 its argument.
4949
4950 We can also use `length' to count the number of elements in an empty
4951 list:
4952
4953 (length ())
4954 => 0
4955
4956 As you would expect, the number of elements in an empty list is zero.
4957
4958 An interesting experiment is to find out what happens if you try to
4959 find 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
4964 What you see, if you evaluate this, is the error message
4965
4966 Wrong number of arguments: #<subr length>, 0
4967
4968 This means that the function receives the wrong number of arguments,
4969 zero, when it expects some other number of arguments. In this case,
4970 one argument is expected, the argument being a list whose length the
4971 function is measuring. (Note that _one_ list is _one_ argument, even
4972 if the list has many elements inside it.)
4973
4974 The part of the error message that says `#<subr length>' is the name
4975 of the function. This is written with a special notation, `#<subr',
4976 that indicates that the function `length' is one of the primitive
4977 functions written in C rather than in Emacs Lisp. (`subr' is an
4978 abbreviation for `subroutine'.) *Note What Is a Function?:
4979 (elisp)What Is a Function, for more about subroutines.
4980
4981 `nthcdr'
4982 ========
4983
4984 The `nthcdr' function is associated with the `cdr' function. What it
4985 does is take the CDR of a list repeatedly.
4986
4987 If you take the CDR of the list `(pine fir oak maple)', you will be
4988 returned the list `(fir oak maple)'. If you repeat this on what was
4989 returned, you will be returned the list `(oak maple)'. (Of course,
4990 repeated CDRing on the original list will just give you the original
4991 CDR since the function does not change the list. You need to
4992 evaluate the CDR of the CDR and so on.) If you continue this,
4993 eventually you will be returned an empty list, which in this case,
4994 instead of being shown as `()' is shown as `nil'.
4995
4996 For 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
5017 You can also do several CDRs without printing the values in between,
5018 like this:
5019
5020 (cdr (cdr '(pine fir oak maple)))
5021 => (oak maple)
5022
5023 In this example, the Lisp interpreter evaluates the innermost list
5024 first. The innermost list is quoted, so it just passes the list as
5025 it is to the innermost `cdr'. This `cdr' passes a list made up of the
5026 second and subsequent elements of the list to the outermost `cdr',
5027 which produces a list composed of the third and subsequent elements of
5028 the original list. In this example, the `cdr' function is repeated
5029 and returns a list that consists of the original list without its
5030 first two elements.
5031
5032 The `nthcdr' function does the same as repeating the call to `cdr'.
5033 In the following example, the argument 2 is passed to the function
5034 `nthcdr', along with the list, and the value returned is the list
5035 without 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
5041 Using the original four element list, we can see what happens when
5042 various numeric arguments are passed to `nthcdr', including 0, 1, and
5043 5:
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
5068 The `nthcdr' function takes the CDR of a list repeatedly. The `nth'
5069 function takes the CAR of the result returned by `nthcdr'. It
5070 returns the Nth element of the list.
5071
5072 Thus, if it were not defined in C for speed, the definition of `nth'
5073 would 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
5081 definition was redone in C in the 1980s.)
5082
5083 The `nth' function returns a single element of a list. This can be
5084 very convenient.
5085
5086 Note that the elements are numbered from zero, not one. That is to
5087 say, the first element of a list, its CAR is the zeroth element.
5088 This is called `zero-based' counting and often bothers people who are
5089 accustomed to the first element in a list being number one, which is
5090 `one-based'.
5091
5092 For example:
5093
5094 (nth 0 '("one" "two" "three"))
5095 => "one"
5096
5097 (nth 1 '("one" "two" "three"))
5098 => "two"
5099
5100 It is worth mentioning that `nth', like `nthcdr' and `cdr', does not
5101 change the original list--the function is non-destructive. This is
5102 in sharp contrast to the `setcar' and `setcdr' functions.
5103
5104 `setcar'
5105 ========
5106
5107 As you might guess from their names, the `setcar' and `setcdr'
5108 functions set the CAR or the CDR of a list to a new value. They
5109 actually change the original list, unlike `car' and `cdr' which leave
5110 the original list as it was. One way to find out how this works is
5111 to experiment. We will start with the `setcar' function.
5112
5113 First, we can make a list and then set the value of a variable to the
5114 list, using the `setq' function. Here is a list of animals:
5115
5116 (setq animals '(antelope giraffe lion tiger))
5117
5118 If you are reading this in Info inside of GNU Emacs, you can evaluate
5119 this expression in the usual fashion, by positioning the cursor after
5120 the expression and typing `C-x C-e'. (I'm doing this right here as I
5121 write this. This is one of the advantages of having the interpreter
5122 built into the computing environment.)
5123
5124 When we evaluate the variable `animals', we see that it is bound to
5125 the list `(antelope giraffe lion tiger)':
5126
5127 animals
5128 => (antelope giraffe lion tiger)
5129
5130 Put another way, the variable `animals' points to the list `(antelope
5131 giraffe lion tiger)'.
5132
5133 Next, evaluate the function `setcar' while passing it two arguments,
5134 the variable `animals' and the quoted symbol `hippopotamus'; this is
5135 done by writing the three element list `(setcar animals
5136 'hippopotamus)' and then evaluating it in the usual fashion:
5137
5138 (setcar animals 'hippopotamus)
5139
5140 After evaluating this expression, evaluate the variable `animals'
5141 again. You will see that the list of animals has changed:
5142
5143 animals
5144 => (hippopotamus giraffe lion tiger)
5145
5146 The first element on the list, `antelope' is replaced by
5147 `hippopotamus'.
5148
5149 So 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
5156 The `setcdr' function is similar to the `setcar' function, except
5157 that the function replaces the second and subsequent elements of a
5158 list rather than the first element.
5159
5160 To see how this works, set the value of the variable to a list of
5161 domesticated animals by evaluating the following expression:
5162
5163 (setq domesticated-animals '(horse cow sheep goat))
5164
5165 If you now evaluate the list, you will be returned the list `(horse
5166 cow sheep goat)':
5167
5168 domesticated-animals
5169 => (horse cow sheep goat)
5170
5171 Next, evaluate `setcdr' with two arguments, the name of the variable
5172 which has a list as its value, and the list to which the CDR of the
5173 first list will be set;
5174
5175 (setcdr domesticated-animals '(cat dog))
5176
5177 If you evaluate this expression, the list `(cat dog)' will appear in
5178 the echo area. This is the value returned by the function. The
5179 result we are interested in is the "side effect", which we can see by
5180 evaluating the variable `domesticated-animals':
5181
5182 domesticated-animals
5183 => (horse cat dog)
5184
5185 Indeed, the list is changed from `(horse cow sheep goat)' to `(horse
5186 cat dog)'. The CDR of the list is changed from `(cow sheep goat)' to
5187 `(cat dog)'.
5188
5189 Exercise
5190 ========
5191
5192 Construct a list of four birds by evaluating several expressions with
5193 `cons'. Find out what happens when you `cons' a list onto itself.
5194 Replace the first element of the list of four birds with a fish.
5195 Replace the rest of that list with a list of other fish.
5196
5197 Cutting and Storing Text
5198 ************************
5199
5200 Whenever you cut or clip text out of a buffer with a `kill' command in
5201 GNU 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
5206 historical accident. A much more appropriate word would be `clip'
5207 since that is what the kill commands do; they clip text out of a
5208 buffer and put it into storage from which it can be brought back. I
5209 have often been tempted to replace globally all occurrences of `kill'
5210 in the Emacs sources with `clip' and all occurrences of `killed' with
5211 `clipped'.)
5212
5213 Storing Text in a List
5214 ======================
5215
5216 When text is cut out of a buffer, it is stored on a list. Successive
5217 pieces of text are stored on the list successively, so the list might
5218 look like this:
5219
5220 ("a piece of text" "previous piece")
5221
5222 The function `cons' can be used to to create a new list from a piece
5223 of text (an `atom', to use the jargon) and an existing list, like
5224 this:
5225
5226 (cons "another piece"
5227 '("a piece of text" "previous piece"))
5228
5229 If you evaluate this expression, a list of three elements will appear
5230 in the echo area:
5231
5232 ("another piece" "a piece of text" "previous piece")
5233
5234 With the `car' and `nthcdr' functions, you can retrieve whichever
5235 piece of text you want. For example, in the following code, `nthcdr
5236 1 ...' returns the list with the first item removed; and the `car'
5237 returns the first element of that remainder--the second element of
5238 the original list:
5239
5240 (car (nthcdr 1 '("another piece"
5241 "a piece of text"
5242 "previous piece")))
5243 => "a piece of text"
5244
5245 The actual functions in Emacs are more complex than this, of course.
5246 The code for cutting and retrieving text has to be written so that
5247 Emacs can figure out which element in the list you want--the first,
5248 second, third, or whatever. In addition, when you get to the end of
5249 the list, Emacs should give you the first element of the list, rather
5250 than nothing at all.
5251
5252 The list that holds the pieces of text is called the "kill ring".
5253 This chapter leads up to a description of the kill ring and how it is
5254 used by first tracing how the `zap-to-char' function works. This
5255 function uses (or `calls') a function that invokes a function that
5256 manipulates the kill ring. Thus, before reaching the mountains, we
5257 climb the foothills.
5258
5259 A subsequent chapter describes how text that is cut from the buffer is
5260 retrieved. *Note Yanking Text Back: Yanking.
5261
5262 `zap-to-char'
5263 =============
5264
5265 The `zap-to-char' function barely changed between GNU Emacs version
5266 19 and GNU Emacs version 21. However, `zap-to-char' calls another
5267 function, `kill-region', which enjoyed a major rewrite on the way to
5268 version 21.
5269
5270 The `kill-region' function in Emacs 19 is complex, but does not use
5271 code that is important at this time. We will skip it.
5272
5273 The `kill-region' function in Emacs 21 is easier to read than the
5274 same function in Emacs 19 and introduces a very important concept,
5275 that of error handling. We will walk through the function.
5276
5277 But first, let us look at the interactive `zap-to-char' function.
5278
5279 The Complete `zap-to-char' Implementation
5280 -----------------------------------------
5281
5282 The GNU Emacs version 19 and version 21 implementations of the
5283 `zap-to-char' function are nearly identical in form, and they work
5284 alike. The function removes the text in the region between the
5285 location of the cursor (i.e., of point) up to and including the next
5286 occurrence of a specified character. The text that `zap-to-char'
5287 removes is put in the kill ring; and it can be retrieved from the kill
5288 ring by typing `C-y' (`yank'). If the command is given an argument,
5289 it removes text through that number of occurrences. Thus, if the
5290 cursor were at the beginning of this sentence and the character were
5291 `s', `Thus' would be removed. If the argument were two, `Thus, if
5292 the curs' would be removed, up to and including the `s' in `cursor'.
5293
5294 If the specified character is not found, `zap-to-char' will say
5295 "Search failed", tell you the character you typed, and not remove any
5296 text.
5297
5298 In order to determine how much text to remove, `zap-to-char' uses a
5299 search function. Searches are used extensively in code that
5300 manipulates text, and we will focus attention on them as well as on
5301 the deletion command.
5302
5303 Here is the complete text of the version 19 implementation of the
5304 function:
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
5316 The `interactive' Expression
5317 ----------------------------
5318
5319 The interactive expression in the `zap-to-char' command looks like
5320 this:
5321
5322 (interactive "*p\ncZap to char: ")
5323
5324 The part within quotation marks, `"*p\ncZap to char: "', specifies
5325 three different things. First, and most simply, the asterisk, `*',
5326 causes an error to be signalled if the buffer is read-only. This
5327 means that if you try `zap-to-char' in a read-only buffer you will
5328 not 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
5331 The version 21 implementation does not have the asterisk, `*'. The
5332 function works the same as in version 19: in both cases, it cannot
5333 remove text from a read-only buffer but the function does copy the
5334 text that would have been removed to the kill ring. Also, in both
5335 cases, you see an error message.
5336
5337 However, the version 19 implementation copies text from a read-only
5338 buffer only because of a mistake in the implementation of
5339 `interactive'. According to the documentation for `interactive', the
5340 asterisk, `*', should prevent the `zap-to-char' function from doing
5341 anything at all when the buffer is read only. The function should
5342 not copy the text to the kill ring. It is a bug that it does.
5343
5344 In version 21, `interactive' is implemented correctly. So the
5345 asterisk, `*', had to be removed from the interactive specification.
5346 If you insert an `*' and evaluate the function definition, then the
5347 next time you run the `zap-to-char' function on a read-only buffer,
5348 you will not copy any text.
5349
5350 That change aside, and a change to the documentation, the two versions
5351 of the `zap-to-char' function are identical.
5352
5353 Let us continue with the interactive specification.
5354
5355 The second part of `"*p\ncZap to char: "' is the `p'. This part is
5356 separated from the next part by a newline, `\n'. The `p' means that
5357 the first argument to the function will be passed the value of a
5358 `processed prefix'. The prefix argument is passed by typing `C-u'
5359 and a number, or `M-' and a number. If the function is called
5360 interactively without a prefix, 1 is passed to this argument.
5361
5362 The third part of `"*p\ncZap to char: "' is `cZap to char: '. In
5363 this part, the lower case `c' indicates that `interactive' expects a
5364 prompt and that the argument will be a character. The prompt follows
5365 the `c' and is the string `Zap to char: ' (with a space after the
5366 colon to make it look good).
5367
5368 What all this does is prepare the arguments to `zap-to-char' so they
5369 are of the right type, and give the user a prompt.
5370
5371 The Body of `zap-to-char'
5372 -------------------------
5373
5374 The 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
5376 of the cursor up to and including the specified character. The first
5377 part of the code looks like this:
5378
5379 (kill-region (point) ...
5380
5381 `(point)' is the current position of the cursor.
5382
5383 The next part of the code is an expression using `progn'. The body
5384 of the `progn' consists of calls to `search-forward' and `point'.
5385
5386 It 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
5390 The `search-forward' Function
5391 -----------------------------
5392
5393 The `search-forward' function is used to locate the
5394 zapped-for-character in `zap-to-char'. If the search is successful,
5395 `search-forward' leaves point immediately after the last character in
5396 the target string. (In `zap-to-char', the target string is just one
5397 character long.) If the search is backwards, `search-forward' leaves
5398 point 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
5402 In `zap-to-char', the `search-forward' function looks like this:
5403
5404 (search-forward (char-to-string char) nil nil arg)
5405
5406 The `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
5441 In 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
5448 We will look at `progn' next.
5449
5450 The `progn' Special Form
5451 ------------------------
5452
5453 `progn' is a special form that causes each of its arguments to be
5454 evaluated in sequence and then returns the value of the last one. The
5455 preceding expressions are evaluated only for the side effects they
5456 perform. The values produced by them are discarded.
5457
5458 The template for a `progn' expression is very simple:
5459
5460 (progn
5461 BODY...)
5462
5463 In `zap-to-char', the `progn' expression has to do two things: put
5464 point in exactly the right position; and return the location of point
5465 so that `kill-region' will know how far to kill to.
5466
5467 The first argument to the `progn' is `search-forward'. When
5468 `search-forward' finds the string, the function leaves point
5469 immediately after the last character in the target string. (In this
5470 case the target string is just one character long.) If the search is
5471 backwards, `search-forward' leaves point just before the first
5472 character in the target. The movement of point is a side effect.
5473
5474 The second and last argument to `progn' is the expression `(point)'.
5475 This expression returns the value of point, which in this case will
5476 be the location to which it has been moved by `search-forward'. This
5477 value is returned by the `progn' expression and is passed to
5478 `kill-region' as `kill-region''s second argument.
5479
5480 Summing up `zap-to-char'
5481 ------------------------
5482
5483 Now that we have seen how `search-forward' and `progn' work, we can
5484 see how the `zap-to-char' function works as a whole.
5485
5486 The first argument to `kill-region' is the position of the cursor
5487 when the `zap-to-char' command is given--the value of point at that
5488 time. Within the `progn', the search function then moves point to
5489 just after the zapped-to-character and `point' returns the value of
5490 this location. The `kill-region' function puts together these two
5491 values of point, the first one as the beginning of the region and the
5492 second one as the end of the region, and removes the region.
5493
5494 The `progn' special form is necessary because the `kill-region'
5495 command takes two arguments; and it would fail if `search-forward'
5496 and `point' expressions were written in sequence as two additional
5497 arguments. The `progn' expression is a single argument to
5498 `kill-region' and returns the one value that `kill-region' needs for
5499 its second argument.
5500
5501 `kill-region'
5502 =============
5503
5504 The `zap-to-char' function uses the `kill-region' function. This
5505 function clips text from a region and copies that text to the kill
5506 ring, from which it may be retrieved.
5507
5508 The 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
5512 In essence, the `kill-region' function calls `condition-case', which
5513 takes three arguments. In this function, the first argument does
5514 nothing. The second argument contains the code that does the work
5515 when all goes well. The third argument contains the code that is
5516 called in the event of an error.
5517
5518 The Complete `kill-region' Definition
5519 -------------------------------------
5520
5521 We will go through the `condition-case' code in a moment. First, let
5522 us look at the complete definition of `kill-region', with comments
5523 added:
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
5575 As we have seen earlier (*note Generate an Error Message: Making
5576 Errors.), when the Emacs Lisp interpreter has trouble evaluating an
5577 expression, it provides you with help; in the jargon, this is called
5578 "signaling an error". Usually, the computer stops the program and
5579 shows you a message.
5580
5581 However, some programs undertake complicated actions. They should not
5582 simply stop on an error. In the `kill-region' function, the most
5583 likely error is that you will try to kill text that is read-only and
5584 cannot be removed. So the `kill-region' function contains code to
5585 handle this circumstance. This code, which makes up the body of the
5586 `kill-region' function, is inside of a `condition-case' special form.
5587
5588 The template for `condition-case' looks like this:
5589
5590 (condition-case
5591 VAR
5592 BODYFORM
5593 ERROR-HANDLER...)
5594
5595 The second argument, BODYFORM, is straightforward. The
5596 `condition-case' special form causes the Lisp interpreter to evaluate
5597 the code in BODYFORM. If no error occurs, the special form returns
5598 the code's value and produces the side-effects, if any.
5599
5600 In short, the BODYFORM part of a `condition-case' expression
5601 determines what should happen when everything works correctly.
5602
5603 However, if an error occurs, among its other actions, the function
5604 generating the error signal will define one or more error condition
5605 names.
5606
5607 An error handler is the third argument to `condition case'. An error
5608 handler has two parts, a CONDITION-NAME and a BODY. If the
5609 CONDITION-NAME part of an error handler matches a condition name
5610 generated by an error, then the BODY part of the error handler is run.
5611
5612 As you will expect, the CONDITION-NAME part of an error handler may
5613 be either a single condition name or a list of condition names.
5614
5615 Also, a complete `condition-case' expression may contain more than
5616 one error handler. When an error occurs, the first applicable
5617 handler is run.
5618
5619 Lastly, the first argument to the `condition-case' expression, the
5620 VAR argument, is sometimes bound to a variable that contains
5621 information about the error. However, if that argument is nil, as is
5622 the case in `kill-region', that information is discarded.
5623
5624 In brief, in the `kill-region' function, the code `condition-case'
5625 works 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
5633 A `condition-case' expression has two parts, a part that is evaluated
5634 in the expectation that all will go well, but which may generate an
5635 error; and a part that is evaluated when there is an error.
5636
5637 First, let us look at the code in `kill-region' that is run in the
5638 expectation that all goes well. This is the core of the function.
5639 The 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
5648 It looks complicated because we have the new functions
5649 `delete-and-extract-region', `kill-append', and `kill-new' as well as
5650 the new variables, `last-command' and `this-command'.
5651
5652 The `delete-and-extract-region' function is straightforward. It is a
5653 built-in function that deletes the text in a region (a side effect)
5654 and also returns that text. This is the function that actually
5655 removes the text. (And if it cannot do that, it signals the error.)
5656
5657 In this `let' expression, the text that `delete-and-extract-region'
5658 returns is placed in the local variable called `string'. This is the
5659 text that is removed from the buffer. (To be more precise, the
5660 variable is set to point to the address of the extracted text; to say
5661 it is `placed in' the variable is simply a shorthand.)
5662
5663 If the variable `string' does point to text, that text is added to
5664 the kill ring. The variable will have a `nil' value if no text was
5665 removed.
5666
5667 The code uses `when' to determine whether the variable `string'
5668 points to text. A `when' statement is simply a programmers'
5669 convenience. A `when' statement is an `if' statement without the
5670 possibility of an else clause. In your mind, you can replace `when'
5671 with `if' and understand what goes on. That is what the Lisp
5672 interpreter does.
5673
5674 Technically speaking, `when' is a Lisp macro. A Lisp "macro" enables
5675 you to define new control constructs and other language features. It
5676 tells the interpreter how to compute another Lisp expression which
5677 will in turn compute the value. In this case, the `other expression'
5678 is an `if' expression. For more about Lisp macros, see *Note Macros:
5679 (elisp)Macros. The C programming language also provides macros.
5680 These are different, but also useful. We will briefly look at C
5681 macros in *Note Digression into C::.
5682
5683 If the string has content, then another conditional expression is
5684 executed. 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
5690 The 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
5694 seen before. Normally, whenever a function is executed, Emacs sets
5695 the value of `last-command' to the previous command.
5696
5697 In this segment of the definition, the `if' expression checks whether
5698 the previous command was `kill-region'. If it was,
5699
5700 (kill-append string (< end beg))
5701
5702 concatenates a copy of the newly clipped text to the just previously
5703 clipped text in the kill ring. (If the `(< end beg))' expression is
5704 true, `kill-append' prepends the string to the just previously
5705 clipped text. For a detailed discussion, see *Note The `kill-append'
5706 function: kill-append function.)
5707
5708 If you then yank back the text, i.e., `paste' it, you get both pieces
5709 of text at once. That way, if you delete two words in a row, and
5710 then yank them back, you get both words, in their proper order, with
5711 one yank. (The `(< end beg))' expression makes sure the order is
5712 correct.)
5713
5714 On the other hand, if the previous command is not `kill-region', then
5715 the `kill-new' function is called, which adds the text to the kill
5716 ring as the latest item, and sets the `kill-ring-yank-pointer'
5717 variable to point to it.
5718
5719 Digression into C
5720 =================
5721
5722 The `zap-to-char' command uses the `delete-and-extract-region'
5723 function, which in turn uses two other functions,
5724 `copy-region-as-kill' and `del_range_1'. The `copy-region-as-kill'
5725 function will be described in a following section; it puts a copy of
5726 the region in the kill ring so it can be yanked back. (*Note
5727 `copy-region-as-kill': copy-region-as-kill.)
5728
5729 The `delete-and-extract-region' function removes the contents of a
5730 region and you cannot get them back.
5731
5732 Unlike the other code discussed here, `delete-and-extract-region' is
5733 not written in Emacs Lisp; it is written in C and is one of the
5734 primitives of the GNU Emacs system. Since it is very simple, I will
5735 digress briefly from Lisp and describe it here.
5736
5737 Like many of the other Emacs primitives, `delete-and-extract-region'
5738 is written as an instance of a C macro, a macro being a template for
5739 code. 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
5751 Without going into the details of the macro writing process, let me
5752 point out that this macro starts with the word `DEFUN'. The word
5753 `DEFUN' was chosen since the code serves the same purpose as `defun'
5754 does in Lisp. The word `DEFUN' is followed by seven parts inside of
5755 parentheses:
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
5797 In a C macro, the formal parameters come next, with a statement of
5798 what kind of object they are, followed by what might be called the
5799 `body' of the macro. For `delete-and-extract-region' the `body'
5800 consists of the following two lines:
5801
5802 validate_region (&start, &end);
5803 return del_range_1 (XINT (start), XINT (end), 1, 1);
5804
5805 The first function, `validate_region' checks whether the values
5806 passed as the beginning and end of the region are the proper type and
5807 are within range. The second function, `del_range_1', actually
5808 deletes the text.
5809
5810 `del_range_1' is a complex function we will not look into. It
5811 updates the buffer and does other things.
5812
5813 However, it is worth looking at the two arguments passed to
5814 `del_range'. These are `XINT (start)' and `XINT (end)'.
5815
5816 As far as the C language is concerned, `start' and `end' are two
5817 integers that mark the beginning and end of the region to be
5818 deleted(1).
5819
5820 In early versions of Emacs, these two numbers were thirty-two bits
5821 long, but the code is slowly being generalized to handle other
5822 lengths. Three of the available bits are used to specify the type of
5823 information and a fourth bit is used for handling the computer's
5824 memory; the remaining bits are used as `content'.
5825
5826 `XINT' is a C macro that extracts the relevant number from the longer
5827 collection of bits; the four other bits are discarded.
5828
5829 The command in `delete-and-extract-region' looks like this:
5830
5831 del_range_1 (XINT (start), XINT (end), 1, 1);
5832
5833 It deletes the region between the beginning position, `start', and
5834 the ending position, `end'.
5835
5836 From the point of view of the person writing Lisp, Emacs is all very
5837 simple; but hidden underneath is a great deal of complexity to make it
5838 all work.
5839
5840 ---------- Footnotes ----------
5841
5842 (1) More precisely, and requiring more expert knowledge to
5843 understand, the two integers are of type `Lisp_Object', which can
5844 also be a C union instead of an integer type.
5845
5846 Initializing a Variable with `defvar'
5847 =====================================
5848
5849 Unlike the `delete-and-extract-region' function, the
5850 `copy-region-as-kill' function is written in Emacs Lisp. Two
5851 functions within it, `kill-append' and `kill-new', copy a region in a
5852 buffer and save it in a variable called the `kill-ring'. This
5853 section describes how the `kill-ring' variable is created and
5854 initialized using the `defvar' special form.
5855
5856 (Again we note that the term `kill-ring' is a misnomer. The text
5857 that is clipped out of the buffer can be brought back; it is not a
5858 ring of corpses, but a ring of resurrectable text.)
5859
5860 In Emacs Lisp, a variable such as the `kill-ring' is created and
5861 given an initial value by using the `defvar' special form. The name
5862 comes from "define variable".
5863
5864 The `defvar' special form is similar to `setq' in that it sets the
5865 value of a variable. It is unlike `setq' in two ways: first, it only
5866 sets the value of the variable if the variable does not already have
5867 a value. If the variable already has a value, `defvar' does not
5868 override the existing value. Second, `defvar' has a documentation
5869 string.
5870
5871 (Another special form, `defcustom', is designed for variables that
5872 people customize. It has more features than `defvar'. (*Note
5873 Setting Variables with `defcustom': defcustom.)
5874
5875 Seeing the Current Value of a Variable
5876 --------------------------------------
5877
5878 You can see the current value of a variable, any variable, by using
5879 the `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
5882 ring--this may be quite a lot! Conversely, if you have been doing
5883 nothing this Emacs session except read this document, you may have
5884 nothing 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
5896 The 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
5902 In this variable definition, the variable is given an initial value of
5903 `nil', which makes sense, since if you have saved nothing, you want
5904 nothing back if you give a `yank' command. The documentation string
5905 is written just like the documentation string of a `defun'. As with
5906 the documentation string of the `defun', the first line of the
5907 documentation should be a complete sentence, since some commands,
5908 like `apropos', print only the first line of documentation.
5909 Succeeding lines should not be indented; otherwise they look odd when
5910 you use `C-h v' (`describe-variable').
5911
5912 `defvar' and an asterisk
5913 ------------------------
5914
5915 In the past, Emacs used the `defvar' special form both for internal
5916 variables that you would not expect a user to change and for
5917 variables that you do expect a user to change. Although you can still
5918 use `defvar' for user customizable variables, please use `defcustom'
5919 instead, since that special form provides a path into the
5920 Customization commands. (*Note Setting Variables with `defcustom':
5921 defcustom.)
5922
5923 When you specified a variable using the `defvar' special form, you
5924 could distinguish a readily settable variable from others by typing
5925 an asterisk, `*', in the first column of its documentation string.
5926 For example:
5927
5928 (defvar shell-command-default-error-buffer nil
5929 "*Buffer name for `shell-command' ... error output.
5930 ... ")
5931
5932 This means that you could (and still can) use the `edit-options'
5933 command to change the value of `shell-command-default-error-buffer'
5934 temporarily.
5935
5936 However, options set using `edit-options' are set only for the
5937 duration of your editing session. The new values are not saved
5938 between sessions. Each time Emacs starts, it reads the original
5939 value, unless you change the value within your `.emacs' file, either
5940 by setting it manually or by using `customize'. *Note Your `.emacs'
5941 File: Emacs Initialization.
5942
5943 For me, the major use of the `edit-options' command is to suggest
5944 variables that I might want to set in my `.emacs' file. I urge you
5945 to look through the list. (*Note Editing Variable Values:
5946 (emacs)Edit Options.)
5947
5948 `copy-region-as-kill'
5949 =====================
5950
5951 The `copy-region-as-kill' function copies a region of text from a
5952 buffer and (via either `kill-append' or `kill-new') saves it in the
5953 `kill-ring'.
5954
5955 If you call `copy-region-as-kill' immediately after a `kill-region'
5956 command, Emacs appends the newly copied text to the previously copied
5957 text. This means that if you yank back the text, you get it all,
5958 from both this and the previous operation. On the other hand, if
5959 some other command precedes the `copy-region-as-kill', the function
5960 copies the text into a separate entry in the kill ring.
5961
5962 The complete `copy-region-as-kill' function definition
5963 ------------------------------------------------------
5964
5965 Here is the complete text of the version 21 `copy-region-as-kill'
5966 function:
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
5981 As 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
5988 The arguments are `beg' and `end' and the function is interactive
5989 with `"r"', so the two arguments must refer to the beginning and end
5990 of the region. If you have been reading though this document from
5991 the beginning, understanding these parts of a function is almost
5992 becoming routine.
5993
5994 The documentation is somewhat confusing unless you remember that the
5995 word `kill' has a meaning different from its usual meaning. The
5996 `Transient Mark' and `interprogram-cut-function' comments explain
5997 certain side-effects.
5998
5999 After you once set a mark, a buffer always contains a region. If you
6000 wish, you can use Transient Mark mode to highlight the region
6001 temporarily. (No one wants to highlight the region all the time, so
6002 Transient Mark mode highlights it only at appropriate times. Many
6003 people turn off Transient Mark mode, so the region is never
6004 highlighted.)
6005
6006 Also, a windowing system allows you to copy, cut, and paste among
6007 different programs. In the X windowing system, for example, the
6008 `interprogram-cut-function' function is `x-select-text', which works
6009 with the windowing system's equivalent of the Emacs kill ring.
6010
6011 The body of the `copy-region-as-kill' function starts with an `if'
6012 clause. What this clause does is distinguish between two different
6013 situations: whether or not this command is executed immediately after
6014 a previous `kill-region' command. In the first case, the new region
6015 is appended to the previously copied text. Otherwise, it is inserted
6016 into the beginning of the kill ring as a separate piece of text from
6017 the previous piece.
6018
6019 The last two lines of the function prevent the region from lighting up
6020 if Transient Mark mode is turned on.
6021
6022 The body of `copy-region-as-kill' merits discussion in detail.
6023
6024 The Body of `copy-region-as-kill'
6025 ---------------------------------
6026
6027 The `copy-region-as-kill' function works in much the same way as the
6028 `kill-region' function (*note `kill-region': kill-region.). Both are
6029 written so that two or more kills in a row combine their text into a
6030 single entry. If you yank back the text from the kill ring, you get
6031 it all in one piece. Moreover, kills that kill forward from the
6032 current position of the cursor are added to the end of the previously
6033 copied text and commands that copy text backwards add it to the
6034 beginning of the previously copied text. This way, the words in the
6035 text stay in the proper order.
6036
6037 Like `kill-region', the `copy-region-as-kill' function makes use of
6038 the `last-command' variable that keeps track of the previous Emacs
6039 command.
6040
6041 `last-command' and `this-command'
6042 .................................
6043
6044 Normally, whenever a function is executed, Emacs sets the value of
6045 `this-command' to the function being executed (which in this case
6046 would be `copy-region-as-kill'). At the same time, Emacs sets the
6047 value of `last-command' to the previous value of `this-command'.
6048
6049 In the first part of the body of the `copy-region-as-kill' function,
6050 an `if' expression determines whether the value of `last-command' is
6051 `kill-region'. If so, the then-part of the `if' expression is
6052 evaluated; it uses the `kill-append' function to concatenate the text
6053 copied at this call to the function with the text already in the
6054 first element (the CAR) of the kill ring. On the other hand, if the
6055 value of `last-command' is not `kill-region', then the
6056 `copy-region-as-kill' function attaches a new element to the kill
6057 ring using the `kill-new' function.
6058
6059 The `if' expression reads as follows; it uses `eq', which is a
6060 function 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
6068 The `eq' function tests whether its first argument is the same Lisp
6069 object 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
6071 in that it determines whether two representations are actually the
6072 same object inside the computer, but with different names. `equal'
6073 determines whether the structure and contents of two expressions are
6074 the same.
6075
6076 If the previous command was `kill-region', then the Emacs Lisp
6077 interpreter calls the `kill-append' function
6078
6079 The `kill-append' function
6080 ..........................
6081
6082 The `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
6094 The `kill-append' function is fairly straightforward. It uses the
6095 `kill-new' function, which we will discuss in more detail in a moment.
6096
6097 First, let us look at the conditional that is one of the two arguments
6098 to `kill-new'. It uses `concat' to concatenate the new text to the
6099 CAR of the kill ring. Whether it prepends or appends the text
6100 depends 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
6106 If the region being killed is before the region that was killed in the
6107 last command, then it should be prepended before the material that was
6108 saved in the previous kill; and conversely, if the killed text follows
6109 what was just killed, it should be appended after the previous text.
6110 The `if' expression depends on the predicate `before-p' to decide
6111 whether the newly saved text should be put before or after the
6112 previously saved text.
6113
6114 The symbol `before-p' is the name of one of the arguments to
6115 `kill-append'. When the `kill-append' function is evaluated, it is
6116 bound to the value returned by evaluating the actual argument. In
6117 this case, this is the expression `(< end beg)'. This expression
6118 does not directly determine whether the killed text in this command
6119 is located before or after the kill text of the last command; what is
6120 does is determine whether the value of the variable `end' is less
6121 than the value of the variable `beg'. If it is, it means that the
6122 user is most likely heading towards the beginning of the buffer.
6123 Also, the result of evaluating the predicate expression, `(< end
6124 beg)', will be true and the text will be prepended before the
6125 previous text. On the other hand, if the value of the variable `end'
6126 is greater than the value of the variable `beg', the text will be
6127 appended after the previous text.
6128
6129 When the newly saved text will be prepended, then the string with the
6130 new text will be concatenated before the old text:
6131
6132 (concat string (car kill-ring))
6133
6134 But if the text will be appended, it will be concatenated after the
6135 old text:
6136
6137 (concat (car kill-ring) string))
6138
6139 To understand how this works, we first need to review the `concat'
6140 function. The `concat' function links together or unites two strings
6141 of 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
6154 We can now make sense of `kill-append': it modifies the contents of
6155 the kill ring. The kill ring is a list, each element of which is
6156 saved text. The `kill-append' function uses the `kill-new' function
6157 which in turn uses the `setcar' function.
6158
6159 The `kill-new' function
6160 .......................
6161
6162 The `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
6181 As usual, we can look at this function in parts.
6182
6183 The first line of the documentation makes sense:
6184
6185 Make STRING the latest kill in the kill ring.
6186
6187 Let's skip over the rest of the documentation for the moment.
6188
6189 Also, let's skip over the first two lines of code, those involving
6190 `menu-bar-update-yank-menu'. We will explain them below.
6191
6192 The 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
6206 The conditional test is `(and replace kill-ring)'. This will be true
6207 when two conditions are met: the kill ring has something in it, and
6208 the `replace' variable is true.
6209
6210 The `kill-append' function sets `replace' to be true; then, when the
6211 kill ring has at least one item in it, the `setcar' expression is
6212 executed:
6213
6214 (setcar kill-ring string)
6215
6216 The `setcar' function actually changes the first element of the
6217 `kill-ring' list to the value of `string'. It replaces the first
6218 element.
6219
6220 On the other hand, if the kill ring is empty, or replace is false, the
6221 else-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
6227 This expression first constructs a new version of the kill ring by
6228 prepending `string' to the existing kill ring as a new element. Then
6229 it executes a second `if' clause. This second `if' clause keeps the
6230 kill ring from growing too long.
6231
6232 Let's look at these two expressions in order.
6233
6234 The `setq' line of the else-part sets the new value of the kill ring
6235 to what results from adding the string being killed to the old kill
6236 ring.
6237
6238 We can see how this works with an example:
6239
6240 (setq example-list '("here is a clause" "another clause"))
6241
6242 After 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
6248 Now, we can add a new element on to this list by evaluating the
6249 following expression:
6250
6251 (setq example-list (cons "a third clause" example-list))
6252
6253 When we evaluate `example-list', we find its value is:
6254
6255 example-list
6256 => ("a third clause" "here is a clause" "another clause")
6257
6258 Thus, the third clause was added to the list by `cons'.
6259
6260 This is exactly similar to what the `setq' and `cons' do in the
6261 function. Here is the line again:
6262
6263 (setq kill-ring (cons string kill-ring))
6264
6265 Now for the second part of the `if' clause. This expression keeps
6266 the 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
6271 The code checks whether the length of the kill ring is greater than
6272 the 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
6274 long, then this code sets the last element of the kill ring to `nil'.
6275 It does this by using two functions, `nthcdr' and `setcdr'.
6276
6277 We looked at `setcdr' earlier (*note `setcdr': setcdr.). It sets the
6278 CDR of a list, just as `setcar' sets the CAR of a list. In this
6279 case, however, `setcdr' will not be setting the CDR of the whole kill
6280 ring; the `nthcdr' function is used to cause it to set the CDR of the
6281 next to last element of the kill ring--this means that since the CDR
6282 of the next to last element is the last element of the kill ring, it
6283 will set the last element of the kill ring.
6284
6285 The `nthcdr' function works by repeatedly taking the CDR of a
6286 list--it takes the CDR of the CDR of the CDR ... It does this N
6287 times and returns the results.
6288
6289 Thus, if we had a four element list that was supposed to be three
6290 elements long, we could set the CDR of the next to last element to
6291 `nil', and thereby shorten the list.
6292
6293 You can see this by evaluating the following three expressions in
6294 turn. First set the value of `trees' to `(maple oak pine birch)',
6295 then set the CDR of its second CDR to `nil' and then find the value
6296 of `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
6308 what the CDR is set to.)
6309
6310 To repeat, in `kill-new', the `nthcdr' function takes the CDR a
6311 number of times that is one less than the maximum permitted size of
6312 the kill ring and sets the CDR of that element (which will be the
6313 rest of the elements in the kill ring) to `nil'. This prevents the
6314 kill ring from growing too long.
6315
6316 The next to last expression in the `kill-new' function is
6317
6318 (setq kill-ring-yank-pointer kill-ring)
6319
6320 The `kill-ring-yank-pointer' is a global variable that is set to be
6321 the `kill-ring'.
6322
6323 Even though the `kill-ring-yank-pointer' is called a `pointer', it is
6324 a variable just like the kill ring. However, the name has been
6325 chosen to help humans understand how the variable is used. The
6326 variable is used in functions such as `yank' and `yank-pop' (*note
6327 Yanking Text Back: Yanking.).
6328
6329 Now, 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
6334 This is an expression whose first element is the function `and'.
6335
6336 The `and' special form evaluates each of its arguments until one of
6337 the arguments returns a value of `nil', in which case the `and'
6338 expression returns `nil'; however, if none of the arguments returns a
6339 value of `nil', the value resulting from evaluating the last argument
6340 is returned. (Since such a value is not `nil', it is considered true
6341 in Emacs Lisp.) In other words, an `and' expression returns a true
6342 value only if all its arguments are true.
6343
6344 In this case, the expression tests first to see whether
6345 `menu-bar-update-yank-menu' exists as a function, and if so, calls
6346 it. The `fboundp' function returns true if the symbol it is testing
6347 has a function definition that `is not void'. If the symbol's
6348 function definition were void, we would receive an error message, as
6349 we did when we created errors intentionally (*note Generate an Error
6350 Message: Making Errors.).
6351
6352 Essentially, 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
6358 possible to use the `Select and Paste' menu in the Edit item of a menu
6359 bar; using a mouse, you can look at the various pieces of text you
6360 have saved and select one piece to paste.
6361
6362 Finally, the last expression in the `kill-new' function adds the
6363 newly copied string to whatever facility exists for copying and
6364 pasting among different programs running in a windowing system. In
6365 the X Windowing system, for example, the `x-select-text' function
6366 takes the string and stores it in memory operated by X. You can paste
6367 the string in another program, such as an Xterm.
6368
6369 The expression looks like this:
6370
6371 (if interprogram-cut-function
6372 (funcall interprogram-cut-function string (not replace))))
6373
6374 If an `interprogram-cut-function' exists, then Emacs executes
6375 `funcall', which in turn calls its first argument as a function and
6376 passes the remaining arguments to it. (Incidentally, as far as I can
6377 see, this `if' expression could be replaced by an `and' expression
6378 similar to the one in the first part of the function.)
6379
6380 We are not going to discuss windowing systems and other programs
6381 further, but merely note that this is a mechanism that enables GNU
6382 Emacs to work easily and well with other programs.
6383
6384 This code for placing text in the kill ring, either concatenated with
6385 an existing element or as a new element, leads us to the code for
6386 bringing back text that has been cut out of the buffer--the yank
6387 commands. However, before discussing the yank commands, it is better
6388 to learn how lists are implemented in a computer. This will make
6389 clear such mysteries as the use of the term `pointer'.
6390
6391 Review
6392 ======
6393
6394 Here 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
6487 Searching 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
6501 How Lists are Implemented
6502 *************************
6503
6504 In Lisp, atoms are recorded in a straightforward fashion; if the
6505 implementation is not straightforward in practice, it is, nonetheless,
6506 straightforward in theory. The atom `rose', for example, is recorded
6507 as the four contiguous letters `r', `o', `s', `e'. A list, on the
6508 other hand, is kept differently. The mechanism is equally simple,
6509 but it takes a moment to get used to the idea. A list is kept using
6510 a series of pairs of pointers. In the series, the first pointer in
6511 each pair points to an atom or to another list, and the second
6512 pointer in each pair points to the next pair, or to the symbol `nil',
6513 which marks the end of the list.
6514
6515 A pointer itself is quite simply the electronic address of what is
6516 pointed to. Hence, a list is kept as a series of electronic
6517 addresses.
6518
6519 Lists diagrammed
6520 ================
6521
6522 For example, the list `(rose violet buttercup)' has three elements,
6523 `rose', `violet', and `buttercup'. In the computer, the electronic
6524 address of `rose' is recorded in a segment of computer memory along
6525 with 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
6528 the address for the atom `buttercup' is located.
6529
6530 This sounds more complicated than it is and is easier seen in a
6531 diagram:
6532
6533 ___ ___ ___ ___ ___ ___
6534 |___|___|--> |___|___|--> |___|___|--> nil
6535 | | |
6536 | | |
6537 --> rose --> violet --> buttercup
6538
6539
6540
6541 In the diagram, each box represents a word of computer memory that
6542 holds a Lisp object, usually in the form of a memory address. The
6543 boxes, i.e. the addresses, are in pairs. Each arrow points to what
6544 the address is the address of, either an atom or another pair of
6545 addresses. The first box is the electronic address of `rose' and the
6546 arrow points to `rose'; the second box is the address of the next
6547 pair of boxes, the first part of which is the address of `violet' and
6548 the second part of which is the address of the next pair. The very
6549 last box points to the symbol `nil', which marks the end of the list.
6550
6551 When a variable is set to a list with a function such as `setq', it
6552 stores the address of the first box in the variable. Thus,
6553 evaluation of the expression
6554
6555 (setq bouquet '(rose violet buttercup))
6556
6557 creates a situation like this:
6558
6559 bouquet
6560 |
6561 | ___ ___ ___ ___ ___ ___
6562 --> |___|___|--> |___|___|--> |___|___|--> nil
6563 | | |
6564 | | |
6565 --> rose --> violet --> buttercup
6566
6567
6568
6569 In this example, the symbol `bouquet' holds the address of the first
6570 pair of boxes.
6571
6572 This same list can be illustrated in a different sort of box notation
6573 like 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
6586 a symbol is made up of addresses. Indeed, the symbol `bouquet'
6587 consists of a group of address-boxes, one of which is the address of
6588 the printed word `bouquet', a second of which is the address of a
6589 function definition attached to the symbol, if any, a third of which
6590 is the address of the first pair of address-boxes for the list `(rose
6591 violet buttercup)', and so on. Here we are showing that the symbol's
6592 third address-box points to the first pair of address-boxes for the
6593 list.)
6594
6595 If a symbol is set to the CDR of a list, the list itself is not
6596 changed; the symbol simply has an address further down the list. (In
6597 the jargon, CAR and CDR are `non-destructive'.) Thus, evaluation of
6598 the following expression
6599
6600 (setq flowers (cdr bouquet))
6601
6602 produces this:
6603
6604
6605 bouquet flowers
6606 | |
6607 | ___ ___ | ___ ___ ___ ___
6608 --> | | | --> | | | | | |
6609 |___|___|----> |___|___|--> |___|___|--> nil
6610 | | |
6611 | | |
6612 --> rose --> violet --> buttercup
6613
6614
6615
6616
6617 The value of `flowers' is `(violet buttercup)', which is to say, the
6618 symbol `flowers' holds the address of the pair of address-boxes, the
6619 first of which holds the address of `violet', and the second of which
6620 holds the address of `buttercup'.
6621
6622 A 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
6625 and dotted pairs.
6626
6627 The function `cons' adds a new pair of addresses to the front of a
6628 series of addresses like that shown above. For example, evaluating
6629 the expression
6630
6631 (setq bouquet (cons 'lily bouquet))
6632
6633 produces:
6634
6635
6636 bouquet flowers
6637 | |
6638 | ___ ___ ___ ___ | ___ ___ ___ ___
6639 --> | | | | | | --> | | | | | |
6640 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
6641 | | | |
6642 | | | |
6643 --> lily --> rose --> violet --> buttercup
6644
6645
6646
6647
6648 However, this does not change the value of the symbol `flowers', as
6649 you can see by evaluating the following,
6650
6651 (eq (cdr (cdr bouquet)) flowers)
6652
6653 which returns `t' for true.
6654
6655 Until it is reset, `flowers' still has the value `(violet
6656 buttercup)'; that is, it has the address of the cons cell whose first
6657 address is of `violet'. Also, this does not alter any of the
6658 pre-existing cons cells; they are all still there.
6659
6660 Thus, in Lisp, to get the CDR of a list, you just get the address of
6661 the next cons cell in the series; to get the CAR of a list, you get
6662 the address of the first element of the list; to `cons' a new element
6663 on a list, you add a new cons cell to the front of the list. That is
6664 all there is to it! The underlying structure of Lisp is brilliantly
6665 simple!
6666
6667 And what does the last address in a series of cons cells refer to? It
6668 is the address of the empty list, of `nil'.
6669
6670 In summary, when a Lisp variable is set to a value, it is provided
6671 with the address of the list to which the variable refers.
6672
6673 Symbols as a Chest of Drawers
6674 =============================
6675
6676 In an earlier section, I suggested that you might imagine a symbol as
6677 being a chest of drawers. The function definition is put in one
6678 drawer, the value in another, and so on. What is put in the drawer
6679 holding the value can be changed without affecting the contents of the
6680 drawer holding the function definition, and vice-versa.
6681
6682 Actually, what is put in each drawer is the address of the value or
6683 function definition. It is as if you found an old chest in the attic,
6684 and in one of its drawers you found a map giving you directions to
6685 where the buried treasure lies.
6686
6687 (In addition to its name, symbol definition, and variable value, a
6688 symbol has a `drawer' for a "property list" which can be used to
6689 record other information. Property lists are not discussed here; see
6690 *Note Property Lists: (elisp)Property Lists.)
6691
6692 Here 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
6721 Exercise
6722 ========
6723
6724 Set `flowers' to `violet' and `buttercup'. Cons two more flowers on
6725 to 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
6728 Yanking Text Back
6729 *****************
6730
6731 Whenever you cut text out of a buffer with a `kill' command in GNU
6732 Emacs, you can bring it back with a `yank' command. The text that is
6733 cut out of the buffer is put in the kill ring and the yank commands
6734 insert the appropriate contents of the kill ring back into a buffer
6735 (not necessarily the original buffer).
6736
6737 A simple `C-y' (`yank') command inserts the first item from the kill
6738 ring into the current buffer. If the `C-y' command is followed
6739 immediately by `M-y', the first element is replaced by the second
6740 element. Successive `M-y' commands replace the second element with
6741 the third, fourth, or fifth element, and so on. When the last
6742 element in the kill ring is reached, it is replaced by the first
6743 element and the cycle is repeated. (Thus the kill ring is called a
6744 `ring' rather than just a `list'. However, the actual data structure
6745 that holds the text is a list. *Note Handling the Kill Ring: Kill
6746 Ring, for the details of how the list is handled as a ring.)
6747
6748 Kill Ring Overview
6749 ==================
6750
6751 The kill ring is a list of textual strings. This is what it looks
6752 like:
6753
6754 ("some text" "a different piece of text" "yet more text")
6755
6756 If this were the contents of my kill ring and I pressed `C-y', the
6757 string of characters saying `some text' would be inserted in this
6758 buffer where my cursor is located.
6759
6760 The `yank' command is also used for duplicating text by copying it.
6761 The copied text is not cut from the buffer, but a copy of it is put
6762 on the kill ring and is inserted by yanking it back.
6763
6764 Three 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
6766 bound to `M-y'; and `rotate-yank-pointer', which is used by the two
6767 other functions.
6768
6769 These 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
6775 To begin to understand how `yank' and `yank-pop' work, it is first
6776 necessary to look at the `kill-ring-yank-pointer' variable and the
6777 `rotate-yank-pointer' function.
6778
6779 The `kill-ring-yank-pointer' Variable
6780 =====================================
6781
6782 `kill-ring-yank-pointer' is a variable, just as `kill-ring' is a
6783 variable. It points to something by being bound to the value of what
6784 it points to, like any other Lisp variable.
6785
6786 Thus, if the value of the kill ring is:
6787
6788 ("some text" "a different piece of text" "yet more text")
6789
6790 and the `kill-ring-yank-pointer' points to the second clause, the
6791 value of `kill-ring-yank-pointer' is:
6792
6793 ("a different piece of text" "yet more text")
6794
6795 As explained in the previous chapter (*note List Implementation::),
6796 the computer does not keep two different copies of the text being
6797 pointed to by both the `kill-ring' and the `kill-ring-yank-pointer'.
6798 The words "a different piece of text" and "yet more text" are not
6799 duplicated. Instead, the two Lisp variables point to the same pieces
6800 of 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
6818 Both the variable `kill-ring' and the variable
6819 `kill-ring-yank-pointer' are pointers. But the kill ring itself is
6820 usually 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
6822 points to the list. Conversely, the `kill-ring-yank-pointer' is
6823 spoken of as pointing to a list.
6824
6825 These two ways of talking about the same thing sound confusing at
6826 first but make sense on reflection. The kill ring is generally
6827 thought of as the complete structure of data that holds the
6828 information of what has recently been cut out of the Emacs buffers.
6829 The `kill-ring-yank-pointer' on the other hand, serves to
6830 indicate--that is, to `point to'--that part of the kill ring of which
6831 the first element (the CAR) will be inserted.
6832
6833 The `rotate-yank-pointer' function changes the element in the kill
6834 ring to which the `kill-ring-yank-pointer' points; when the pointer
6835 is set to point to the next element beyond the end of the kill ring,
6836 it automatically sets it to point to the first element of the kill
6837 ring. This is how the list is transformed into a ring. The
6838 `rotate-yank-pointer' function itself is not difficult, but contains
6839 many details. It and the much simpler `yank' and `yank-pop'
6840 functions are described in an appendix. *Note Handling the Kill
6841 Ring: Kill Ring.
6842
6843 Exercises 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
6856 Loops and Recursion
6857 *******************
6858
6859 Emacs Lisp has two primary ways to cause an expression, or a series of
6860 expressions, to be evaluated repeatedly: one uses a `while' loop, and
6861 the other uses "recursion".
6862
6863 Repetition can be very valuable. For example, to move forward four
6864 sentences, you need only write a program that will move forward one
6865 sentence and then repeat the process four times. Since a computer
6866 does not get bored or tired, such repetitive action does not have the
6867 deleterious effects that excessive or the wrong kinds of repetition
6868 can have on humans.
6869
6870 People mostly write Emacs Lisp functions using `while' loops and
6871 their kin; but you can use recursion, which provides a very powerful
6872 way 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
6877 mental or computer resources; as it happens, methods that people find
6878 easy--that are frugal of `mental resources'--sometimes use
6879 considerable computer resources. Emacs was designed to run on
6880 machines that we now consider limited and its default settings are
6881 conservative. You may want to increase the values of
6882 `max-specpdl-size' and `max-lisp-eval-depth'. In my `.emacs' file, I
6883 set them to 15 and 30 times their default value.
6884
6885 `while'
6886 =======
6887
6888 The `while' special form tests whether the value returned by
6889 evaluating its first argument is true or false. This is similar to
6890 what the Lisp interpreter does with an `if'; what the interpreter does
6891 next, however, is different.
6892
6893 In a `while' expression, if the value returned by evaluating the
6894 first argument is false, the Lisp interpreter skips the rest of the
6895 expression (the "body" of the expression) and does not evaluate it.
6896 However, if the value is true, the Lisp interpreter evaluates the body
6897 of the expression and then again tests whether the first argument to
6898 `while' is true or false. If the value returned by evaluating the
6899 first argument is again true, the Lisp interpreter again evaluates the
6900 body of the expression.
6901
6902 The template for a `while' expression looks like this:
6903
6904 (while TRUE-OR-FALSE-TEST
6905 BODY...)
6906
6907 Looping with `while'
6908 --------------------
6909
6910 So long as the true-or-false-test of the `while' expression returns a
6911 true value when it is evaluated, the body is repeatedly evaluated.
6912 This process is called a loop since the Lisp interpreter repeats the
6913 same thing again and again, like an airplane doing a loop. When the
6914 result of evaluating the true-or-false-test is false, the Lisp
6915 interpreter does not evaluate the rest of the `while' expression and
6916 `exits the loop'.
6917
6918 Clearly, if the value returned by evaluating the first argument to
6919 `while' is always true, the body following will be evaluated again
6920 and again ... and again ... forever. Conversely, if the value
6921 returned is never true, the expressions in the body will never be
6922 evaluated. The craft of writing a `while' loop consists of choosing
6923 a mechanism such that the true-or-false-test returns true just the
6924 number of times that you want the subsequent expressions to be
6925 evaluated, and then have the test return false.
6926
6927 The value returned by evaluating a `while' is the value of the
6928 true-or-false-test. An interesting consequence of this is that a
6929 `while' loop that evaluates without error will return `nil' or false
6930 regardless of whether it has looped 1 or 100 times or none at all. A
6931 `while' expression that evaluates successfully never returns a true
6932 value! What this means is that `while' is always evaluated for its
6933 side effects, which is to say, the consequences of evaluating the
6934 expressions within the body of the `while' loop. This makes sense.
6935 It is not the mere act of looping that is desired, but the
6936 consequences of what happens when the expressions in the loop are
6937 repeatedly evaluated.
6938
6939 A `while' Loop and a List
6940 -------------------------
6941
6942 A common way to control a `while' loop is to test whether a list has
6943 any elements. If it does, the loop is repeated; but if it does not,
6944 the repetition is ended. Since this is an important technique, we
6945 will create a short example to illustrate it.
6946
6947 A simple way to test whether a list has elements is to evaluate the
6948 list: if it has no elements, it is an empty list and will return the
6949 empty list, `()', which is a synonym for `nil' or false. On the
6950 other hand, a list with elements will return those elements when it
6951 is evaluated. Since Emacs Lisp considers as true any value that is
6952 not `nil', a list that returns elements will test true in a `while'
6953 loop.
6954
6955 For example, you can set the variable `empty-list' to `nil' by
6956 evaluating the following `setq' expression:
6957
6958 (setq empty-list ())
6959
6960 After evaluating the `setq' expression, you can evaluate the variable
6961 `empty-list' in the usual way, by placing the cursor after the symbol
6962 and typing `C-x C-e'; `nil' will appear in your echo area:
6963
6964 empty-list
6965
6966 On the other hand, if you set a variable to be a list with elements,
6967 the list will appear when you evaluate the variable, as you can see by
6968 evaluating the following two expressions:
6969
6970 (setq animals '(gazelle giraffe lion tiger))
6971
6972 animals
6973
6974 Thus, to create a `while' loop that tests whether there are any items
6975 in the list `animals', the first part of the loop will be written
6976 like this:
6977
6978 (while animals
6979 ...
6980
6981 When the `while' tests its first argument, the variable `animals' is
6982 evaluated. 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
6984 list is empty, it considers the results of the test to be false.
6985
6986 To prevent the `while' loop from running forever, some mechanism
6987 needs to be provided to empty the list eventually. An oft-used
6988 technique is to have one of the subsequent forms in the `while'
6989 expression set the value of the list to be the CDR of the list. Each
6990 time the `cdr' function is evaluated, the list will be made shorter,
6991 until eventually only the empty list will be left. At this point,
6992 the test of the `while' loop will return false, and the arguments to
6993 the `while' will no longer be evaluated.
6994
6995 For example, the list of animals bound to the variable `animals' can
6996 be set to be the CDR of the original list with the following
6997 expression:
6998
6999 (setq animals (cdr animals))
7000
7001 If you have evaluated the previous expressions and then evaluate this
7002 expression, you will see `(giraffe lion tiger)' appear in the echo
7003 area. If you evaluate the expression again, `(lion tiger)' will
7004 appear in the echo area. If you evaluate it again and yet again,
7005 `(tiger)' appears and then the empty list, shown by `nil'.
7006
7007 A template for a `while' loop that uses the `cdr' function repeatedly
7008 to cause the true-or-false-test eventually to test false looks like
7009 this:
7010
7011 (while TEST-WHETHER-LIST-IS-EMPTY
7012 BODY...
7013 SET-LIST-TO-CDR-OF-LIST)
7014
7015 This test and use of `cdr' can be put together in a function that
7016 goes through a list and prints each element of the list on a line of
7017 its own.
7018
7019 An Example: `print-elements-of-list'
7020 ------------------------------------
7021
7022 The `print-elements-of-list' function illustrates a `while' loop with
7023 a list.
7024
7025 The function requires several lines for its output. If you are
7026 reading this in Emacs 21 or a later version, you can evaluate the
7027 following expression inside of Info, as usual.
7028
7029 If you are using an earlier version of Emacs, you need to copy the
7030 necessary expressions to your `*scratch*' buffer and evaluate them
7031 there. This is because the echo area had only one line in the
7032 earlier versions.
7033
7034 You can copy the expressions by marking the beginning of the region
7035 with `C-<SPC>' (`set-mark-command'), moving the cursor to the end of
7036 the region and then copying the region using `M-w'
7037 (`copy-region-as-kill'). In the `*scratch*' buffer, you can yank the
7038 expressions back by typing `C-y' (`yank').
7039
7040 After you have copied the expressions to the `*scratch*' buffer,
7041 evaluate each expression in turn. Be sure to evaluate the last
7042 expression, `(print-elements-of-list animals)', by typing `C-u C-x
7043 C-e', that is, by giving an argument to `eval-last-sexp'. This will
7044 cause the result of the evaluation to be printed in the `*scratch*'
7045 buffer instead of being printed in the echo area. (Otherwise you
7046 will see something like this in your echo area:
7047 `^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil', in which each `^J'
7048 stands for a `newline'.)
7049
7050 If you are using Emacs 21 or later, you can evaluate these expressions
7051 directly in the Info buffer, and the echo area will grow to show the
7052 results.
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
7064 When you evaluate the three expressions in sequence, you will see
7065 this:
7066
7067 gazelle
7068
7069 giraffe
7070
7071 lion
7072
7073 tiger
7074 nil
7075
7076 Each element of the list is printed on a line of its own (that is what
7077 the function `print' does) and then the value returned by the
7078 function is printed. Since the last expression in the function is the
7079 `while' loop, and since `while' loops always return `nil', a `nil' is
7080 printed after the last element of the list.
7081
7082 A Loop with an Incrementing Counter
7083 -----------------------------------
7084
7085 A loop is not useful unless it stops when it ought. Besides
7086 controlling a loop with a list, a common way of stopping a loop is to
7087 write the first argument as a test that returns false when the correct
7088 number of repetitions are complete. This means that the loop must
7089 have a counter--an expression that counts how many times the loop
7090 repeats itself.
7091
7092 The test can be an expression such as `(< count desired-number)'
7093 which 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
7096 expression 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
7098 Lisp that adds 1 to its argument. (The expression `(1+ count)' has
7099 the same result as `(+ count 1)', but is easier for a human to read.)
7100
7101 The template for a `while' loop controlled by an incrementing counter
7102 looks 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
7109 Note that you need to set the initial value of `count'; usually it is
7110 set to 1.
7111
7112 Example with incrementing counter
7113 .................................
7114
7115 Suppose you are playing on the beach and decide to make a triangle of
7116 pebbles, putting one pebble in the first row, two in the second row,
7117 three 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
7127 of number theory by considering questions such as this.)
7128
7129 Suppose you want to know how many pebbles you will need to make a
7130 triangle with 7 rows?
7131
7132 Clearly, what you need to do is add up the numbers from 1 to 7. There
7133 are two ways to do this; start with the smallest number, one, and add
7134 up the list in sequence, 1, 2, 3, 4 and so on; or start with the
7135 largest number and add the list going down: 7, 6, 5, 4 and so on.
7136 Because both mechanisms illustrate common ways of writing `while'
7137 loops, we will create two examples, one counting up and the other
7138 counting down. In this first example, we will start with 1 and add
7139 2, 3, 4 and so on.
7140
7141 If you are just adding up a short list of numbers, the easiest way to
7142 do it is to add up all the numbers at once. However, if you do not
7143 know ahead of time how many numbers your list will have, or if you
7144 want to be prepared for a very long list, then you need to design
7145 your addition so that what you do is repeat a simple process many
7146 times instead of doing a more complex process once.
7147
7148 For example, instead of adding up all the pebbles all at once, what
7149 you can do is add the number of pebbles in the first row, 1, to the
7150 number in the second row, 2, and then add the total of those two rows
7151 to the third row, 3. Then you can add the number in the fourth row,
7152 4, to the total of the first three rows; and so on.
7153
7154 The critical characteristic of the process is that each repetitive
7155 action is simple. In this case, at each step we add only two numbers,
7156 the number of pebbles in the row and the total already found. This
7157 process of adding two numbers is repeated again and again until the
7158 last row has been added to the total of all the preceding rows. In a
7159 more complex loop the repetitive action might not be so simple, but
7160 it will be simpler than doing everything all at once.
7161
7162 The parts of the function definition
7163 ....................................
7164
7165 The preceding analysis gives us the bones of our function definition:
7166 first, we will need a variable that we can call `total' that will be
7167 the total number of pebbles. This will be the value returned by the
7168 function.
7169
7170 Second, we know that the function will require an argument: this
7171 argument will be the total number of rows in the triangle. It can be
7172 called `number-of-rows'.
7173
7174 Finally, we need a variable to use as a counter. We could call this
7175 variable `counter', but a better name is `row-number'. That is
7176 because what the counter does is count rows, and a program should be
7177 written to be as understandable as possible.
7178
7179 When the Lisp interpreter first starts evaluating the expressions in
7180 the function, the value of `total' should be set to zero, since we
7181 have not added anything to it. Then the function should add the
7182 number of pebbles in the first row to the total, and then add the
7183 number of pebbles in the second to the total, and then add the number
7184 of pebbles in the third row to the total, and so on, until there are
7185 no more rows left to add.
7186
7187 Both `total' and `row-number' are used only inside the function, so
7188 they can be declared as local variables with `let' and given initial
7189 values. Clearly, the initial value for `total' should be 0. The
7190 initial value of `row-number' should be 1, since we start with the
7191 first row. This means that the `let' statement will look like this:
7192
7193 (let ((total 0)
7194 (row-number 1))
7195 BODY...)
7196
7197 After the internal variables are declared and bound to their initial
7198 values, we can begin the `while' loop. The expression that serves as
7199 the 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
7201 expression tests true only so long as the row number is less than the
7202 number of rows in the triangle, the last row will never be added to
7203 the total; hence the row number has to be either less than or equal
7204 to the number of rows.)
7205
7206 Lisp provides the `<=' function that returns true if the value of its
7207 first argument is less than or equal to the value of its second
7208 argument and false otherwise. So the expression that the `while'
7209 will evaluate as its test should look like this:
7210
7211 (<= row-number number-of-rows)
7212
7213 The total number of pebbles can be found by repeatedly adding the
7214 number of pebbles in a row to the total already found. Since the
7215 number of pebbles in the row is equal to the row number, the total
7216 can be found by adding the row number to the total. (Clearly, in a
7217 more complex situation, the number of pebbles in the row might be
7218 related to the row number in a more complicated way; if this were the
7219 case, the row number would be replaced by the appropriate expression.)
7220
7221 (setq total (+ total row-number))
7222
7223 What this does is set the new value of `total' to be equal to the sum
7224 of adding the number of pebbles in the row to the previous total.
7225
7226 After setting the value of `total', the conditions need to be
7227 established for the next repetition of the loop, if there is one.
7228 This is done by incrementing the value of the `row-number' variable,
7229 which serves as a counter. After the `row-number' variable has been
7230 incremented, the true-or-false-test at the beginning of the `while'
7231 loop tests whether its value is still less than or equal to the value
7232 of 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
7234 the loop.
7235
7236 The 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
7241 Putting the function definition together
7242 ........................................
7243
7244 We have created the parts for the function definition; now we need to
7245 put them together.
7246
7247 First, 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
7253 Along with the `let' expression varlist, this very nearly completes
7254 the body of the function definition. However, it requires one final
7255 element, the need for which is somewhat subtle.
7256
7257 The final touch is to place the variable `total' on a line by itself
7258 after the `while' expression. Otherwise, the value returned by the
7259 whole function is the value of the last expression that is evaluated
7260 in the body of the `let', and this is the value returned by the
7261 `while', which is always `nil'.
7262
7263 This may not be evident at first sight. It almost looks as if the
7264 incrementing expression is the last expression of the whole function.
7265 But that expression is part of the body of the `while'; it is the
7266 last element of the list that starts with the symbol `while'.
7267 Moreover, the whole of the `while' loop is a list within the body of
7268 the `let'.
7269
7270 In 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
7279 The result of evaluating the `let' is what is going to be returned by
7280 the `defun' since the `let' is not embedded within any containing
7281 list, except for the `defun' as a whole. However, if the `while' is
7282 the last element of the `let' expression, the function will always
7283 return `nil'. This is not what we want! Instead, what we want is
7284 the value of the variable `total'. This is returned by simply
7285 placing the symbol as the last element of the list starting with
7286 `let'. It gets evaluated after the preceding elements of the list
7287 are evaluated, which means it gets evaluated after it has been
7288 assigned the correct value for the total.
7289
7290 It may be easier to see this by printing the list starting with `let'
7291 all on one line. This format makes it evident that the VARLIST and
7292 `while' expressions are the second and third elements of the list
7293 starting with `let', and the `total' is the last element:
7294
7295 (let (VARLIST) (while (TRUE-OR-FALSE-TEST) BODY-OF-WHILE... ) total)
7296
7297 Putting everything together, the `triangle' function definition looks
7298 like 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
7313 After you have installed `triangle' by evaluating the function, you
7314 can try it out. Here are two examples:
7315
7316 (triangle 4)
7317
7318 (triangle 7)
7319
7320 The sum of the first four numbers is 10 and the sum of the first seven
7321 numbers is 28.
7322
7323 Loop with a Decrementing Counter
7324 --------------------------------
7325
7326 Another common way to write a `while' loop is to write the test so
7327 that it determines whether a counter is greater than zero. So long
7328 as the counter is greater than zero, the loop is repeated. But when
7329 the counter is equal to or less than zero, the loop is stopped. For
7330 this to work, the counter has to start out greater than zero and then
7331 be made smaller and smaller by a form that is evaluated repeatedly.
7332
7333 The 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
7336 zero. The expression that makes the number smaller and smaller can
7337 be a simple `setq' such as `(setq counter (1- counter))', where `1-'
7338 is a built-in function in Emacs Lisp that subtracts 1 from its
7339 argument.
7340
7341 The 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
7347 Example with decrementing counter
7348 .................................
7349
7350 To illustrate a loop with a decrementing counter, we will rewrite the
7351 `triangle' function so the counter decreases to zero.
7352
7353 This is the reverse of the earlier version of the function. In this
7354 case, to find out how many pebbles are needed to make a triangle with
7355 3 rows, add the number of pebbles in the third row, 3, to the number
7356 in the preceding row, 2, and then add the total of those two rows to
7357 the row that precedes them, which is 1.
7358
7359 Likewise, to find the number of pebbles in a triangle with 7 rows, add
7360 the number of pebbles in the seventh row, 7, to the number in the
7361 preceding row, which is 6, and then add the total of those two rows to
7362 the row that precedes them, which is 5, and so on. As in the previous
7363 example, each addition only involves adding two numbers, the total of
7364 the rows already added up and the number of pebbles in the row that is
7365 being added to the total. This process of adding two numbers is
7366 repeated again and again until there are no more pebbles to add.
7367
7368 We know how many pebbles to start with: the number of pebbles in the
7369 last row is equal to the number of rows. If the triangle has seven
7370 rows, the number of pebbles in the last row is 7. Likewise, we know
7371 how many pebbles are in the preceding row: it is one less than the
7372 number in the row.
7373
7374 The parts of the function definition
7375 ....................................
7376
7377 We start with three variables: the total number of rows in the
7378 triangle; the number of pebbles in a row; and the total number of
7379 pebbles, which is what we want to calculate. These variables can be
7380 named `number-of-rows', `number-of-pebbles-in-row', and `total',
7381 respectively.
7382
7383 Both `total' and `number-of-pebbles-in-row' are used only inside the
7384 function and are declared with `let'. The initial value of `total'
7385 should, of course, be zero. However, the initial value of
7386 `number-of-pebbles-in-row' should be equal to the number of rows in
7387 the triangle, since the addition will start with the longest row.
7388
7389 This means that the beginning of the `let' expression will look like
7390 this:
7391
7392 (let ((total 0)
7393 (number-of-pebbles-in-row number-of-rows))
7394 BODY...)
7395
7396 The total number of pebbles can be found by repeatedly adding the
7397 number of pebbles in a row to the total already found, that is, by
7398 repeatedly evaluating the following expression:
7399
7400 (setq total (+ total number-of-pebbles-in-row))
7401
7402 After 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
7404 next time the loop repeats, the preceding row will be added to the
7405 total.
7406
7407 The number of pebbles in a preceding row is one less than the number
7408 of pebbles in a row, so the built-in Emacs Lisp function `1-' can be
7409 used to compute the number of pebbles in the preceding row. This can
7410 be done with the following expression:
7411
7412 (setq number-of-pebbles-in-row
7413 (1- number-of-pebbles-in-row))
7414
7415 Finally, we know that the `while' loop should stop making repeated
7416 additions 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
7421 Putting the function definition together
7422 ........................................
7423
7424 We can put these expressions together to create a function definition
7425 that works. However, on examination, we find that one of the local
7426 variables is unneeded!
7427
7428 The 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
7441 As written, this function works.
7442
7443 However, we do not need `number-of-pebbles-in-row'.
7444
7445 When the `triangle' function is evaluated, the symbol
7446 `number-of-rows' will be bound to a number, giving it an initial
7447 value. That number can be changed in the body of the function as if
7448 it were a local variable, without any fear that such a change will
7449 effect the value of the variable outside of the function. This is a
7450 very 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
7454 Here 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
7464 In 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
7476 Save your time: `dolist' and `dotimes'
7477 ======================================
7478
7479 In addition to `while', both `dolist' and `dotimes' provide for
7480 looping. 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'
7484 automatically shortens the list each time it loops--takes the CDR of
7485 the list--and binds the CAR of each shorter version of the list to
7486 the first of its arguments.
7487
7488 `dotimes' loops a specific number of times: you specify the number.
7489
7490 The `dolist' Macro
7491 ..................
7492
7493 Suppose, for example, you want to reverse a list, so that "first"
7494 "second" "third" becomes "third" "second" "first".
7495
7496 In practice, you would use the `reverse' function, like this:
7497
7498 (setq animals '(gazelle giraffe lion tiger))
7499
7500 (reverse animals)
7501
7502 Here 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
7516 And 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
7528 In Info, you can place your cursor after the closing parenthesis of
7529 each expression and type `C-x C-e'; in each case, you should see
7530
7531 (tiger lion giraffe gazelle)
7532
7533 in the echo area.
7534
7535 For this example, the existing `reverse' function is obviously best.
7536 The `while' loop is just like our first example (*note A `while' Loop
7537 and a List: Loop Example.). The `while' first checks whether the
7538 list has elements; if so, it constructs a new list by adding the
7539 first element of the list to the existing list (which in the first
7540 iteration of the loop is `nil'). Since the second element is
7541 prepended in front of the first element, and the third element is
7542 prepended in front of the second element, the list is reversed.
7543
7544 In the expression using a `while' loop, the `(setq list (cdr list))'
7545 expression shortens the list, so the `while' loop eventually stops.
7546 In addition, it provides the `cons' expression with a new first
7547 element by creating a new and shorter list at each repetition of the
7548 loop.
7549
7550 The `dolist' expression does very much the same as the `while'
7551 expression, except that the `dolist' macro does some of the work you
7552 have to do when writing a `while' expression.
7553
7554 Like a `while' loop, a `dolist' loops. What is different is that it
7555 automatically shortens the list each time it loops -- it `CDRs down
7556 the list' on its own -- and it automatically binds the CAR of each
7557 shorter version of the list to the first of its arguments.
7558
7559 In the example, the CAR of each shorter version of the list is
7560 referred to using the symbol `element', the list itself is called
7561 `list', and the value returned is called `value'. The remainder of
7562 the `dolist' expression is the body.
7563
7564 The `dolist' expression binds the CAR of each shorter version of the
7565 list to `element' and then evaluates the body of the expression; and
7566 repeats the loop. The result is returned in `value'.
7567
7568 The `dotimes' Macro
7569 ...................
7570
7571 The `dotimes' macro is similar to `dolist', except that it loops a
7572 specific number of times.
7573
7574 The first argument to `dotimes' is assigned the numbers 0, 1, 2 and
7575 so forth each time around the loop, and the value of the third
7576 argument is returned. You need to provide the value of the second
7577 argument, which is how many times the macro loops.
7578
7579 For example, the following binds the numbers from 0 up to, but not
7580 including, the number 3 to the first argument, NUMBER, and then
7581 constructs a list of the three numbers. (The first number is 0, the
7582 second number is 1, and the third number is 2; this makes a total of
7583 three 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
7592 on some expression NUMBER number of times and then return the result,
7593 either as a list or an atom.
7594
7595 Here is an example of a `defun' that uses `dotimes' to add up the
7596 number 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
7606 Recursion
7607 =========
7608
7609 A recursive function contains code that tells the Lisp interpreter to
7610 call a program that runs exactly like itself, but with slightly
7611 different arguments. The code runs exactly the same because it has
7612 the same name. However, even though the program has the same name, it
7613 is not the same entity. It is different. In the jargon, it is a
7614 different `instance'.
7615
7616 Eventually, if the program is written correctly, the `slightly
7617 different arguments' will become sufficiently different from the first
7618 arguments that the final instance will stop.
7619
7620 Building Robots: Extending the Metaphor
7621 ---------------------------------------
7622
7623 It is sometimes helpful to think of a running program as a robot that
7624 does a job. In doing its job, a recursive function calls on a second
7625 robot to help it. The second robot is identical to the first in every
7626 way, except that the second robot helps the first and has been passed
7627 different arguments than the first.
7628
7629 In a recursive function, the second robot may call a third; and the
7630 third may call a fourth, and so on. Each of these is a different
7631 entity; but all are clones.
7632
7633 Since each robot has slightly different instructions--the arguments
7634 will differ from one robot to the next--the last robot should know
7635 when to stop.
7636
7637 Let's expand on the metaphor in which a computer program is a robot.
7638
7639 A function definition provides the blueprints for a robot. When you
7640 install a function definition, that is, when you evaluate a `defun'
7641 special form, you install the necessary equipment to build robots.
7642 It is as if you were in a factory, setting up an assembly line.
7643 Robots with the same name are built according to the same blueprints.
7644 So they have, as it were, the same `model number', but a different
7645 `serial number'.
7646
7647 We often say that a recursive function `calls itself'. What we mean
7648 is that the instructions in a recursive function cause the Lisp
7649 interpreter to run a different function that has the same name and
7650 does the same job as the first, but with different arguments.
7651
7652 It is important that the arguments differ from one instance to the
7653 next; otherwise, the process will never stop.
7654
7655 The Parts of a Recursive Definition
7656 -----------------------------------
7657
7658 A recursive function typically contains a conditional expression which
7659 has 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
7676 Recursive functions can be much simpler than any other kind of
7677 function. Indeed, when people first start to use them, they often
7678 look so mysteriously simple as to be incomprehensible. Like riding a
7679 bicycle, reading a recursive function definition takes a certain knack
7680 which is hard at first but then seems simple.
7681
7682 There are several different common recursive patterns. A very simple
7683 pattern 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
7692 Each time a recursive function is evaluated, a new instance of it is
7693 created and told what to do. The arguments tell the instance what to
7694 do.
7695
7696 An argument is bound to the value of the next-step-expression. Each
7697 instance runs with a different value of the next-step-expression.
7698
7699 The value in the next-step-expression is used in the do-again-test.
7700
7701 The value returned by the next-step-expression is passed to the new
7702 instance of the function, which evaluates it (or some
7703 transmogrification of it) to determine whether to continue or stop.
7704 The next-step-expression is designed so that the do-again-test returns
7705 false when the function should no longer be repeated.
7706
7707 The do-again-test is sometimes called the "stop condition", since it
7708 stops the repetitions when it tests false.
7709
7710 Recursion with a List
7711 ---------------------
7712
7713 The example of a `while' loop that printed the elements of a list of
7714 numbers can be written recursively. Here is the code, including an
7715 expression to set the value of the variable `animals' to a list.
7716
7717 If you are using Emacs 20 or before, this example must be copied to
7718 the `*scratch*' buffer and each expression must be evaluated there.
7719 Use `C-u C-x C-e' to evaluate the `(print-elements-recursively
7720 animals)' expression so that the results are printed in the buffer;
7721 otherwise the Lisp interpreter will try to squeeze the results into
7722 the one line of the echo area.
7723
7724 Also, place your cursor immediately after the last closing parenthesis
7725 of the `print-elements-recursively' function, before the comment.
7726 Otherwise, the Lisp interpreter will try to evaluate the comment.
7727
7728 If you are using Emacs 21 or later, you can evaluate this expression
7729 directly 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
7744 The `print-elements-recursively' function first tests whether there
7745 is any content in the list; if there is, the function prints the
7746 first element of the list, the CAR of the list. Then the function
7747 `invokes itself', but gives itself as its argument, not the whole
7748 list, but the second and subsequent elements of the list, the CDR of
7749 the list.
7750
7751 Put another way, if the list is not empty, the function invokes
7752 another instance of code that is similar to the initial code, but is a
7753 different thread of execution, with different arguments than the first
7754 instance.
7755
7756 Put in yet another way, if the list is not empty, the first robot
7757 assemblies a second robot and tells it what to do; the second robot is
7758 a different individual from the first, but is the same model.
7759
7760 When the second evaluation occurs, the `if' expression is evaluated
7761 and if true, prints the first element of the list it receives as its
7762 argument (which is the second element of the original list). Then
7763 the function `calls itself' with the CDR of the list it is invoked
7764 with, which (the second time around) is the CDR of the CDR of the
7765 original list.
7766
7767 Note that although we say that the function `calls itself', what we
7768 mean is that the Lisp interpreter assembles and instructs a new
7769 instance of the program. The new instance is a clone of the first,
7770 but is a separate individual.
7771
7772 Each time the function `invokes itself', it invokes itself on a
7773 shorter version of the original list. It creates a new instance that
7774 works on a shorter list.
7775
7776 Eventually, the function invokes itself on an empty list. It creates
7777 a new instance whose argument is `nil'. The conditional expression
7778 tests 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
7780 function as a whole then returns `nil'.
7781
7782 When 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
7794 Recursion in Place of a Counter
7795 -------------------------------
7796
7797 The `triangle' function described in a previous section can also be
7798 written 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
7811 You can install this function by evaluating it and then try it by
7812 evaluating `(triangle-recursively 7)'. (Remember to put your cursor
7813 immediately after the last parenthesis of the function definition,
7814 before the comment.) The function evaluates to 28.
7815
7816 To understand how this function works, let's consider what happens in
7817 the various cases when the function is passed 1, 2, 3, or 4 as the
7818 value of its argument.
7819
7820 An argument of 1 or 2
7821 .....................
7822
7823 First, what happens if the value of the argument is 1?
7824
7825 The function has an `if' expression after the documentation string.
7826 It tests whether the value of `number' is equal to 1; if so, Emacs
7827 evaluates the then-part of the `if' expression, which returns the
7828 number 1 as the value of the function. (A triangle with one row has
7829 one pebble in it.)
7830
7831 Suppose, however, that the value of the argument is 2. In this case,
7832 Emacs evaluates the else-part of the `if' expression.
7833
7834 The else-part consists of an addition, the recursive call to
7835 `triangle-recursively' and a decrementing action; and it looks like
7836 this:
7837
7838 (+ number (triangle-recursively (1- number)))
7839
7840 When Emacs evaluates this expression, the innermost expression is
7841 evaluated first; then the other parts in sequence. Here are the steps
7842 in detail:
7843
7844 Step 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
7848 Step 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
7859 Step 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
7863 Step 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
7872 An argument of 3 or 4
7873 .....................
7874
7875 Suppose that `triangle-recursively' is called with an argument of 3.
7876
7877 Step 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
7884 Step 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
7888 Step 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
7896 Step 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
7901 The value returned by the function as a whole will be 6.
7902
7903 Now that we know what will happen when `triangle-recursively' is
7904 called with an argument of 3, it is evident what will happen if it is
7905 called 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
7918 The value returned by the function as a whole will be 10.
7919
7920 Each time `triangle-recursively' is evaluated, it evaluates a version
7921 of itself--a different instance of itself--with a smaller argument,
7922 until the argument is small enough so that it does not evaluate
7923 itself.
7924
7925 Note that this particular design for a recursive function requires
7926 that operations be deferred.
7927
7928 Before `(triangle-recursively 7)' can calculate its answer, it must
7929 call `(triangle-recursively 6)'; and before `(triangle-recursively
7930 6)' can calculate its answer, it must call `(triangle-recursively
7931 5)'; 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
7935 5)' completes; and so on.
7936
7937 If each of these instances of `triangle-recursively' are thought of
7938 as different robots, the first robot must wait for the second to
7939 complete its job, which must wait until the third completes, and so
7940 on.
7941
7942 There is a way around this kind of waiting, which we will discuss in
7943 *Note Recursion without Deferments: No Deferment.
7944
7945 Recursion Example Using `cond'
7946 ------------------------------
7947
7948 The version of `triangle-recursively' described earlier is written
7949 with the `if' special form. It can also be written using another
7950 special form called `cond'. The name of the special form `cond' is
7951 an abbreviation of the word `conditional'.
7952
7953 Although the `cond' special form is not used as often in the Emacs
7954 Lisp sources as `if', it is used often enough to justify explaining
7955 it.
7956
7957 The template for a `cond' expression looks like this:
7958
7959 (cond
7960 BODY...)
7961
7962 where the BODY is a series of lists.
7963
7964 Written 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
7972 When the Lisp interpreter evaluates the `cond' expression, it
7973 evaluates the first element (the CAR or true-or-false-test) of the
7974 first expression in a series of expressions within the body of the
7975 `cond'.
7976
7977 If the true-or-false-test returns `nil' the rest of that expression,
7978 the consequent, is skipped and the true-or-false-test of the next
7979 expression is evaluated. When an expression is found whose
7980 true-or-false-test returns a value that is not `nil', the consequent
7981 of that expression is evaluated. The consequent can be one or more
7982 expressions. If the consequent consists of more than one expression,
7983 the expressions are evaluated in sequence and the value of the last
7984 one is returned. If the expression does not have a consequent, the
7985 value of the true-or-false-test is returned.
7986
7987 If none of the true-or-false-tests test true, the `cond' expression
7988 returns `nil'.
7989
7990 Written 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
7998 In this example, the `cond' returns 0 if the number is less than or
7999 equal to 0, it returns 1 if the number is 1 and it evaluates `(+
8000 number (triangle-using-cond (1- number)))' if the number is greater
8001 than 1.
8002
8003 Recursive Patterns
8004 ------------------
8005
8006 Here are three common recursive patterns. Each involves a list.
8007 Recursion does not need to involve lists, but Lisp is designed for
8008 lists and this provides a sense of its primal capabilities.
8009
8010 Recursive Pattern: _every_
8011 ..........................
8012
8013 In the `every' recursive pattern, an action is performed on every
8014 element of a list.
8015
8016 The 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
8027 Here 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
8040 If `numbers-list' is empty, do nothing. But if it has content,
8041 construct a list combining the square of the first number in the list
8042 with the result of the recursive call.
8043
8044 (The example follows the pattern exactly: `nil' is returned if the
8045 numbers' list is empty. In practice, you would write the conditional
8046 so it carries out the action when the numbers' list is not empty.)
8047
8048 The `print-elements-recursively' function (*note Recursion with a
8049 List: Recursion with list.) is another example of an `every' pattern,
8050 except in this case, rather than bring the results together using
8051 `cons', we print each element of output.
8052
8053 The `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
8068 The 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
8078 Recursive Pattern: _accumulate_
8079 ...............................
8080
8081 Another recursive pattern is called the `accumulate' pattern. In the
8082 `accumulate' recursive pattern, an action is performed on every
8083 element of a list and the result of that action is accumulated with
8084 the results of performing the action on the other elements.
8085
8086 This is very like the `every' pattern using `cons', except that
8087 `cons' is not used, but some other combiner.
8088
8089 The 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
8100 Here 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
8112 accumulate pattern.
8113
8114 Recursive Pattern: _keep_
8115 .........................
8116
8117 A third recursive pattern is called the `keep' pattern. In the
8118 `keep' recursive pattern, each element of a list is tested; the
8119 element is acted on and the results are kept only if the element
8120 meets a criterion.
8121
8122 Again, this is very like the `every' pattern, except the element is
8123 skipped unless it meets a criterion.
8124
8125 The 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
8143 Here 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
8163 It goes without saying that you need not use `nil' as the test for
8164 when to stop; and you can, of course, combine these patterns.
8165
8166 Recursion without Deferments
8167 ----------------------------
8168
8169 Let's consider again what happens with the `triangle-recursively'
8170 function. We will find that the intermediate calculations are
8171 deferred until all can be done.
8172
8173 Here 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
8184 What happens when we call this function with a argument of 7?
8185
8186 The first instance of the `triangle-recursively' function adds the
8187 number 7 to the value returned by a second instance of
8188 `triangle-recursively', an instance that has been passed an argument
8189 of 6. That is to say, the first calculation is:
8190
8191 (+ 7 (triangle-recursively 6))
8192
8193 The first instance of `triangle-recursively'--you may want to think
8194 of it as a little robot--cannot complete its job. It must hand off
8195 the calculation for `(triangle-recursively 6)' to a second instance
8196 of the program, to a second robot. This second individual is
8197 completely different from the first one; it is, in the jargon, a
8198 `different instantiation'. Or, put another way, it is a different
8199 robot. It is the same model as the first; it calculates triangle
8200 numbers recursively; but it has a different serial number.
8201
8202 And what does `(triangle-recursively 6)' return? It returns the
8203 number 6 added to the value returned by evaluating
8204 `triangle-recursively' with an argument of 5. Using the robot
8205 metaphor, it asks yet another robot to help it.
8206
8207 Now the total is:
8208
8209 (+ 7 6 (triangle-recursively 5))
8210
8211 And what happens next?
8212
8213 (+ 7 6 5 (triangle-recursively 4))
8214
8215 Each time `triangle-recursively' is called, except for the last time,
8216 it creates another instance of the program--another robot--and asks
8217 it to make a calculation.
8218
8219 Eventually, the full addition is set up and performed:
8220
8221 (+ 7 6 5 4 3 2 1)
8222
8223 This design for the function defers the calculation of the first step
8224 until the second can be done, and defers that until the third can be
8225 done, and so on. Each deferment means the computer must remember what
8226 is being waited on. This is not a problem when there are only a few
8227 steps, as in this example. But it can be a problem when there are
8228 more steps.
8229
8230 No Deferment Solution
8231 ---------------------
8232
8233 The solution to the problem of deferred operations is to write in a
8234 manner that does not defer operations(1). This requires writing to a
8235 different pattern, often one that involves writing two function
8236 definitions, an `initialization' function and a `helper' function.
8237
8238 The `initialization' function sets up the job; the `helper' function
8239 does the work.
8240
8241 Here are the two function definitions for adding up numbers. They are
8242 so 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
8260 Install both function definitions by evaluating them, then call
8261 `triangle-initialization' with 2 rows:
8262
8263 (triangle-initialization 2)
8264 => 3
8265
8266 The `initialization' function calls the first instance of the `helper'
8267 function with three arguments: zero, zero, and a number which is the
8268 number of rows in the triangle.
8269
8270 The first two arguments passed to the `helper' function are
8271 initialization values. These values are changed when
8272 `triangle-recursive-helper' invokes new instances.(2)
8273
8274 Let'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 `(>
8279 counter number)':
8280
8281 (> 0 1)
8282
8283 and find that the result is false, so it will invoke the then-part of
8284 the `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
8291 which will first compute:
8292
8293 (triangle-recursive-helper (+ 0 0) ; sum
8294 (1+ 0) ; counter
8295 1) ; number
8296 which is:
8297
8298 (triangle-recursive-helper 0 1 1)
8299
8300 Again, `(> counter number)' will be false, so again, the Lisp
8301 interpreter will evaluate `triangle-recursive-helper', creating a new
8302 instance with new arguments.
8303
8304 This 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
8311 which is:
8312
8313 (triangle-recursive-helper 1 2 1)
8314
8315 In this case, the `(> counter number)' test will be true! So the
8316 instance will return the value of the sum, which will be 1, as
8317 expected.
8318
8319 Now, let's pass `triangle-initialization' an argument of 2, to find
8320 out how many pebbles there are in a triangle with two rows.
8321
8322 That function calls `(triangle-recursive-helper 0 0 2)'.
8323
8324 In 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
8333 When the last instance is called, the `(> counter number)' test will
8334 be true, so the instance will return the value of `sum', which will
8335 be 3.
8336
8337 This kind of pattern helps when you are writing functions that can use
8338 many resources in a computer.
8339
8340 ---------- Footnotes ----------
8341
8342 (1) The phrase "tail recursive" is used to describe such a process,
8343 one that uses `constant space'.
8344
8345 (2) The jargon is mildly confusing: `triangle-recursive-helper' uses
8346 a process that is iterative in a procedure that is recursive. The
8347 process is called iterative because the computer need only record the
8348 three values, `sum', `counter', and `number'; the procedure is
8349 recursive because the function `calls itself'. On the other hand,
8350 both the process and the procedure used by `triangle-recursively' are
8351 called recursive. The word `recursive' has different meanings in the
8352 two contexts.
8353
8354 Looping 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
8372 Regular Expression Searches
8373 ***************************
8374
8375 Regular expression searches are used extensively in GNU Emacs. The
8376 two functions, `forward-sentence' and `forward-paragraph', illustrate
8377 these searches well. They use regular expressions to find where to
8378 move point. The phrase `regular expression' is often written as
8379 `regexp'.
8380
8381 Regular expression searches are described in *Note Regular Expression
8382 Search: (emacs)Regexp Search, as well as in *Note Regular
8383 Expressions: (elisp)Regular Expressions. In writing this chapter, I
8384 am presuming that you have at least a mild acquaintance with them.
8385 The major point to remember is that regular expressions permit you to
8386 search for patterns as well as for literal strings of characters.
8387 For example, the code in `forward-sentence' searches for the pattern
8388 of possible characters that could mark the end of a sentence, and
8389 moves point to that spot.
8390
8391 Before looking at the code for the `forward-sentence' function, it is
8392 worth considering what the pattern that marks the end of a sentence
8393 must be. The pattern is discussed in the next section; following that
8394 is a description of the regular expression search function,
8395 `re-search-forward'. The `forward-sentence' function is described in
8396 the section following. Finally, the `forward-paragraph' function is
8397 described in the last section of this chapter. `forward-paragraph'
8398 is a complex function that introduces several new features.
8399
8400 The Regular Expression for `sentence-end'
8401 =========================================
8402
8403 The symbol `sentence-end' is bound to the pattern that marks the end
8404 of a sentence. What should this regular expression be?
8405
8406 Clearly, a sentence may be ended by a period, a question mark, or an
8407 exclamation mark. Indeed, only clauses that end with one of those
8408 three characters should be considered the end of a sentence. This
8409 means that the pattern should include the character set:
8410
8411 [.?!]
8412
8413 However, we do not want `forward-sentence' merely to jump to a
8414 period, a question mark, or an exclamation mark, because such a
8415 character might be used in the middle of a sentence. A period, for
8416 example, is used after abbreviations. So other information is needed.
8417
8418 According to convention, you type two spaces after every sentence, but
8419 only one space after a period, a question mark, or an exclamation
8420 mark in the body of a sentence. So a period, a question mark, or an
8421 exclamation mark followed by two spaces is a good indicator of an end
8422 of sentence. However, in a file, the two spaces may instead be a tab
8423 or the end of a line. This means that the regular expression should
8424 include these three items as alternatives.
8425
8426 This group of alternatives will look like this:
8427
8428 \\($\\| \\| \\)
8429 ^ ^^
8430 TAB SPC
8431
8432 Here, `$' indicates the end of the line, and I have pointed out where
8433 the tab and two spaces are inserted in the expression. Both are
8434 inserted by putting the actual characters into the expression.
8435
8436 Two backslashes, `\\', are required before the parentheses and
8437 vertical bars: the first backslash quotes the following backslash in
8438 Emacs; and the second indicates that the following character, the
8439 parenthesis or the vertical bar, is special.
8440
8441 Also, a sentence may be followed by one or more carriage returns, like
8442 this:
8443
8444 [
8445 ]*
8446
8447 Like tabs and spaces, a carriage return is inserted into a regular
8448 expression by inserting it literally. The asterisk indicates that the
8449 <RET> is repeated zero or more times.
8450
8451 But a sentence end does not consist only of a period, a question mark
8452 or an exclamation mark followed by appropriate space: a closing
8453 quotation mark or a closing brace of some kind may precede the space.
8454 Indeed more than one such mark or brace may precede the space.
8455 These require a expression that looks like this:
8456
8457 []\"')}]*
8458
8459 In this expression, the first `]' is the first character in the
8460 expression; the second character is `"', which is preceded by a `\'
8461 to tell Emacs the `"' is _not_ special. The last three characters
8462 are `'', `)', and `}'.
8463
8464 All this suggests what the regular expression pattern for matching the
8465 end 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
8472 The `re-search-forward' Function
8473 ================================
8474
8475 The `re-search-forward' function is very like the `search-forward'
8476 function. (*Note The `search-forward' Function: search-forward.)
8477
8478 `re-search-forward' searches for a regular expression. If the search
8479 is successful, it leaves point immediately after the last character
8480 in the target. If the search is backwards, it leaves point just
8481 before the first character in the target. You may tell
8482 `re-search-forward' to return `t' for true. (Moving point is
8483 therefore a `side effect'.)
8484
8485 Like `search-forward', the `re-search-forward' function takes four
8486 arguments:
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
8505 The 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
8512 The second, third, and fourth arguments are optional. However, if you
8513 want to pass a value to either or both of the last two arguments, you
8514 must also pass a value to all the preceding arguments. Otherwise, the
8515 Lisp interpreter will mistake which argument you are passing the value
8516 to.
8517
8518 In the `forward-sentence' function, the regular expression will be
8519 the value of the variable `sentence-end', namely:
8520
8521 "[.?!][]\"')}]*\\($\\| \\| \\)[
8522 ]*"
8523
8524 The limit of the search will be the end of the paragraph (since a
8525 sentence cannot go beyond a paragraph). If the search fails, the
8526 function will return `nil'; and the repeat count will be provided by
8527 the argument to the `forward-sentence' function.
8528
8529 `forward-sentence'
8530 ==================
8531
8532 The command to move the cursor forward a sentence is a straightforward
8533 illustration of how to use regular expression searches in Emacs Lisp.
8534 Indeed, the function looks longer and more complicated than it is;
8535 this is because the function is designed to go backwards as well as
8536 forwards; and, optionally, over more than one sentence. The function
8537 is usually bound to the key command `M-e'.
8538
8539 Complete `forward-sentence' function definition
8540 -----------------------------------------------
8541
8542 Here 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
8568 The function looks long at first sight and it is best to look at its
8569 skeleton first, and then its muscle. The way to see the skeleton is
8570 to 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
8581 This looks much simpler! The function definition consists of
8582 documentation, an `interactive' expression, an `or' expression, and
8583 `while' loops.
8584
8585 Let's look at each of these parts in turn.
8586
8587 We note that the documentation is thorough and understandable.
8588
8589 The function has an `interactive "p"' declaration. This means that
8590 the processed prefix argument, if any, is passed to the function as
8591 its argument. (This will be a number.) If the function is not
8592 passed an argument (it is optional) then the argument `arg' will be
8593 bound to 1. When `forward-sentence' is called non-interactively
8594 without an argument, `arg' is bound to `nil'.
8595
8596 The `or' expression handles the prefix argument. What it does is
8597 either leave the value of `arg' as it is, but only if `arg' is bound
8598 to a value; or it sets the value of `arg' to 1, in the case when
8599 `arg' is bound to `nil'.
8600
8601 The `while' loops
8602 -----------------
8603
8604 Two `while' loops follow the `or' expression. The first `while' has
8605 a true-or-false-test that tests true if the prefix argument for
8606 `forward-sentence' is a negative number. This is for going
8607 backwards. The body of this loop is similar to the body of the
8608 second `while' clause, but it is not exactly the same. We will skip
8609 this `while' loop and concentrate on the second `while' loop.
8610
8611 The second `while' loop is for moving point forward. Its skeleton
8612 looks 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
8621 The `while' loop is of the decrementing kind. (*Note A Loop with a
8622 Decrementing Counter: Decrementing Loop.) It has a
8623 true-or-false-test that tests true so long as the counter (in this
8624 case, the variable `arg') is greater than zero; and it has a
8625 decrementer that subtracts 1 from the value of the counter every time
8626 the loop repeats.
8627
8628 If no prefix argument is given to `forward-sentence', which is the
8629 most common way the command is used, this `while' loop will run once,
8630 since the value of `arg' will be 1.
8631
8632 The body of the `while' loop consists of a `let' expression, which
8633 creates and binds a local variable, and has, as its body, an `if'
8634 expression.
8635
8636 The 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
8644 The `let' expression creates and binds the local variable `par-end'.
8645 As we shall see, this local variable is designed to provide a bound
8646 or limit to the regular expression search. If the search fails to
8647 find a proper sentence ending in the paragraph, it will stop on
8648 reaching the end of the paragraph.
8649
8650 But first, let us examine how `par-end' is bound to the value of the
8651 end of the paragraph. What happens is that the `let' sets the value
8652 of `par-end' to the value returned when the Lisp interpreter
8653 evaluates the expression
8654
8655 (save-excursion (end-of-paragraph-text) (point))
8656
8657 In this expression, `(end-of-paragraph-text)' moves point to the end
8658 of 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'
8661 expression, which is the position of the end of the paragraph. (The
8662 `(end-of-paragraph-text)' function uses `forward-paragraph', which we
8663 will discuss shortly.)
8664
8665 Emacs next evaluates the body of the `let', which is an `if'
8666 expression 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
8672 The `if' tests whether its first argument is true and if so,
8673 evaluates its then-part; otherwise, the Emacs Lisp interpreter
8674 evaluates the else-part. The true-or-false-test of the `if'
8675 expression is the regular expression search.
8676
8677 It 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
8679 this kind of operation is carried out in Lisp.
8680
8681 The regular expression search
8682 -----------------------------
8683
8684 The `re-search-forward' function searches for the end of the
8685 sentence, that is, for the pattern defined by the `sentence-end'
8686 regular expression. If the pattern is found--if the end of the
8687 sentence is found--then the `re-search-forward' function does two
8688 things:
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
8697 The side effect, the movement of point, is completed before the `if'
8698 function is handed the value returned by the successful conclusion of
8699 the search.
8700
8701 When the `if' function receives the value of true from a successful
8702 call to `re-search-forward', the `if' evaluates the then-part, which
8703 is the expression `(skip-chars-backward " \t\n")'. This expression
8704 moves backwards over any blank spaces, tabs or carriage returns until
8705 a printed character is found and then leaves point after the
8706 character. Since point has already been moved to the end of the
8707 pattern that marks the end of the sentence, this action leaves point
8708 right after the closing printed character of the sentence, which is
8709 usually a period.
8710
8711 On the other hand, if the `re-search-forward' function fails to find
8712 a pattern marking the end of the sentence, the function returns
8713 false. The false then causes the `if' to evaluate its third
8714 argument, which is `(goto-char par-end)': it moves point to the end
8715 of the paragraph.
8716
8717 Regular expression searches are exceptionally useful and the pattern
8718 illustrated by `re-search-forward', in which the search is the test
8719 of an `if' expression, is handy. You will see or write code
8720 incorporating this pattern often.
8721
8722 `forward-paragraph': a Goldmine of Functions
8723 ============================================
8724
8725 The `forward-paragraph' function moves point forward to the end of
8726 the paragraph. It is usually bound to `M-}' and makes use of a
8727 number of functions that are important in themselves, including
8728 `let*', `match-beginning', and `looking-at'.
8729
8730 The function definition for `forward-paragraph' is considerably
8731 longer than the function definition for `forward-sentence' because it
8732 works with a paragraph, each line of which may begin with a fill
8733 prefix.
8734
8735 A fill prefix consists of a string of characters that are repeated at
8736 the beginning of each line. For example, in Lisp code, it is a
8737 convention to start each line of a paragraph-long comment with `;;;
8738 '. In Text mode, four blank spaces make up another common fill
8739 prefix, creating an indented paragraph. (*Note Fill Prefix:
8740 (emacs)Fill Prefix, for more information about fill prefixes.)
8741
8742 The existence of a fill prefix means that in addition to being able to
8743 find the end of a paragraph whose lines begin on the left-most
8744 column, the `forward-paragraph' function must be able to find the end
8745 of a paragraph when all or many of the lines in the buffer begin with
8746 the fill prefix.
8747
8748 Moreover, it is sometimes practical to ignore a fill prefix that
8749 exists, especially when blank lines separate paragraphs. This is an
8750 added complication.
8751
8752 Shortened `forward-paragraph' function definition
8753 -------------------------------------------------
8754
8755 Rather than print all of the `forward-paragraph' function, we will
8756 only print parts of it. Read without preparation, the function can
8757 be daunting!
8758
8759 In 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
8774 The first parts of the function are routine: the function's argument
8775 list consists of one optional argument. Documentation follows.
8776
8777 The lower case `p' in the `interactive' declaration means that the
8778 processed prefix argument, if any, is passed to the function. This
8779 will be a number, and is the repeat count of how many paragraphs
8780 point will move. The `or' expression in the next line handles the
8781 common case when no argument is passed to the function, which occurs
8782 if the function is called from other code rather than interactively.
8783 This case was described earlier. (*Note The `forward-sentence'
8784 function: forward-sentence.) Now we reach the end of the familiar
8785 part of this function.
8786
8787 The `let*' expression
8788 ---------------------
8789
8790 The next line of the `forward-paragraph' function begins a `let*'
8791 expression. This is a different kind of expression than we have seen
8792 so far. The symbol is `let*' not `let'.
8793
8794 The `let*' special form is like `let' except that Emacs sets each
8795 variable in sequence, one after another, and variables in the latter
8796 part of the varlist can make use of the values to which Emacs set
8797 variables in the earlier part of the varlist.
8798
8799 In 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
8804 Let's look at each in turn. The symbol `fill-prefix-regexp' is set
8805 to 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
8812 This is an expression whose first element is the `and' special form.
8813
8814 As we learned earlier (*note The `kill-new' function: kill-new
8815 function.), the `and' special form evaluates each of its arguments
8816 until one of the arguments returns a value of `nil', in which case
8817 the `and' expression returns `nil'; however, if none of the arguments
8818 returns a value of `nil', the value resulting from evaluating the
8819 last argument is returned. (Since such a value is not `nil', it is
8820 considered true in Lisp.) In other words, an `and' expression
8821 returns a true value only if all its arguments are true.
8822
8823 In this case, the variable `fill-prefix-regexp' is bound to a
8824 non-`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
8849 The result of evaluating this `and' expression successfully is that
8850 `fill-prefix-regexp' will be bound to the value of `fill-prefix' as
8851 modified by the `regexp-quote' function. What `regexp-quote' does is
8852 read a string and return a regular expression that will exactly match
8853 the string and match nothing else. This means that
8854 `fill-prefix-regexp' will be set to a value that will exactly match
8855 the fill prefix if the fill prefix exists. Otherwise, the variable
8856 will be set to `nil'.
8857
8858 The second local variable in the `let*' expression is
8859 `paragraph-separate'. It is bound to the value returned by
8860 evaluating the expression:
8861
8862 (if fill-prefix-regexp
8863 (concat paragraph-separate
8864 "\\|^" fill-prefix-regexp "[ \t]*$")
8865 paragraph-separate)))
8866
8867 This expression shows why `let*' rather than `let' was used. The
8868 true-or-false-test for the `if' depends on whether the variable
8869 `fill-prefix-regexp' evaluates to `nil' or some other value.
8870
8871 If `fill-prefix-regexp' does not have a value, Emacs evaluates the
8872 else-part of the `if' expression and binds `paragraph-separate' to
8873 its local value. (`paragraph-separate' is a regular expression that
8874 matches what separates paragraphs.)
8875
8876 But if `fill-prefix-regexp' does have a value, Emacs evaluates the
8877 then-part of the `if' expression and binds `paragraph-separate' to a
8878 regular expression that includes the `fill-prefix-regexp' as part of
8879 the pattern.
8880
8881 Specifically, `paragraph-separate' is set to the original value of
8882 the paragraph separate regular expression concatenated with an
8883 alternative expression that consists of the `fill-prefix-regexp'
8884 followed by a blank line. The `^' indicates that the
8885 `fill-prefix-regexp' must begin a line, and the optional whitespace
8886 to the end of the line is defined by `"[ \t]*$"'.) The `\\|' defines
8887 this portion of the regexp as an alternative to `paragraph-separate'.
8888
8889 Now we get into the body of the `let*'. The first part of the body
8890 of the `let*' deals with the case when the function is given a
8891 negative argument and is therefore moving backwards. We will skip
8892 this section.
8893
8894 The forward motion `while' loop
8895 -------------------------------
8896
8897 The second part of the body of the `let*' deals with forward motion.
8898 It 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,
8900 the value of the argument is 1, so the body of the `while' loop is
8901 evaluated exactly once, and the cursor moves forward one paragraph.
8902
8903 This part handles three situations: when point is between paragraphs,
8904 when point is within a paragraph and there is a fill prefix, and when
8905 point is within a paragraph and there is no fill prefix.
8906
8907 The `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
8932 We can see immediately that this is a decrementing counter `while'
8933 loop, using the expression `(setq arg (1- arg))' as the decrementer.
8934
8935 The 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
8949 When the Emacs Lisp interpreter evaluates the body of the `while'
8950 loop, the first thing it does is evaluate the `(beginning-of-line)'
8951 expression and move point to the beginning of the line. Then there
8952 is an inner `while' loop. This `while' loop is designed to move the
8953 cursor out of the blank space between paragraphs, if it should happen
8954 to be there. Finally, there is an `if' expression that actually
8955 moves point to the end of the paragraph.
8956
8957 Between paragraphs
8958 ------------------
8959
8960 First, let us look at the inner `while' loop. This loop handles the
8961 case when point is between paragraphs; it uses three functions that
8962 are 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
8978 The `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
8984 This is a `while' loop with no body! The true-or-false-test of the
8985 loop is the expression:
8986
8987 (prog1 (and (not (eobp))
8988 (looking-at paragraph-separate))
8989 (forward-line 1))
8990
8991 The first argument to the `prog1' is the `and' expression. It has
8992 within in it a test of whether point is at the end of the buffer and
8993 also a test of whether the pattern following point matches the regular
8994 expression for separating paragraphs.
8995
8996 If the cursor is not at the end of the buffer and if the characters
8997 following the cursor mark the separation between two paragraphs, then
8998 the `and' expression is true. After evaluating the `and' expression,
8999 the Lisp interpreter evaluates the second argument to `prog1', which
9000 is `forward-line'. This moves point forward one line. The value
9001 returned by the `prog1' however, is the value of its first argument,
9002 so the `while' loop continues so long as point is not at the end of
9003 the buffer and is between paragraphs. When, finally, point is moved
9004 to a paragraph, the `and' expression tests false. Note however, that
9005 the `forward-line' command is carried out anyhow. This means that
9006 when point is moved from between paragraphs to a paragraph, it is left
9007 at the beginning of the second line of the paragraph.
9008
9009 Within paragraphs
9010 -----------------
9011
9012 The next expression in the outer `while' loop is an `if' expression.
9013 The Lisp interpreter evaluates the then-part of the `if' when the
9014 `fill-prefix-regexp' variable has a value other than `nil', and it
9015 evaluates the else-part when the value of `if fill-prefix-regexp' is
9016 `nil', that is, when there is no fill prefix.
9017
9018 No fill prefix
9019 --------------
9020
9021 It is simplest to look at the code for the case when there is no fill
9022 prefix first. This code consists of yet another inner `if'
9023 expression, 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
9029 This expression actually does the work that most people think of as
9030 the primary purpose of the `forward-paragraph' command: it causes a
9031 regular expression search to occur that searches forward to the start
9032 of the next paragraph and if it is found, moves point there; but if
9033 the start of another paragraph if not found, it moves point to the
9034 end of the accessible region of the buffer.
9035
9036 The only unfamiliar part of this is the use of `match-beginning'.
9037 This is another function that is new to us. The `match-beginning'
9038 function returns a number specifying the location of the start of the
9039 text that was matched by the last regular expression search.
9040
9041 The `match-beginning' function is used here because of a
9042 characteristic of a forward search: a successful forward search,
9043 regardless of whether it is a plain search or a regular expression
9044 search, will move point to the end of the text that is found. In this
9045 case, a successful search will move point to the end of the pattern
9046 for `paragraph-start', which will be the beginning of the next
9047 paragraph rather than the end of the current one.
9048
9049 However, we want to put point at the end of the current paragraph,
9050 not at the beginning of the next one. The two positions may be
9051 different, because there may be several blank lines between
9052 paragraphs.
9053
9054 When given an argument of 0, `match-beginning' returns the position
9055 that is the start of the text that the most recent regular expression
9056 search matched. In this case, the most recent regular expression
9057 search is the one looking for `paragraph-start', so `match-beginning'
9058 returns the beginning position of the pattern, rather than the end of
9059 the 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
9063 expression in the last regular expression. It is a useful function.)
9064
9065 With a fill prefix
9066 ------------------
9067
9068 The inner `if' expression just discussed is the else-part of an
9069 enclosing `if' expression which tests whether there is a fill prefix.
9070 If there is a fill prefix, the then-part of this `if' is evaluated.
9071 It 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
9078 What this expression does is move point forward line by line so long
9079 as 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
9088 The last condition may be puzzling, until you remember that point was
9089 moved to the beginning of the line early in the `forward-paragraph'
9090 function. This means that if the text has a fill prefix, the
9091 `looking-at' function will see it.
9092
9093 Summary
9094 -------
9095
9096 In summary, when moving forward, the `forward-paragraph' function
9097 does 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
9118 For review, here is the code we have just been discussing, formatted
9119 for 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
9158 The full definition for the `forward-paragraph' function not only
9159 includes this code for going forwards, but also code for going
9160 backwards.
9161
9162 If you are reading this inside of GNU Emacs and you want to see the
9163 whole function, you can type `C-h f' (`describe-function') and the
9164 name of the function. This gives you the function documentation and
9165 the name of the library containing the function's source. Place
9166 point over the name of the library and press the RET key; you will be
9167 taken directly to the source. (Be sure to install your sources!
9168 Without them, you are like a person who tries to drive a car with his
9169 eyes shut!)
9170
9171 Or - a good habit to get into - you can type `M-.' (`find-tag') and
9172 the name of the function when prompted for it. This will take you
9173 directly to the source. If the `find-tag' function first asks you
9174 for the name of a `TAGS' table, give it the name of the `TAGS' file
9175 such as `/usr/local/share/emacs/21.0.100/lisp/TAGS'. (The exact path
9176 to your `TAGS' file depends on how your copy of Emacs was installed.)
9177
9178 You can also create your own `TAGS' file for directories that lack
9179 one. *Note Create Your Own `TAGS' File: etags.
9180
9181 Create Your Own `TAGS' File
9182 ===========================
9183
9184 The `M-.' (`find-tag') command takes you directly to the source for a
9185 function, variable, node, or other source. The function depends on
9186 tags tables to tell it where to go.
9187
9188 You often need to build and install tags tables yourself. They are
9189 not built automatically. A tags table is called a `TAGS' file; the
9190 name is in upper case letters.
9191
9192 You can create a `TAGS' file by calling the `etags' program that
9193 comes as a part of the Emacs distribution. Usually, `etags' is
9194 compiled and installed when Emacs is built. (`etags' is not an Emacs
9195 Lisp function or a part of Emacs; it is a C program.)
9196
9197 To create a `TAGS' file, first switch to the directory in which you
9198 want to create the file. In Emacs you can do this with the `M-x cd'
9199 command, or by visiting a file in the directory, or by listing the
9200 directory 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
9205 to create a `TAGS' file.
9206
9207 For example, if you have a large number of files in your `~/emacs'
9208 directory, as I do--I have 137 `.el' files in it, of which I load
9209 12--you can create a `TAGS' file for the Emacs Lisp files in that
9210 directory.
9211
9212 The `etags' program takes all the usual shell `wildcards'. For
9213 example, if you have two directories for which you want a single
9214 `TAGS file', type `etags *.el ../elisp/*.el', where `../elisp/' is
9215 the second directory:
9216
9217 M-x compile RET etags *.el ../elisp/*.el RET
9218
9219 Type
9220
9221 M-x compile RET etags --help RET
9222
9223 to see a list of the options accepted by `etags' as well as a list of
9224 supported languages.
9225
9226 The `etags' program handles more than 20 languages, including Emacs
9227 Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX, Pascal,
9228 Perl, Python, Texinfo, makefiles, and most assemblers. The program
9229 has no switches for specifying the language; it recognizes the
9230 language 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
9233 to refer back to functions you have already written. Just run
9234 `etags' again at intervals as you write new functions, so they become
9235 part of the `TAGS' file.
9236
9237 If you think an appropriate `TAGS' file already exists for what you
9238 want, but do not know where it is, you can use the `locate' program
9239 to attempt to find it.
9240
9241 Type `M-x locate RET TAGS RET' and Emacs will list for you the full
9242 path names of all your `TAGS' files. On my system, this command
9243 lists 34 `TAGS' files. On the other hand, a `plain vanilla' system I
9244 recently installed did not contain any `TAGS' files.
9245
9246 If the tags table you want has been created, you can use the `M-x
9247 visit-tags-table' command to specify it. Otherwise, you will need to
9248 create the tag table yourself and then use `M-x visit-tags-table'.
9249
9250 Building Tags in the Emacs sources
9251 ..................................
9252
9253 The GNU Emacs sources come with a `Makefile' that contains a
9254 sophisticated `etags' command that creates, collects, and merges tags
9255 tables from all over the Emacs sources and puts the information into
9256 one `TAGS' file in the `src/' directory below the top level of your
9257 Emacs source directory.
9258
9259 To build this `TAGS' file, go to the top level of your Emacs source
9260 directory 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
9265 well as with some other source packages.)
9266
9267 For more information, see *Note Tag Tables: (emacs)Tags.
9268
9269 Review
9270 ======
9271
9272 Here 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
9348 Exercises 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
9362 Counting: Repetition and Regexps
9363 ********************************
9364
9365 Repetition and regular expression searches are powerful tools that you
9366 often use when you write code in Emacs Lisp. This chapter illustrates
9367 the use of regular expression searches through the construction of
9368 word count commands using `while' loops and recursion.
9369
9370 Counting words
9371 ==============
9372
9373 The standard Emacs distribution contains a function for counting the
9374 number of lines within a region. However, there is no corresponding
9375 function for counting words.
9376
9377 Certain types of writing ask you to count words. Thus, if you write
9378 an essay, you may be limited to 800 words; if you write a novel, you
9379 may discipline yourself to write 1000 words a day. It seems odd to me
9380 that Emacs lacks a word count command. Perhaps people use Emacs
9381 mostly for code or types of documentation that do not require word
9382 counts; or perhaps they restrict themselves to the operating system
9383 word count command, `wc'. Alternatively, people may follow the
9384 publishers' convention and compute a word count by dividing the
9385 number of characters in a document by five. In any event, here are
9386 commands to count words.
9387
9388 The `count-words-region' Function
9389 =================================
9390
9391 A word count command could count words in a line, paragraph, region,
9392 or buffer. What should the command cover? You could design the
9393 command to count the number of words in a complete buffer. However,
9394 the Emacs tradition encourages flexibility--you may want to count
9395 words in just a section, rather than all of a buffer. So it makes
9396 more sense to design the command to count the number of words in a
9397 region. Once you have a `count-words-region' command, you can, if
9398 you wish, count words in a whole buffer by marking it with `C-x h'
9399 (`mark-whole-buffer').
9400
9401 Clearly, counting words is a repetitive act: starting from the
9402 beginning of the region, you count the first word, then the second
9403 word, then the third word, and so on, until you reach the end of the
9404 region. This means that word counting is ideally suited to recursion
9405 or to a `while' loop.
9406
9407 Designing `count-words-region'
9408 ------------------------------
9409
9410 First, we will implement the word count command with a `while' loop,
9411 then with recursion. The command will, of course, be interactive.
9412
9413 The 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
9420 What we need to do is fill in the slots.
9421
9422 The name of the function should be self-explanatory and similar to the
9423 existing `count-lines-region' name. This makes the name easier to
9424 remember. `count-words-region' is a good choice.
9425
9426 The function counts words within a region. This means that the
9427 argument list must contain symbols that are bound to the two
9428 positions, the beginning and end of the region. These two positions
9429 can be called `beginning' and `end' respectively. The first line of
9430 the documentation should be a single sentence, since that is all that
9431 is printed as documentation by a command such as `apropos'. The
9432 interactive expression will be of the form `(interactive "r")', since
9433 that will cause Emacs to pass the beginning and end of the region to
9434 the function's argument list. All this is routine.
9435
9436 The body of the function needs to be written to do three tasks:
9437 first, to set up conditions under which the `while' loop can count
9438 words, second, to run the `while' loop, and third, to send a message
9439 to the user.
9440
9441 When a user calls `count-words-region', point may be at the beginning
9442 or the end of the region. However, the counting process must start
9443 at the beginning of the region. This means we will want to put point
9444 there if it is not already there. Executing `(goto-char beginning)'
9445 ensures this. Of course, we will want to return point to its
9446 expected position when the function finishes its work. For this
9447 reason, the body must be enclosed in a `save-excursion' expression.
9448
9449 The central part of the body of the function consists of a `while'
9450 loop in which one expression jumps point forward word by word, and
9451 another expression counts those jumps. The true-or-false-test of the
9452 `while' loop should test true so long as point should jump forward,
9453 and false when point is at the end of the region.
9454
9455 We could use `(forward-word 1)' as the expression for moving point
9456 forward word by word, but it is easier to see what Emacs identifies
9457 as a `word' if we use a regular expression search.
9458
9459 A regular expression search that finds the pattern for which it is
9460 searching leaves point after the last character matched. This means
9461 that a succession of successful word searches will move point forward
9462 word by word.
9463
9464 As a practical matter, we want the regular expression search to jump
9465 over whitespace and punctuation between words as well as over the
9466 words themselves. A regexp that refuses to jump over interword
9467 whitespace would never jump more than one word! This means that the
9468 regexp should include the whitespace and punctuation that follows a
9469 word, if any, as well as the word itself. (A word may end a buffer
9470 and not have any following whitespace or punctuation, so that part of
9471 the regexp must be optional.)
9472
9473 Thus, what we want for the regexp is a pattern defining one or more
9474 word constituent characters followed, optionally, by one or more
9475 characters that are not word constituents. The regular expression for
9476 this is:
9477
9478 \w+\W*
9479
9480 The buffer's syntax table determines which characters are and are not
9481 word constituents. (*Note What Constitutes a Word or Symbol?:
9482 Syntax, for more about syntax. Also, see *Note Syntax:
9483 (emacs)Syntax, and *Note Syntax Tables: (elisp)Syntax Tables.)
9484
9485 The 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
9490 backslash has special meaning to the Emacs Lisp interpreter. It
9491 indicates that the following character is interpreted differently than
9492 usual. For example, the two characters, `\n', stand for `newline',
9493 rather than for a backslash followed by `n'. Two backslashes in a
9494 row stand for an ordinary, `unspecial' backslash.)
9495
9496 We need a counter to count how many words there are; this variable
9497 must first be set to 0 and then incremented each time Emacs goes
9498 around the `while' loop. The incrementing expression is simply:
9499
9500 (setq count (1+ count))
9501
9502 Finally, we want to tell the user how many words there are in the
9503 region. The `message' function is intended for presenting this kind
9504 of information to the user. The message has to be phrased so that it
9505 reads properly regardless of how many words there are in the region:
9506 we don't want to say that "there are 1 words in the region". The
9507 conflict between singular and plural is ungrammatical. We can solve
9508 this problem by using a conditional expression that evaluates
9509 different messages depending on the number of words in the region.
9510 There are three possibilities: no words in the region, one word in the
9511 region, and more than one word. This means that the `cond' special
9512 form is appropriate.
9513
9514 All 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
9547 As written, the function works, but not in all circumstances.
9548
9549 The Whitespace Bug in `count-words-region'
9550 ------------------------------------------
9551
9552 The `count-words-region' command described in the preceding section
9553 has two bugs, or rather, one bug with two manifestations. First, if
9554 you mark a region containing only whitespace in the middle of some
9555 text, the `count-words-region' command tells you that the region
9556 contains one word! Second, if you mark a region containing only
9557 whitespace at the end of the buffer or the accessible portion of a
9558 narrowed buffer, the command displays an error message that looks
9559 like this:
9560
9561 Search failed: "\\w+\\W*"
9562
9563 If you are reading this in Info in GNU Emacs, you can test for these
9564 bugs yourself.
9565
9566 First, evaluate the function in the usual manner to install it. Here
9567 is a copy of the definition. Place your cursor after the closing
9568 parenthesis 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
9595 If you wish, you can also install this keybinding by evaluating it:
9596
9597 (global-set-key "\C-c=" 'count-words-region)
9598
9599 To conduct the first test, set mark and point to the beginning and end
9600 of the following line and then type `C-c =' (or `M-x
9601 count-words-region' if you have not bound `C-c ='):
9602
9603 one two three
9604
9605 Emacs will tell you, correctly, that the region has three words.
9606
9607 Repeat the test, but place mark at the beginning of the line and place
9608 point 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
9610 has no words, since it is composed only of the whitespace at the
9611 beginning of the line. But instead Emacs tells you that the region
9612 has one word!
9613
9614 For 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
9616 line. Place mark right after the word `three' and point at the end
9617 of 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,
9619 Emacs should tell you that the region has no words, since it is
9620 composed only of the whitespace at the end of the line. Instead,
9621 Emacs displays an error message saying `Search failed'.
9622
9623 The two bugs stem from the same problem.
9624
9625 Consider the first manifestation of the bug, in which the command
9626 tells you that the whitespace at the beginning of the line contains
9627 one word. What happens is this: The `M-x count-words-region' command
9628 moves point to the beginning of the region. The `while' tests
9629 whether the value of point is smaller than the value of `end', which
9630 it is. Consequently, the regular expression search looks for and
9631 finds the first word. It leaves point after the word. `count' is
9632 set to one. The `while' loop repeats; but this time the value of
9633 point is larger than the value of `end', the loop is exited; and the
9634 function displays a message saying the number of words in the region
9635 is one. In brief, the regular expression search looks for and finds
9636 the word even though it is outside the marked region.
9637
9638 In the second manifestation of the bug, the region is whitespace at
9639 the end of the buffer. Emacs says `Search failed'. What happens is
9640 that the true-or-false-test in the `while' loop tests true, so the
9641 search expression is executed. But since there are no more words in
9642 the buffer, the search fails.
9643
9644 In both manifestations of the bug, the search extends or attempts to
9645 extend outside of the region.
9646
9647 The solution is to limit the search to the region--this is a fairly
9648 simple action, but as you may have come to expect, it is not quite as
9649 simple as you might think.
9650
9651 As we have seen, the `re-search-forward' function takes a search
9652 pattern as its first argument. But in addition to this first,
9653 mandatory argument, it accepts three optional arguments. The optional
9654 second argument bounds the search. The optional third argument, if
9655 `t', causes the function to return `nil' rather than signal an error
9656 if 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',
9658 the name of the function, and then <RET>.)
9659
9660 In the `count-words-region' definition, the value of the end of the
9661 region is held by the variable `end' which is passed as an argument
9662 to the function. Thus, we can add `end' as an argument to the
9663 regular expression search expression:
9664
9665 (re-search-forward "\\w+\\W*" end)
9666
9667 However, if you make only this change to the `count-words-region'
9668 definition and then test the new version of the definition on a
9669 stretch of whitespace, you will receive an error message saying
9670 `Search failed'.
9671
9672 What happens is this: the search is limited to the region, and fails
9673 as you expect because there are no word-constituent characters in the
9674 region. Since it fails, we receive an error message. But we do not
9675 want to receive an error message in this case; we want to receive the
9676 message that "The region does NOT have any words."
9677
9678 The solution to this problem is to provide `re-search-forward' with a
9679 third argument of `t', which causes the function to return `nil'
9680 rather than signal an error if the search fails.
9681
9682 However, 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
9684 message ..., until you type `C-g' (`keyboard-quit').
9685
9686 Here is what happens: the search is limited to the region, as before,
9687 and it fails because there are no word-constituent characters in the
9688 region, as expected. Consequently, the `re-search-forward'
9689 expression returns `nil'. It does nothing else. In particular, it
9690 does not move point, which it does as a side effect if it finds the
9691 search target. After the `re-search-forward' expression returns
9692 `nil', the next expression in the `while' loop is evaluated. This
9693 expression increments the count. Then the loop repeats. The
9694 true-or-false-test tests true because the value of point is still less
9695 than the value of end, since the `re-search-forward' expression did
9696 not move point. ... and the cycle repeats ...
9697
9698 The `count-words-region' definition requires yet another
9699 modification, to cause the true-or-false-test of the `while' loop to
9700 test false if the search fails. Put another way, there are two
9701 conditions that must be satisfied in the true-or-false-test before the
9702 word count variable is incremented: point must still be within the
9703 region and the search expression must have found a word to count.
9704
9705 Since both the first condition and the second condition must be true
9706 together, the two expressions, the region test and the search
9707 expression, can be joined with an `and' special form and embedded in
9708 the `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
9714 The `re-search-forward' expression returns `t' if the search succeeds
9715 and as a side effect moves point. Consequently, as words are found,
9716 point is moved through the region. When the search expression fails
9717 to find another word, or when point reaches the end of the region,
9718 the 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
9721 After incorporating these final changes, the `count-words-region'
9722 works without bugs (or at least, without bugs that I have found!).
9723 Here 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
9752 Count Words Recursively
9753 =======================
9754
9755 You can write the function for counting words recursively as well as
9756 with a `while' loop. Let's see how this is done.
9757
9758 First, we need to recognize that the `count-words-region' function
9759 has three jobs: it sets up the appropriate conditions for counting to
9760 occur; it counts the words in the region; and it sends a message to
9761 the user telling how many words there are.
9762
9763 If we write a single recursive function to do everything, we will
9764 receive a message for every recursive call. If the region contains 13
9765 words, we will receive thirteen messages, one right after the other.
9766 We don't want this! Instead, we must write two functions to do the
9767 job, one of which (the recursive function) will be used inside of the
9768 other. One function will set up the conditions and display the
9769 message; the other will return the word count.
9770
9771 Let us start with the function that causes the message to be
9772 displayed. We can continue to call this `count-words-region'.
9773
9774 This is the function that the user will call. It will be interactive.
9775 Indeed, it will be similar to our previous versions of this function,
9776 except that it will call `recursive-count-words' to determine how
9777 many words are in the region.
9778
9779 We can readily construct a template for this function, based on our
9780 previous 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
9797 The definition looks straightforward, except that somehow the count
9798 returned by the recursive call must be passed to the message
9799 displaying the word count. A little thought suggests that this can be
9800 done by making use of a `let' expression: we can bind a variable in
9801 the varlist of a `let' expression to the number of words in the
9802 region, as returned by the recursive call; and then the `cond'
9803 expression, using binding, can display the value to the user.
9804
9805 Often, one thinks of the binding within a `let' expression as somehow
9806 secondary to the `primary' work of a function. But in this case,
9807 what you might consider the `primary' job of the function, counting
9808 words, is done within the `let' expression.
9809
9810 Using `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
9835 Next, we need to write the recursive counting function.
9836
9837 A recursive function has at least three parts: the `do-again-test',
9838 the `next-step-expression', and the recursive call.
9839
9840 The do-again-test determines whether the function will or will not be
9841 called again. Since we are counting words in a region and can use a
9842 function that moves point forward for every word, the do-again-test
9843 can check whether point is still within the region. The do-again-test
9844 should find the value of point and determine whether point is before,
9845 at, 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
9847 the end of the region to the recursive counting function as an
9848 argument.
9849
9850 In addition, the do-again-test should also test whether the search
9851 finds a word. If it does not, the function should not call itself
9852 again.
9853
9854 The next-step-expression changes a value so that when the recursive
9855 function is supposed to stop calling itself, it stops. More
9856 precisely, the next-step-expression changes a value so that at the
9857 right time, the do-again-test stops the recursive function from
9858 calling itself again. In this case, the next-step-expression can be
9859 the expression that moves point forward, word by word.
9860
9861 The third part of a recursive function is the recursive call.
9862
9863 Somewhere, also, we also need a part that does the `work' of the
9864 function, a part that does the counting. A vital part!
9865
9866 But 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
9874 Now we need to fill in the slots. Let's start with the simplest cases
9875 first: if point is at or beyond the end of the region, there cannot
9876 be any words in the region, so the function should return zero.
9877 Likewise, if the search fails, there are no words to count, so the
9878 function should return zero.
9879
9880 On the other hand, if point is within the region and the search
9881 succeeds, the function should call itself again.
9882
9883 Thus, the do-again-test should look like this:
9884
9885 (and (< (point) region-end)
9886 (re-search-forward "\\w+\\W*" region-end t))
9887
9888 Note that the search expression is part of the do-again-test--the
9889 function returns `t' if its search succeeds and `nil' if it fails.
9890 (*Note The Whitespace Bug in `count-words-region': Whitespace Bug,
9891 for an explanation of how `re-search-forward' works.)
9892
9893 The do-again-test is the true-or-false test of an `if' clause.
9894 Clearly, if the do-again-test succeeds, the then-part of the `if'
9895 clause should call the function again; but if it fails, the else-part
9896 should return zero since either point is outside the region or the
9897 search failed because there were no words to find.
9898
9899 But before considering the recursive call, we need to consider the
9900 next-step-expression. What is it? Interestingly, it is the search
9901 part of the do-again-test.
9902
9903 In addition to returning `t' or `nil' for the do-again-test,
9904 `re-search-forward' moves point forward as a side effect of a
9905 successful search. This is the action that changes the value of
9906 point so that the recursive function stops calling itself when point
9907 completes its movement through the region. Consequently, the
9908 `re-search-forward' expression is the next-step-expression.
9909
9910 In outline, then, the body of the `recursive-count-words' function
9911 looks 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
9919 How to incorporate the mechanism that counts?
9920
9921 If you are not used to writing recursive functions, a question like
9922 this can be troublesome. But it can and should be approached
9923 systematically.
9924
9925 We know that the counting mechanism should be associated in some way
9926 with the recursive call. Indeed, since the next-step-expression moves
9927 point forward by one word, and since a recursive call is made for
9928 each word, the counting mechanism must be an expression that adds one
9929 to the value returned by a call to `recursive-count-words'.
9930
9931 Consider 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
9946 From the sketch we can see that the else-part of the `if' returns
9947 zero 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
9949 returned from a count of the remaining words.
9950
9951 The expression will look like this, where `1+' is a function that
9952 adds one to its argument.
9953
9954 (1+ (recursive-count-words region-end))
9955
9956 The 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
9971 Let's examine how this works:
9972
9973 If there are no words in the region, the else part of the `if'
9974 expression is evaluated and consequently the function returns zero.
9975
9976 If there is one word in the region, the value of point is less than
9977 the value of `region-end' and the search succeeds. In this case, the
9978 true-or-false-test of the `if' expression tests true, and the
9979 then-part of the `if' expression is evaluated. The counting
9980 expression is evaluated. This expression returns a value (which will
9981 be the value returned by the whole function) that is the sum of one
9982 added to the value returned by a recursive call.
9983
9984 Meanwhile, the next-step-expression has caused point to jump over the
9985 first (and in this case only) word in the region. This means that
9986 when `(recursive-count-words region-end)' is evaluated a second time,
9987 as a result of the recursive call, the value of point will be equal
9988 to or greater than the value of region end. So this time,
9989 `recursive-count-words' will return zero. The zero will be added to
9990 one, and the original evaluation of `recursive-count-words' will
9991 return one plus zero, which is one, which is the correct amount.
9992
9993 Clearly, if there are two words in the region, the first call to
9994 `recursive-count-words' returns one added to the value returned by
9995 calling `recursive-count-words' on a region containing the remaining
9996 word--that is, it adds one to one, producing two, which is the
9997 correct amount.
9998
9999 Similarly, if there are three words in the region, the first call to
10000 `recursive-count-words' returns one added to the value returned by
10001 calling `recursive-count-words' on a region containing the remaining
10002 two words--and so on and so on.
10003
10004 With full documentation the two functions look like this:
10005
10006 The 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
10021 The 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
10045 Exercise: Counting Punctuation
10046 ==============================
10047
10048 Using a `while' loop, write a function to count the number of
10049 punctuation marks in a region--period, comma, semicolon, colon,
10050 exclamation mark, and question mark. Do the same using recursion.
10051
10052 Counting Words in a `defun'
10053 ***************************
10054
10055 Our next project is to count the number of words in a function
10056 definition. Clearly, this can be done using some variant of
10057 `count-word-region'. *Note Counting Words: Repetition and Regexps:
10058 Counting Words. If we are just going to count the words in one
10059 definition, it is easy enough to mark the definition with the `C-M-h'
10060 (`mark-defun') command, and then call `count-word-region'.
10061
10062 However, I am more ambitious: I want to count the words and symbols in
10063 every definition in the Emacs sources and then print a graph that
10064 shows how many functions there are of each length: how many contain 40
10065 to 49 words or symbols, how many contain 50 to 59 words or symbols,
10066 and so on. I have often been curious how long a typical function is,
10067 and this will tell.
10068
10069 Divide and Conquer
10070 ==================
10071
10072 Described in one phrase, the histogram project is daunting; but
10073 divided into numerous small steps, each of which we can take one at a
10074 time, the project becomes less fearsome. Let us consider what the
10075 steps 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
10095 This is quite a project! But if we take each step slowly, it will not
10096 be difficult.
10097
10098 What to Count?
10099 ==============
10100
10101 When we first start thinking about how to count the words in a
10102 function definition, the first question is (or ought to be) what are
10103 we going to count? When we speak of `words' with respect to a Lisp
10104 function definition, we are actually speaking, in large part, of
10105 `symbols'. For example, the following `multiply-by-seven' function
10106 contains the five symbols `defun', `multiply-by-seven', `number',
10107 `*', and `7'. In addition, in the documentation string, it contains
10108 the four words `Multiply', `NUMBER', `by', and `seven'. The symbol
10109 `number' is repeated, so the definition contains a total of ten words
10110 and symbols.
10111
10112 (defun multiply-by-seven (number)
10113 "Multiply NUMBER by seven."
10114 (* 7 number))
10115
10116 However, 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
10118 find that `count-words-region' claims the definition has eleven
10119 words, not ten! Something is wrong!
10120
10121 The problem is twofold: `count-words-region' does not count the `*'
10122 as a word, and it counts the single symbol, `multiply-by-seven', as
10123 containing three words. The hyphens are treated as if they were
10124 interword spaces rather than intraword connectors:
10125 `multiply-by-seven' is counted as if it were written `multiply by
10126 seven'.
10127
10128 The cause of this confusion is the regular expression search within
10129 the `count-words-region' definition that moves point forward word by
10130 word. In the canonical version of `count-words-region', the regexp
10131 is:
10132
10133 "\\w+\\W*"
10134
10135 This regular expression is a pattern defining one or more word
10136 constituent characters possibly followed by one or more characters
10137 that are not word constituents. What is meant by `word constituent
10138 characters' brings us to the issue of syntax, which is worth a section
10139 of its own.
10140
10141 What Constitutes a Word or Symbol?
10142 ==================================
10143
10144 Emacs treats different characters as belonging to different "syntax
10145 categories". For example, the regular expression, `\\w+', is a
10146 pattern specifying one or more _word constituent_ characters. Word
10147 constituent characters are members of one syntax category. Other
10148 syntax categories include the class of punctuation characters, such
10149 as the period and the comma, and the class of whitespace characters,
10150 such as the blank space and the tab character. (For more
10151 information, see *Note Syntax: (emacs)Syntax, and *Note Syntax
10152 Tables: (elisp)Syntax Tables.)
10153
10154 Syntax tables specify which characters belong to which categories.
10155 Usually, a hyphen is not specified as a `word constituent character'.
10156 Instead, it is specified as being in the `class of characters that are
10157 part of symbol names but not words.' This means that the
10158 `count-words-region' function treats it in the same way it treats an
10159 interword white space, which is why `count-words-region' counts
10160 `multiply-by-seven' as three words.
10161
10162 There are two ways to cause Emacs to count `multiply-by-seven' as one
10163 symbol: modify the syntax table or modify the regular expression.
10164
10165 We could redefine a hyphen as a word constituent character by
10166 modifying the syntax table that Emacs keeps for each mode. This
10167 action would serve our purpose, except that a hyphen is merely the
10168 most common character within symbols that is not typically a word
10169 constituent character; there are others, too.
10170
10171 Alternatively, we can redefine the regular expression used in the
10172 `count-words' definition so as to include symbols. This procedure
10173 has the merit of clarity, but the task is a little tricky.
10174
10175 The first part is simple enough: the pattern must match "at least one
10176 character that is a word or symbol constituent". Thus:
10177
10178 "\\(\\w\\|\\s_\\)+"
10179
10180 The `\\(' is the first part of the grouping construct that includes
10181 the `\\w' and the `\\s_' as alternatives, separated by the `\\|'.
10182 The `\\w' matches any word-constituent character and the `\\s_'
10183 matches any character that is part of a symbol name but not a
10184 word-constituent character. The `+' following the group indicates
10185 that the word or symbol constituent characters must be matched at
10186 least once.
10187
10188 However, the second part of the regexp is more difficult to design.
10189 What we want is to follow the first part with "optionally one or more
10190 characters that are not constituents of a word or symbol". At first,
10191 I thought I could define this with the following:
10192
10193 "\\(\\W\\|\\S_\\)*"
10194
10195 The upper case `W' and `S' match characters that are _not_ word or
10196 symbol constituents. Unfortunately, this expression matches any
10197 character that is either not a word constituent or not a symbol
10198 constituent. This matches any character!
10199
10200 I then noticed that every word or symbol in my test region was
10201 followed by white space (blank space, tab, or newline). So I tried
10202 placing a pattern to match one or more blank spaces after the pattern
10203 for one or more word or symbol constituents. This failed, too. Words
10204 and symbols are often separated by whitespace, but in actual code
10205 parentheses may follow symbols and punctuation may follow words. So
10206 finally, I designed a pattern in which the word or symbol constituents
10207 are followed optionally by characters that are not white space and
10208 then followed optionally by white space.
10209
10210 Here is the full regular expression:
10211
10212 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
10213
10214 The `count-words-in-defun' Function
10215 ===================================
10216
10217 We have seen that there are several ways to write a
10218 `count-word-region' function. To write a `count-words-in-defun', we
10219 need merely adapt one of these versions.
10220
10221 The version that uses a `while' loop is easy to understand, so I am
10222 going to adapt that. Because `count-words-in-defun' will be part of
10223 a more complex program, it need not be interactive and it need not
10224 display a message but just return the count. These considerations
10225 simplify the definition a little.
10226
10227 On the other hand, `count-words-in-defun' will be used within a
10228 buffer that contains function definitions. Consequently, it is
10229 reasonable to ask that the function determine whether it is called
10230 when point is within a function definition, and if it is, to return
10231 the count for that definition. This adds complexity to the
10232 definition, but saves us from needing to pass arguments to the
10233 function.
10234
10235 These 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
10243 As usual, our job is to fill in the slots.
10244
10245 First, the set up.
10246
10247 We are presuming that this function will be called within a buffer
10248 containing function definitions. Point will either be within a
10249 function definition or not. For `count-words-in-defun' to work,
10250 point must move to the beginning of the definition, a counter must
10251 start at zero, and the counting loop must stop when point reaches the
10252 end of the definition.
10253
10254 The `beginning-of-defun' function searches backwards for an opening
10255 delimiter such as a `(' at the beginning of a line, and moves point
10256 to that position, or else to the limit of the search. In practice,
10257 this means that `beginning-of-defun' moves point to the beginning of
10258 an enclosing or preceding function definition, or else to the
10259 beginning of the buffer. We can use `beginning-of-defun' to place
10260 point where we wish to start.
10261
10262 The `while' loop requires a counter to keep track of the words or
10263 symbols being counted. A `let' expression can be used to create a
10264 local variable for this purpose, and bind it to an initial value of
10265 zero.
10266
10267 The `end-of-defun' function works like `beginning-of-defun' except
10268 that it moves point to the end of the definition. `end-of-defun' can
10269 be used as part of an expression that determines the position of the
10270 end of the definition.
10271
10272 The set up for `count-words-in-defun' takes shape rapidly: first we
10273 move point to the beginning of the definition, then we create a local
10274 variable to hold the count, and finally, we record the position of
10275 the end of the definition so the `while' loop will know when to stop
10276 looping.
10277
10278 The code looks like this:
10279
10280 (beginning-of-defun)
10281 (let ((count 0)
10282 (end (save-excursion (end-of-defun) (point))))
10283
10284 The 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
10289 The second part of the `count-words-in-defun', after the set up, is
10290 the `while' loop.
10291
10292 The loop must contain an expression that jumps point forward word by
10293 word and symbol by symbol, and another expression that counts the
10294 jumps. The true-or-false-test for the `while' loop should test true
10295 so long as point should jump forward, and false when point is at the
10296 end of the definition. We have already redefined the regular
10297 expression 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
10304 The third part of the function definition returns the count of words
10305 and 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
10309 Put 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
10324 How to test this? The function is not interactive, but it is easy to
10325 put a wrapper around the function to make it interactive; we can use
10326 almost 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
10347 Let's re-use `C-c =' as a convenient keybinding:
10348
10349 (global-set-key "\C-c=" 'count-words-defun)
10350
10351 Now we can try out `count-words-defun': install both
10352 `count-words-in-defun' and `count-words-defun', and set the
10353 keybinding, 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
10360 Success! The definition has 10 words and symbols.
10361
10362 The next problem is to count the numbers of words and symbols in
10363 several definitions within a single file.
10364
10365 Count Several `defuns' Within a File
10366 ====================================
10367
10368 A file such as `simple.el' may have 80 or more function definitions
10369 within it. Our long term goal is to collect statistics on many
10370 files, but as a first step, our immediate goal is to collect
10371 statistics on one file.
10372
10373 The information will be a series of numbers, each number being the
10374 length of a function definition. We can store the numbers in a list.
10375
10376 We know that we will want to incorporate the information regarding one
10377 file with information about many other files; this means that the
10378 function for counting definition lengths within one file need only
10379 return the list of lengths. It need not and should not display any
10380 messages.
10381
10382 The word count commands contain one expression to jump point forward
10383 word by word and another expression to count the jumps. The function
10384 to return the lengths of definitions can be designed to work the same
10385 way, with one expression to jump point forward definition by
10386 definition and another expression to construct the lengths' list.
10387
10388 This statement of the problem makes it elementary to write the
10389 function definition. Clearly, we will start the count at the
10390 beginning of the file, so the first command will be `(goto-char
10391 (point-min))'. Next, we start the `while' loop; and the
10392 true-or-false test of the loop can be a regular expression search for
10393 the next function definition--so long as the search succeeds, point
10394 is moved forward and then the body of the loop is evaluated. The body
10395 needs an expression that constructs the lengths' list. `cons', the
10396 list construction command, can be used to create the list. That is
10397 almost all there is to it.
10398
10399 Here 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
10406 What we have left out is the mechanism for finding the file that
10407 contains the function definitions.
10408
10409 In previous examples, we either used this, the Info file, or we
10410 switched back and forth to some other buffer, such as the `*scratch*'
10411 buffer.
10412
10413 Finding a file is a new process that we have not yet discussed.
10414
10415 Find a File
10416 ===========
10417
10418 To find a file in Emacs, you use the `C-x C-f' (`find-file') command.
10419 This command is almost, but not quite right for the lengths problem.
10420
10421 Let's look at the source for `find-file' (you can use the `find-tag'
10422 command or `C-h f' (`describe-function') to find the source of a
10423 function):
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
10432 The definition possesses short but complete documentation and an
10433 interactive specification that prompts you for a file name when you
10434 use the command interactively. The body of the definition contains
10435 two functions, `find-file-noselect' and `switch-to-buffer'.
10436
10437 According to its documentation as shown by `C-h f' (the
10438 `describe-function' command), the `find-file-noselect' function reads
10439 the named file into a buffer and returns the buffer. However, the
10440 buffer is not selected. Emacs does not switch its attention (or
10441 yours if you are using `find-file-noselect') to the named buffer.
10442 That is what `switch-to-buffer' does: it switches the buffer to which
10443 Emacs attention is directed; and it switches the buffer displayed in
10444 the window to the new buffer. We have discussed buffer switching
10445 elsewhere. (*Note Switching Buffers::.)
10446
10447 In this histogram project, we do not need to display each file on the
10448 screen as the program determines the length of each definition within
10449 it. Instead of employing `switch-to-buffer', we can work with
10450 `set-buffer', which redirects the attention of the computer program
10451 to a different buffer but does not redisplay it on the screen. So
10452 instead of calling on `find-file' to do the job, we must write our
10453 own expression.
10454
10455 The task is easy: use `find-file-noselect' and `set-buffer'.
10456
10457 `lengths-list-file' in Detail
10458 =============================
10459
10460 The core of the `lengths-list-file' function is a `while' loop
10461 containing a function to move point forward `defun by defun' and a
10462 function to count the number of words and symbols in each defun.
10463 This core must be surrounded by functions that do various other tasks,
10464 including finding the file, and ensuring that point starts out at the
10465 beginning 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
10486 The function is passed one argument, the name of the file on which it
10487 will work. It has four lines of documentation, but no interactive
10488 specification. Since people worry that a computer is broken if they
10489 don't see anything going on, the first line of the body is a message.
10490
10491 The next line contains a `save-excursion' that returns Emacs'
10492 attention to the current buffer when the function completes. This is
10493 useful in case you embed this function in another function that
10494 presumes point is restored to the original buffer.
10495
10496 In the varlist of the `let' expression, Emacs finds the file and
10497 binds the local variable `buffer' to the buffer containing the file.
10498 At the same time, Emacs creates `lengths-list' as a local variable.
10499
10500 Next, Emacs switches its attention to the buffer.
10501
10502 In the following line, Emacs makes the buffer read-only. Ideally,
10503 this line is not necessary. None of the functions for counting words
10504 and symbols in a function definition should change the buffer.
10505 Besides, the buffer is not going to be saved, even if it were changed.
10506 This line is entirely the consequence of great, perhaps excessive,
10507 caution. The reason for the caution is that this function and those
10508 it calls work on the sources for Emacs and it is very inconvenient if
10509 they are inadvertently modified. It goes without saying that I did
10510 not realize a need for this line until an experiment went awry and
10511 started to modify my Emacs source files ...
10512
10513 Next comes a call to widen the buffer if it is narrowed. This
10514 function is usually not needed--Emacs creates a fresh buffer if none
10515 already exists; but if a buffer visiting the file already exists Emacs
10516 returns that one. In this case, the buffer may be narrowed and must
10517 be widened. If we wanted to be fully `user-friendly', we would
10518 arrange to save the restriction and the location of point, but we
10519 won't.
10520
10521 The `(goto-char (point-min))' expression moves point to the beginning
10522 of the buffer.
10523
10524 Then comes a `while' loop in which the `work' of the function is
10525 carried out. In the loop, Emacs determines the length of each
10526 definition and constructs a lengths' list containing the information.
10527
10528 Emacs kills the buffer after working through it. This is to save
10529 space inside of Emacs. My version of Emacs 19 contained over 300
10530 source files of interest; Emacs 21 contains over 800 source files.
10531 Another function will apply `lengths-list-file' to each of the files.
10532
10533 Finally, the last expression within the `let' expression is the
10534 `lengths-list' variable; its value is returned as the value of the
10535 whole function.
10536
10537 You can try this function by installing it in the usual fashion. Then
10538 place 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
10545 with GNU Emacs version 21.0.100. To change the expression, copy it to
10546 the `*scratch*' buffer and edit it.
10547
10548 (Also, to see the full length of the list, rather than a truncated
10549 version, 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
10554 the `lengths-list-file' expression.)
10555
10556 The lengths' list for `debug.el' takes less than a second to produce
10557 and 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'
10562 took 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
10567 earlier one; and my new machine is much faster than the old one.)
10568
10569 Note that the length of the last definition in the file is first in
10570 the list.
10571
10572 Count Words in `defuns' in Different Files
10573 ==========================================
10574
10575 In the previous section, we created a function that returns a list of
10576 the lengths of each definition in a file. Now, we want to define a
10577 function to return a master list of the lengths of the definitions in
10578 a list of files.
10579
10580 Working on each of a list of files is a repetitious act, so we can use
10581 either a `while' loop or recursion.
10582
10583 Determine the lengths of `defuns'
10584 ---------------------------------
10585
10586 The design using a `while' loop is routine. The argument passed the
10587 function is a list of files. As we saw earlier (*note Loop
10588 Example::), you can write a `while' loop so that the body of the loop
10589 is evaluated if such a list contains elements, but to exit the loop
10590 if the list is empty. For this design to work, the body of the loop
10591 must contain an expression that shortens the list each time the body
10592 is evaluated, so that eventually the list is empty. The usual
10593 technique is to set the value of the list to the value of the CDR of
10594 the list each time the body is evaluated.
10595
10596 The template looks like this:
10597
10598 (while TEST-WHETHER-LIST-IS-EMPTY
10599 BODY...
10600 SET-LIST-TO-CDR-OF-LIST)
10601
10602 Also, we remember that a `while' loop returns `nil' (the result of
10603 evaluating the true-or-false-test), not the result of any evaluation
10604 within its body. (The evaluations within the body of the loop are
10605 done for their side effects.) However, the expression that sets the
10606 lengths' list is part of the body--and that is the value that we want
10607 returned by the function as a whole. To do this, we enclose the
10608 `while' loop within a `let' expression, and arrange that the last
10609 element of the `let' expression contains the value of the lengths'
10610 list. (*Note Loop Example with an Incrementing Counter: Incrementing
10611 Example.)
10612
10613 These 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
10637 to the absolute, long, path name form of the directory in which the
10638 function is called.
10639
10640 Thus, if `expand-file-name' is called on `debug.el' when Emacs is
10641 visiting the `/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/'
10642 directory,
10643
10644 debug.el
10645
10646 becomes
10647
10648 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
10649
10650 The only other new element of this function definition is the as yet
10651 unstudied function `append', which merits a short section for itself.
10652
10653 The `append' Function
10654 ---------------------
10655
10656 The `append' function attaches one list to another. Thus,
10657
10658 (append '(1 2 3 4) '(5 6 7 8))
10659
10660 produces the list
10661
10662 (1 2 3 4 5 6 7 8)
10663
10664 This 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
10669 which constructs a new list in which the first argument to `cons'
10670 becomes the first element of the new list:
10671
10672 ((1 2 3 4) 5 6 7 8)
10673
10674 Recursively Count Words in Different Files
10675 ==========================================
10676
10677 Besides a `while' loop, you can work on each of a list of files with
10678 recursion. A recursive version of `lengths-list-many-files' is short
10679 and simple.
10680
10681 The recursive function has the usual parts: the `do-again-test', the
10682 `next-step-expression', and the recursive call. The `do-again-test'
10683 determines whether the function should call itself again, which it
10684 will do if the `list-of-files' contains any remaining elements; the
10685 `next-step-expression' resets the `list-of-files' to the CDR of
10686 itself, so eventually the list will be empty; and the recursive call
10687 calls itself on the shorter list. The complete function is shorter
10688 than 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
10699 In a sentence, the function returns the lengths' list for the first of
10700 the `list-of-files' appended to the result of calling itself on the
10701 rest of the `list-of-files'.
10702
10703 Here is a test of `recursive-lengths-list-many-files', along with the
10704 results of running `lengths-list-file' on each of the files
10705 individually.
10706
10707 Install `recursive-lengths-list-many-files' and `lengths-list-file',
10708 if necessary, and then evaluate the following expressions. You may
10709 need to change the files' pathnames; those here work when this Info
10710 file and the Emacs sources are located in their customary places. To
10711 change the expressions, copy them to the `*scratch*' buffer, edit
10712 them, and then evaluate them.
10713
10714 The results are shown after the `=>'. (These results are for files
10715 from Emacs Version 21.0.100; files from other versions of Emacs may
10716 produce 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
10735 The `recursive-lengths-list-many-files' function produces the output
10736 we want.
10737
10738 The next step is to prepare the data in the list for display in a
10739 graph.
10740
10741 Prepare the Data for Display in a Graph
10742 =======================================
10743
10744 The `recursive-lengths-list-many-files' function returns a list of
10745 numbers. Each number records the length of a function definition.
10746 What we need to do now is transform this data into a list of numbers
10747 suitable for generating a graph. The new list will tell how many
10748 functions definitions contain less than 10 words and symbols, how
10749 many contain between 10 and 19 words and symbols, how many contain
10750 between 20 and 29 words and symbols, and so on.
10751
10752 In brief, we need to go through the lengths' list produced by the
10753 `recursive-lengths-list-many-files' function and count the number of
10754 defuns within each range of lengths, and produce a list of those
10755 numbers.
10756
10757 Based on what we have done before, we can readily foresee that it
10758 should not be too hard to write a function that `CDRs' down the
10759 lengths' list, looks at each element, determines which length range it
10760 is in, and increments a counter for that range.
10761
10762 However, before beginning to write such a function, we should consider
10763 the advantages of sorting the lengths' list first, so the numbers are
10764 ordered from smallest to largest. First, sorting will make it easier
10765 to count the numbers in each range, since two adjacent numbers will
10766 either be in the same length range or in adjacent ranges. Second, by
10767 inspecting a sorted list, we can discover the highest and lowest
10768 number, and thereby determine the largest and smallest length range
10769 that we will need.
10770
10771 Sorting Lists
10772 -------------
10773
10774 Emacs contains a function to sort lists, called (as you might guess)
10775 `sort'. The `sort' function takes two arguments, the list to be
10776 sorted, and a predicate that determines whether the first of two list
10777 elements is "less" than the second.
10778
10779 As we saw earlier (*note Using the Wrong Type Object as an Argument:
10780 Wrong Type of Argument.), a predicate is a function that determines
10781 whether some property is true or false. The `sort' function will
10782 reorder a list according to whatever property the predicate uses;
10783 this means that `sort' can be used to sort non-numeric lists by
10784 non-numeric criteria--it can, for example, alphabetize a list.
10785
10786 The `<' function is used when sorting a numeric list. For example,
10787
10788 (sort '(4 8 21 17 33 7 21 7) '<)
10789
10790 produces 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
10795 symbols are not evaluated before being passed to `sort' as arguments.)
10796
10797 Sorting the list returned by the `recursive-lengths-list-many-files'
10798 function 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
10807 which 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
10812 quoted, since the expression must be evaluated so as to produce the
10813 list that is passed to `sort'.)
10814
10815 Making a List of Files
10816 ----------------------
10817
10818 The `recursive-lengths-list-many-files' function requires a list of
10819 files as its argument. For our test examples, we constructed such a
10820 list by hand; but the Emacs Lisp source directory is too large for us
10821 to do for that. Instead, we will write a function to do the job for
10822 us. In this function, we will use both a `while' loop and a
10823 recursive call.
10824
10825 We did not have to write a function like this for older versions of
10826 GNU Emacs, since they placed all the `.el' files in one directory.
10827 Instead, we were able to use the `directory-files' function, which
10828 lists the names of files that match a specified pattern within a
10829 single directory.
10830
10831 However, recent versions of Emacs place Emacs Lisp files in
10832 sub-directories of the top level `lisp' directory. This
10833 re-arrangement eases navigation. For example, all the mail related
10834 files are in a `lisp' sub-directory called `mail'. But at the same
10835 time, this arrangement forces us to create a file listing function
10836 that descends into the sub-directories.
10837
10838 We can create this function, called `files-in-below-directory', using
10839 familiar functions such as `car', `nthcdr', and `substring' in
10840 conjunction with an existing function called
10841 `directory-files-and-attributes'. This latter function not only
10842 lists all the filenames in a directory, including the names of
10843 sub-directories, but also their attributes.
10844
10845 To restate our goal: to create a function that will enable us to feed
10846 filenames to `recursive-lengths-list-many-files' as a list that looks
10847 like this (but with more elements):
10848
10849 ("../lisp/macros.el"
10850 "../lisp/mail/rmail.el"
10851 "../lisp/makesum.el")
10852
10853 The `directory-files-and-attributes' function returns a list of
10854 lists. Each of the lists within the main list consists of 13
10855 elements. The first element is a string that contains the name of the
10856 file - which, in GNU/Linux, may be a `directory file', that is to
10857 say, a file with the special attributes of a directory. The second
10858 element of the list is `t' for a directory, a string for symbolic
10859 link (the string is the name linked to), or `nil'.
10860
10861 For 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
10864 directory or a symbolic link.
10865
10866 This is how `directory-files-and-attributes' lists that file and its
10867 attributes:
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
10883 On the other hand, `mail/' is a directory within the `lisp/'
10884 directory. 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
10892 different attributes. Bear in mind that the `file-attributes'
10893 function does not list the filename, so its first element is
10894 `directory-files-and-attributes''s second element.)
10895
10896 We will want our new function, `files-in-below-directory', to list
10897 the `.el' files in the directory it is told to check, and in any
10898 directories below that directory.
10899
10900 This gives us a hint on how to construct `files-in-below-directory':
10901 within a directory, the function should add `.el' filenames to a
10902 list; and if, within a directory, the function comes upon a
10903 sub-directory, it should go into that sub-directory and repeat its
10904 actions.
10905
10906 However, we should note that every directory contains a name that
10907 refers to itself, called `.', ("dot") and a name that refers to its
10908 parent directory, called `..' ("double dot"). (In `/', the root
10909 directory, `..' refers to itself, since `/' has no parent.) Clearly,
10910 we do not want our `files-in-below-directory' function to enter those
10911 directories, since they always lead us, directly or indirectly, to
10912 the current directory.
10913
10914 Consequently, our `files-in-below-directory' function must do several
10915 tasks:
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
10928 Let'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,
10930 checking what needs to be done; and we will use a recursive call to
10931 repeat the actions on each sub-directory. The recursive pattern is
10932 `accumulate' (*note Recursive Pattern: _accumulate_: Accumulate.),
10933 using `append' as the combiner.
10934
10935 Here 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
10976 The `files-in-below-directory' `directory-files' function takes one
10977 argument, the name of a directory.
10978
10979 Thus, on my system,
10980
10981 (length
10982 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
10983
10984 tells 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
10988 order. An expression to sort the list in alphabetical order looks
10989 like this:
10990
10991 (sort
10992 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
10993 'string-lessp)
10994
10995 Counting function definitions
10996 -----------------------------
10997
10998 Our immediate goal is to generate a list that tells us how many
10999 function definitions contain fewer than 10 words and symbols, how many
11000 contain between 10 and 19 words and symbols, how many contain between
11001 20 and 29 words and symbols, and so on.
11002
11003 With a sorted list of numbers, this is easy: count how many elements
11004 of the list are smaller than 10, then, after moving past the numbers
11005 just counted, count how many are smaller than 20, then, after moving
11006 past the numbers just counted, count how many are smaller than 30, and
11007 so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
11008 larger than the top of that range. We can call the list of such
11009 numbers the `top-of-ranges' list.
11010
11011 If we wished, we could generate this list automatically, but it is
11012 simpler 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
11023 To change the ranges, we edit this list.
11024
11025 Next, we need to write the function that creates the list of the
11026 number of definitions within each range. Clearly, this function must
11027 take the `sorted-lengths' and the `top-of-ranges' lists as arguments.
11028
11029 The `defuns-per-range' function must do two things again and again:
11030 it must count the number of definitions within a range specified by
11031 the current top-of-range value; and it must shift to the next higher
11032 value in the `top-of-ranges' list after counting the number of
11033 definitions in the current range. Since each of these actions is
11034 repetitive, we can use `while' loops for the job. One loop counts
11035 the number of definitions in the range defined by the current
11036 top-of-range value, and the other loop selects each of the
11037 top-of-range values in turn.
11038
11039 Several entries of the `sorted-lengths' list are counted for each
11040 range; this means that the loop for the `sorted-lengths' list will be
11041 inside the loop for the `top-of-ranges' list, like a small gear
11042 inside a big gear.
11043
11044 The inner loop counts the number of definitions within the range. It
11045 is a simple counting loop of the type we have seen before. (*Note A
11046 loop with an incrementing counter: Incrementing Loop.) The
11047 true-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
11049 the range. If it is, the function increments the counter and tests
11050 the next value from the `sorted-lengths' list.
11051
11052 The 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
11058 The outer loop must start with the lowest value of the
11059 `top-of-ranges' list, and then be set to each of the succeeding
11060 higher 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
11066 Put 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
11078 In addition, in each circuit of the outer loop, Emacs should record
11079 the number of definitions within that range (the value of
11080 `number-within-range') in a list. We can use `cons' for this
11081 purpose. (*Note `cons': cons.)
11082
11083 The `cons' function works fine, except that the list it constructs
11084 will contain the number of definitions for the highest range at its
11085 beginning and the number of definitions for the lowest range at its
11086 end. This is because `cons' attaches new elements of the list to the
11087 beginning of the list, and since the two loops are working their way
11088 through the lengths' list from the lower end first, the
11089 `defuns-per-range-list' will end up largest number first. But we
11090 will want to print our graph with smallest values first and the
11091 larger later. The solution is to reverse the order of the
11092 `defuns-per-range-list'. We can do this using the `nreverse'
11093 function, which reverses the order of a list.
11094
11095 For example,
11096
11097 (nreverse '(1 2 3 4))
11098
11099 produces:
11100
11101 (4 3 2 1)
11102
11103 Note that the `nreverse' function is "destructive"--that is, it
11104 changes the list to which it is applied; this contrasts with the
11105 `car' and `cdr' functions, which are non-destructive. In this case,
11106 we do not want the original `defuns-per-range-list', so it does not
11107 matter that it is destroyed. (The `reverse' function provides a
11108 reversed copy of a list, leaving the original list as is.)
11109
11110 Put 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
11153 The function is straightforward except for one subtle feature. The
11154 true-or-false test of the inner loop looks like this:
11155
11156 (and (car sorted-lengths)
11157 (< (car sorted-lengths) top-of-range))
11158
11159 instead of like this:
11160
11161 (< (car sorted-lengths) top-of-range)
11162
11163 The 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
11166 The simple version of the test works fine unless the `sorted-lengths'
11167 list has a `nil' value. In that case, the `(car sorted-lengths)'
11168 expression function returns `nil'. The `<' function cannot compare a
11169 number to `nil', which is an empty list, so Emacs signals an error and
11170 stops the function from attempting to continue to execute.
11171
11172 The `sorted-lengths' list always becomes `nil' when the counter
11173 reaches 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
11175 fail.
11176
11177 We solve the problem by using the `(car sorted-lengths)' expression
11178 in conjunction with the `and' expression. The `(car sorted-lengths)'
11179 expression returns a non-`nil' value so long as the list has at least
11180 one number within it, but returns `nil' if the list is empty. The
11181 `and' expression first evaluates the `(car sorted-lengths)'
11182 expression, and if it is `nil', returns false _without_ evaluating the
11183 `<' expression. But if the `(car sorted-lengths)' expression returns
11184 a non-`nil' value, the `and' expression evaluates the `<' expression,
11185 and returns that value as the value of the `and' expression.
11186
11187 This way, we avoid an error. *Note forward-paragraph::, for more
11188 information about `and'.
11189
11190 Here is a short test of the `defuns-per-range' function. First,
11191 evaluate the expression that binds (a shortened) `top-of-ranges' list
11192 to the list of values, then evaluate the expression for binding the
11193 `sorted-lengths' list, and then evaluate the `defuns-per-range'
11194 function.
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
11206 The list returned looks like this:
11207
11208 (2 2 2 0 0 1 0 2 0 0 4)
11209
11210 Indeed, there are two elements of the `sorted-lengths' list smaller
11211 than 110, two elements between 110 and 119, two elements between 120
11212 and 129, and so on. There are four elements with a value of 200 or
11213 larger.
11214
11215 Readying a Graph
11216 ****************
11217
11218 Our goal is to construct a graph showing the numbers of function
11219 definitions of various lengths in the Emacs lisp sources.
11220
11221 As a practical matter, if you were creating a graph, you would
11222 probably use a program such as `gnuplot' to do the job. (`gnuplot'
11223 is nicely integrated into GNU Emacs.) In this case, however, we
11224 create one from scratch, and in the process we will re-acquaint
11225 ourselves with some of what we learned before and learn more.
11226
11227 In this chapter, we will first write a simple graph printing function.
11228 This first definition will be a "prototype", a rapidly written
11229 function that enables us to reconnoiter this unknown graph-making
11230 territory. We will discover dragons, or find that they are myth.
11231 After scouting the terrain, we will feel more confident and enhance
11232 the function to label the axes automatically.
11233
11234 Printing the Columns of a Graph
11235 ===============================
11236
11237 Since Emacs is designed to be flexible and work with all kinds of
11238 terminals, including character-only terminals, the graph will need to
11239 be made from one of the `typewriter' symbols. An asterisk will do; as
11240 we enhance the graph-printing function, we can make the choice of
11241 symbol a user option.
11242
11243 We can call this function `graph-body-print'; it will take a
11244 `numbers-list' as its only argument. At this stage, we will not
11245 label the graph, but only print its body.
11246
11247 The `graph-body-print' function inserts a vertical column of
11248 asterisks for each element in the `numbers-list'. The height of each
11249 line is determined by the value of that element of the `numbers-list'.
11250
11251 Inserting columns is a repetitive act; that means that this function
11252 can be written either with a `while' loop or recursively.
11253
11254 Our first challenge is to discover how to print a column of asterisks.
11255 Usually, in Emacs, we print characters onto a screen horizontally,
11256 line by line, by typing. We have two routes we can follow: write our
11257 own column-insertion function or discover whether one exists in Emacs.
11258
11259 To see whether there is one in Emacs, we can use the `M-x apropos'
11260 command. This command is like the `C-h a' (command-apropos) command,
11261 except that the latter finds only those functions that are commands.
11262 The `M-x apropos' command lists all symbols that match a regular
11263 expression, including functions that are not interactive.
11264
11265 What we want to look for is some command that prints or inserts
11266 columns. Very likely, the name of the function will contain either
11267 the word `print' or the word `insert' or the word `column'.
11268 Therefore, we can simply type `M-x apropos RET print\|insert\|column
11269 RET' and look at the result. On my system, this command takes quite
11270 some time, and then produces a list of 79 functions and variables.
11271 Scanning down the list, the only function that looks as if it might
11272 do the job is `insert-rectangle'.
11273
11274 Indeed, 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
11282 We can run a quick test, to make sure it does what we expect of it.
11283
11284 Here is the result of placing the cursor after the `insert-rectangle'
11285 expression and typing `C-u C-x C-e' (`eval-last-sexp'). The function
11286 inserts the strings `"first"', `"second"', and `"third"' at and below
11287 point. Also the function returns `nil'.
11288
11289 (insert-rectangle '("first" "second" "third"))first
11290 second
11291 third
11292 nil
11293
11294 Of course, we won't be inserting the text of the `insert-rectangle'
11295 expression itself into the buffer in which we are making the graph,
11296 but will call the function from our program. We shall, however, have
11297 to make sure that point is in the buffer at the place where the
11298 `insert-rectangle' function will insert its column of strings.
11299
11300 If you are reading this in Info, you can see how this works by
11301 switching to another buffer, such as the `*scratch*' buffer, placing
11302 point somewhere in the buffer, typing `M-:', typing the
11303 `insert-rectangle' expression into the minibuffer at the prompt, and
11304 then typing <RET>. This causes Emacs to evaluate the expression in
11305 the minibuffer, but to use as the value of point the position of
11306 point in the `*scratch*' buffer. (`M-:' is the keybinding for
11307 `eval-expression'.)
11308
11309 We find when we do this that point ends up at the end of the last
11310 inserted line--that is to say, this function moves point as a
11311 side-effect. If we were to repeat the command, with point at this
11312 position, the next insertion would be below and to the right of the
11313 previous insertion. We don't want this! If we are going to make a
11314 bar graph, the columns need to be beside each other.
11315
11316 So we discover that each cycle of the column-inserting `while' loop
11317 must reposition point to the place we want it, and that place will be
11318 at the top, not the bottom, of the column. Moreover, we remember
11319 that when we print a graph, we do not expect all the columns to be
11320 the same height. This means that the top of each column may be at a
11321 different height from the previous one. We cannot simply reposition
11322 point to the same line each time, but moved over to the right--or
11323 perhaps we can...
11324
11325 We are planning to make the columns of the bar graph out of asterisks.
11326 The number of asterisks in the column is the number specified by the
11327 current element of the `numbers-list'. We need to construct a list
11328 of asterisks of the right length for each call to `insert-rectangle'.
11329 If this list consists solely of the requisite number of asterisks,
11330 then we will have position point the right number of lines above the
11331 base for the graph to print correctly. This could be difficult.
11332
11333 Alternatively, if we can figure out some way to pass
11334 `insert-rectangle' a list of the same length each time, then we can
11335 place point on the same line each time, but move it over one column
11336 to the right for each new column. If we do this, however, some of
11337 the entries in the list passed to `insert-rectangle' must be blanks
11338 rather than asterisks. For example, if the maximum height of the
11339 graph is 5, but the height of the column is 3, then
11340 `insert-rectangle' requires an argument that looks like this:
11341
11342 (" " " " "*" "*" "*")
11343
11344 This last proposal is not so difficult, so long as we can determine
11345 the column height. There are two ways for us to specify the column
11346 height: we can arbitrarily state what it will be, which would work
11347 fine for graphs of that height; or we can search through the list of
11348 numbers and use the maximum height of the list as the maximum height
11349 of the graph. If the latter operation were difficult, then the former
11350 procedure would be easiest, but there is a function built into Emacs
11351 that determines the maximum of its arguments. We can use that
11352 function. The function is called `max' and it returns the largest of
11353 all its arguments, which must be numbers. Thus, for example,
11354
11355 (max 3 4 6 5 7 3)
11356
11357 returns 7. (A corresponding function called `min' returns the
11358 smallest of all its arguments.)
11359
11360 However, we cannot simply call `max' on the `numbers-list'; the `max'
11361 function expects numbers as its argument, not a list of numbers.
11362 Thus, the following expression,
11363
11364 (max '(3 4 6 5 7 3))
11365
11366 produces the following error message;
11367
11368 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
11369
11370 We need a function that passes a list of arguments to a function.
11371 This function is `apply'. This function `applies' its first argument
11372 (a function) to its remaining arguments, the last of which may be a
11373 list.
11374
11375 For example,
11376
11377 (apply 'max 3 4 7 3 '(4 8 5))
11378
11379 returns 8.
11380
11381 (Incidentally, I don't know how you would learn of this function
11382 without a book such as this. It is possible to discover other
11383 functions, like `search-forward' or `insert-rectangle', by guessing
11384 at a part of their names and then using `apropos'. Even though its
11385 base in metaphor is clear--`apply' its first argument to the rest--I
11386 doubt 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
11388 function was first named by someone who had to invent it.)
11389
11390 The second and subsequent arguments to `apply' are optional, so we
11391 can use `apply' to call a function and pass the elements of a list to
11392 it, like this, which also returns 8:
11393
11394 (apply 'max '(4 8 5))
11395
11396 This latter way is how we will use `apply'. The
11397 `recursive-lengths-list-many-files' function returns a numbers' list
11398 to which we can apply `max' (we could also apply `max' to the sorted
11399 numbers' list; it does not matter whether the list is sorted or not.)
11400
11401 Hence, the operation for finding the maximum height of the graph is
11402 this:
11403
11404 (setq max-graph-height (apply 'max numbers-list))
11405
11406 Now we can return to the question of how to create a list of strings
11407 for a column of the graph. Told the maximum height of the graph and
11408 the number of asterisks that should appear in the column, the
11409 function should return a list of strings for the `insert-rectangle'
11410 command to insert.
11411
11412 Each column is made up of asterisks or blanks. Since the function is
11413 passed the value of the height of the column and the number of
11414 asterisks in the column, the number of blanks can be found by
11415 subtracting the number of asterisks from the height of the column.
11416 Given the number of blanks and the number of asterisks, two `while'
11417 loops 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
11440 If you install this function and then evaluate the following
11441 expression you will see that it returns the list as desired:
11442
11443 (column-of-graph 5 3)
11444
11445 returns
11446
11447 (" " " " "*" "*" "*")
11448
11449 As written, `column-of-graph' contains a major flaw: the symbols used
11450 for 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,
11452 but you, or another user, may wish to use other symbols. For example,
11453 in testing the graph function, you many want to use a period in place
11454 of the space, to make sure the point is being repositioned properly
11455 each time the `insert-rectangle' function is called; or you might
11456 want to substitute a `+' sign or other symbol for the asterisk. You
11457 might even want to make a graph-column that is more than one display
11458 column wide. The program should be more flexible. The way to do
11459 that is to replace the blank and the asterisk with two variables that
11460 we can call `graph-blank' and `graph-symbol' and define those
11461 variables separately.
11462
11463 Also, the documentation is not well written. These considerations
11464 lead 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
11475 with `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
11503 If we wished, we could rewrite `column-of-graph' a third time to
11504 provide optionally for a line graph as well as for a bar graph. This
11505 would not be hard to do. One way to think of a line graph is that it
11506 is no more than a bar graph in which the part of each bar that is
11507 below the top is blank. To construct a column for a line graph, the
11508 function first constructs a list of blanks that is one shorter than
11509 the value, then it uses `cons' to attach a graph symbol to the list;
11510 then it uses `cons' again to attach the `top blanks' to the list.
11511
11512 It is easy to see how to write such a function, but since we don't
11513 need it, we will not do it. But the job could be done, and if it were
11514 done, it would be done with `column-of-graph'. Even more important,
11515 it is worth noting that few changes would have to be made anywhere
11516 else. The enhancement, if we ever wish to make it, is simple.
11517
11518 Now, finally, we come to our first actual graph printing function.
11519 This prints the body of a graph, not the labels for the vertical and
11520 horizontal axes, so we can call this `graph-body-print'.
11521
11522 The `graph-body-print' Function
11523 ===============================
11524
11525 After our preparation in the preceding section, the
11526 `graph-body-print' function is straightforward. The function will
11527 print column after column of asterisks and blanks, using the elements
11528 of a numbers' list to specify the number of asterisks in each column.
11529 This is a repetitive act, which means we can use a decrementing
11530 `while' loop or recursive function for the job. In this section, we
11531 will write the definition using a `while' loop.
11532
11533 The `column-of-graph' function requires the height of the graph as an
11534 argument, so we should determine and record that as a local variable.
11535
11536 This leads us to the following template for the `while' loop version
11537 of 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
11548 We need to fill in the slots of the template.
11549
11550 Clearly, we can use the `(apply 'max numbers-list)' expression to
11551 determine the height of the graph.
11552
11553 The `while' loop will cycle through the `numbers-list' one element at
11554 a time. As it is shortened by the `(setq numbers-list (cdr
11555 numbers-list))' expression, the CAR of each instance of the list is
11556 the value of the argument for `column-of-graph'.
11557
11558 At each cycle of the `while' loop, the `insert-rectangle' function
11559 inserts the list returned by `column-of-graph'. Since the
11560 `insert-rectangle' function moves point to the lower right of the
11561 inserted rectangle, we need to save the location of point at the time
11562 the rectangle is inserted, move back to that position after the
11563 rectangle is inserted, and then move horizontally to the next place
11564 from which `insert-rectangle' is called.
11565
11566 If the inserted columns are one character wide, as they will be if
11567 single blanks and asterisks are used, the repositioning command is
11568 simply `(forward-char 1)'; however, the width of a column may be
11569 greater than one. This means that the repositioning command should be
11570 written `(forward-char symbol-width)'. The `symbol-width' itself is
11571 the length of a `graph-blank' and can be found using the expression
11572 `(length graph-blank)'. The best place to bind the `symbol-width'
11573 variable to the value of the width of graph column is in the varlist
11574 of the `let' expression.
11575
11576 These 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
11600 The one unexpected expression in this function is the `(sit-for 0)'
11601 expression in the `while' loop. This expression makes the graph
11602 printing operation more interesting to watch than it would be
11603 otherwise. The expression causes Emacs to `sit' or do nothing for a
11604 zero length of time and then redraw the screen. Placed here, it
11605 causes Emacs to redraw the screen column by column. Without it,
11606 Emacs would not redraw the screen until the function exits.
11607
11608 We 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
11627 Emacs will print a graph like this:
11628
11629 *
11630 * **
11631 * ****
11632 *** ****
11633 ********* *
11634 ************
11635 *************
11636
11637 The `recursive-graph-body-print' Function
11638 =========================================
11639
11640 The `graph-body-print' function may also be written recursively. The
11641 recursive solution is divided into two parts: an outside `wrapper'
11642 that uses a `let' expression to determine the values of several
11643 variables that need only be found once, such as the maximum height of
11644 the graph, and an inside function that is called recursively to print
11645 the graph.
11646
11647 The `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
11660 The recursive function is a little more difficult. It has four parts:
11661 the `do-again-test', the printing code, the recursive call, and the
11662 `next-step-expression'. The `do-again-test' is an `if' expression
11663 that determines whether the `numbers-list' contains any remaining
11664 elements; if it does, the function prints one column of the graph
11665 using the printing code and calls itself again. The function calls
11666 itself again according to the value produced by the
11667 `next-step-expression' which causes the call to act on a shorter
11668 version 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
11686 After 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
11690 Here is what `recursive-graph-body-print' produces:
11691
11692 *
11693 ** *
11694 **** *
11695 **** ***
11696 * *********
11697 ************
11698 *************
11699
11700 Either of these two functions, `graph-body-print' or
11701 `recursive-graph-body-print', create the body of a graph.
11702
11703 Need for Printed Axes
11704 =====================
11705
11706 A graph needs printed axes, so you can orient yourself. For a do-once
11707 project, it may be reasonable to draw the axes by hand using Emacs'
11708 Picture mode; but a graph drawing function may be used more than once.
11709
11710 For this reason, I have written enhancements to the basic
11711 `print-graph-body' function that automatically print labels for the
11712 horizontal and vertical axes. Since the label printing functions do
11713 not contain much new material, I have placed their description in an
11714 appendix. *Note A Graph with Labelled Axes: Full Graph.
11715
11716 Exercise
11717 ========
11718
11719 Write a line graph version of the graph printing functions.
11720
11721 Your `.emacs' File
11722 ******************
11723
11724 "You don't have to like Emacs to like it" - this seemingly
11725 paradoxical statement is the secret of GNU Emacs. The plain, `out of
11726 the box' Emacs is a generic tool. Most people who use it, customize
11727 it to suit themselves.
11728
11729 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
11730 expressions in Emacs Lisp you can change or extend Emacs.
11731
11732 Emacs' Default Configuration
11733 ============================
11734
11735 There are those who appreciate Emacs' default configuration. After
11736 all, Emacs starts you in C mode when you edit a C file, starts you in
11737 Fortran mode when you edit a Fortran file, and starts you in
11738 Fundamental mode when you edit an unadorned file. This all makes
11739 sense, if you do not know who is going to use Emacs. Who knows what a
11740 person hopes to do with an unadorned file? Fundamental mode is the
11741 right default for such a file, just as C mode is the right default for
11742 editing C code. But when you do know who is going to use Emacs--you,
11743 yourself--then it makes sense to customize Emacs.
11744
11745 For example, I seldom want Fundamental mode when I edit an otherwise
11746 undistinguished file; I want Text mode. This is why I customize
11747 Emacs: so it suits me.
11748
11749 You can customize and extend Emacs by writing or adapting a
11750 `~/.emacs' file. This is your personal initialization file; its
11751 contents, written in Emacs Lisp, tell Emacs what to do.(1)
11752
11753 A `~/.emacs' file contains Emacs Lisp code. You can write this code
11754 yourself; or you can use Emacs' `customize' feature to write the code
11755 for you. You can combine your own expressions and auto-written
11756 Customize expressions in your `.emacs' file.
11757
11758 (I myself prefer to write my own expressions, except for those,
11759 particularly fonts, that I find easier to manipulate using the
11760 `customize' command. I combine the two methods.)
11761
11762 Most of this chapter is about writing expressions yourself. It
11763 describes a simple `.emacs' file; for more information, see *Note The
11764 Init File: (emacs)Init File, and *Note The Init File: (elisp)Init
11765 File.
11766
11767 ---------- Footnotes ----------
11768
11769 (1) You may also add `.el' to `~/.emacs' and call it a `~/.emacs.el'
11770 file. In the past, you were forbidden to type the extra keystrokes
11771 that the name `~/.emacs.el' requires, but now you may. The new
11772 format is consistent with the Emacs Lisp file naming conventions; the
11773 old format saves typing.
11774
11775 Site-wide Initialization Files
11776 ==============================
11777
11778 In addition to your personal initialization file, Emacs automatically
11779 loads various site-wide initialization files, if they exist. These
11780 have the same form as your `.emacs' file, but are loaded by everyone.
11781
11782 Two site-wide initialization files, `site-load.el' and
11783 `site-init.el', are loaded into Emacs and then `dumped' if a `dumped'
11784 version of Emacs is created, as is most common. (Dumped copies of
11785 Emacs load more quickly. However, once a file is loaded and dumped,
11786 a change to it does not lead to a change in Emacs unless you load it
11787 yourself or re-dump Emacs. *Note Building Emacs: (elisp)Building
11788 Emacs, and the `INSTALL' file.)
11789
11790 Three other site-wide initialization files are loaded automatically
11791 each time you start Emacs, if they exist. These are `site-start.el',
11792 which is loaded _before_ your `.emacs' file, and `default.el', and
11793 the terminal type file, which are both loaded _after_ your `.emacs'
11794 file.
11795
11796 Settings and definitions in your `.emacs' file will overwrite
11797 conflicting settings and definitions in a `site-start.el' file, if it
11798 exists; but the settings and definitions in a `default.el' or
11799 terminal type file will overwrite those in your `.emacs' file. (You
11800 can prevent interference from a terminal type file by setting
11801 `term-file-prefix' to `nil'. *Note A Simple Extension: Simple
11802 Extension.)
11803
11804 The `INSTALL' file that comes in the distribution contains
11805 descriptions of the `site-init.el' and `site-load.el' files.
11806
11807 The `loadup.el', `startup.el', and `loaddefs.el' files control
11808 loading. These files are in the `lisp' directory of the Emacs
11809 distribution and are worth perusing.
11810
11811 The `loaddefs.el' file contains a good many suggestions as to what to
11812 put into your own `.emacs' file, or into a site-wide initialization
11813 file.
11814
11815 Specifying Variables using `defcustom'
11816 ======================================
11817
11818 You can specify variables using `defcustom' so that you and others
11819 can then use Emacs' `customize' feature to set their values. (You
11820 cannot use `customize' to write function definitions; but you can
11821 write `defuns' in your `.emacs' file. Indeed, you can write any Lisp
11822 expression in your `.emacs' file.)
11823
11824 The `customize' feature depends on the `defcustom' special form.
11825 Although you can use `defvar' or `setq' for variables that users set,
11826 the `defcustom' special form is designed for the job.
11827
11828 You can use your knowledge of `defvar' for writing the first three
11829 arguments for `defcustom'. The first argument to `defcustom' is the
11830 name of the variable. The second argument is the variable's initial
11831 value, if any; and this value is set only if the value has not
11832 already been set. The third argument is the documentation.
11833
11834 The fourth and subsequent arguments to `defcustom' specify types and
11835 options; these are not featured in `defvar'. (These arguments are
11836 optional.)
11837
11838 Each of these arguments consists of a keyword followed by a value.
11839 Each keyword starts with the character `:'.
11840
11841 For example, the customizable user option variable `text-mode-hook'
11842 looks 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
11850 The name of the variable is `text-mode-hook'; it has no default
11851 value; and its documentation string tells you what it does.
11852
11853 The `:type' keyword tells Emacs what kind of data `text-mode-hook'
11854 should be set to and how to display the value in a Customization
11855 buffer.
11856
11857 The `:options' keyword specifies a suggested list of values for the
11858 variable. Currently, you can use `:options' only for a hook. The
11859 list is only a suggestion; it is not exclusive; a person who sets the
11860 variable may set it to other values; the list shown following the
11861 `:options' keyword is intended to offer convenient choices to a user.
11862
11863 Finally, the `:group' keyword tells the Emacs Customization command
11864 in which group the variable is located. This tells where to find it.
11865
11866 For more information, see *Note Writing Customization Definitions:
11867 (elisp)Customization.
11868
11869 Consider `text-mode-hook' as an example.
11870
11871 There are two ways to customize this variable. You can use the
11872 customization command or write the appropriate expressions yourself.
11873
11874 Using the customization command, you can type:
11875
11876 M-x customize
11877
11878 and find that the group for editing files of data is called `data'.
11879 Enter that group. Text Mode Hook is the first member. You can click
11880 on its various options to set the values. After you click on the
11881 button to
11882
11883 Save for Future Sessions
11884
11885 Emacs will write an expression into your `.emacs' file. It will look
11886 like 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
11897 In spite of the warning, you certainly may edit, cut, and paste the
11898 expression! I do all time. The purpose of the warning is to scare
11899 those who do not know what they are doing, so they do not
11900 inadvertently generate an error.
11901
11902 The `custom-set-variables' works somewhat differently than a `setq'.
11903 While I have never learned the differences, I do modify the
11904 `custom-set-variables' expressions in my `.emacs' file by hand: I
11905 make the changes in what appears to me to be a reasonable manner and
11906 have not had any problems. Others prefer to use the Customization
11907 command and let Emacs do the work for them.
11908
11909 Another `custom-set-...' function is `custom-set-faces'. This
11910 function sets the various font faces. Over time, I have set a
11911 considerable number of faces. Some of the time, I re-set them using
11912 `customize'; other times, I simply edit the `custom-set-faces'
11913 expression in my `.emacs' file itself.
11914
11915 The second way to customize your `text-mode-hook' is to set it
11916 yourself in your `.emacs' file using code that has nothing to do with
11917 the `custom-set-...' functions.
11918
11919 When you do this, and later use `customize', you will see a message
11920 that says
11921
11922 this option has been changed outside the customize buffer.
11923
11924 This message is only a warning. If you click on the button to
11925
11926 Save for Future Sessions
11927
11928 Emacs will write a `custom-set-...' expression near the end of your
11929 `.emacs' file that will be evaluated after your hand-written
11930 expression. It will, therefore, overrule your hand-written
11931 expression. No harm will be done. When you do this, however, be
11932 careful to remember which expression is active; if you forget, you
11933 may confuse yourself.
11934
11935 So long as you remember where the values are set, you will have no
11936 trouble. In any event, the values are always set in your
11937 initialization file, which is usually called `.emacs'.
11938
11939 I myself use `customize' for hardly anything. Mostly, I write
11940 expressions myself.
11941
11942 Beginning a `.emacs' File
11943 =========================
11944
11945 When you start Emacs, it loads your `.emacs' file unless you tell it
11946 not to by specifying `-q' on the command line. (The `emacs -q'
11947 command gives you a plain, out-of-the-box Emacs.)
11948
11949 A `.emacs' file contains Lisp expressions. Often, these are no more
11950 than expressions to set values; sometimes they are function
11951 definitions.
11952
11953 *Note The Init File `~/.emacs': (emacs)Init File, for a short
11954 description of initialization files.
11955
11956 This chapter goes over some of the same ground, but is a walk among
11957 extracts from a complete, long-used `.emacs' file--my own.
11958
11959 The first part of the file consists of comments: reminders to myself.
11960 By now, of course, I remember these things, but when I started, I did
11961 not.
11962
11963 ;;;; Bob's .emacs file
11964 ; Robert J. Chassell
11965 ; 26 September 1985
11966
11967 Look at that date! I started this file a long time ago. I have been
11968 adding 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
11975 This describes the usual conventions for comments in Emacs Lisp.
11976 Everything on a line that follows a semicolon is a comment. Two,
11977 three, and four semicolons are used as section and subsection
11978 markers. (*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
11987 Just 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
11995 all you need to know.
11996
11997 Of course, you don't need to include comments like these in your
11998 `.emacs' file. I included them in mine because I kept forgetting
11999 about Mode help or the conventions for comments--but I was able to
12000 remember to look here to remind myself.
12001
12002 Text and Auto Fill Mode
12003 =======================
12004
12005 Now 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
12016 Here is the first part of this `.emacs' file that does something
12017 besides remind a forgetful human!
12018
12019 The first of the two lines in parentheses tells Emacs to turn on Text
12020 mode when you find a file, _unless_ that file should go into some
12021 other mode, such as C mode.
12022
12023 When Emacs reads a file, it looks at the extension to the file name,
12024 if any. (The extension is the part that comes after a `.'.) If the
12025 file ends with a `.c' or `.h' extension then Emacs turns on C mode.
12026 Also, Emacs looks at first nonblank line of the file; if the line
12027 says `-*- C -*-', Emacs turns on C mode. Emacs possesses a list of
12028 extensions and specifications that it uses automatically. In
12029 addition, Emacs looks near the last page for a per-buffer, "local
12030 variables 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
12036 Now, back to the `.emacs' file.
12037
12038 Here is the line again; how does it work?
12039
12040 (setq default-major-mode 'text-mode)
12041
12042 This line is a short, but complete Emacs Lisp expression.
12043
12044 We are already familiar with `setq'. It sets the following variable,
12045 `default-major-mode', to the subsequent value, which is `text-mode'.
12046 The single quote mark before `text-mode' tells Emacs to deal directly
12047 with 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
12049 how `setq' works. The main point is that there is no difference
12050 between the procedure you use to set a value in your `.emacs' file
12051 and the procedure you use anywhere else in Emacs.
12052
12053 Here 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
12058 In these two lines, the `add-hook' command first adds
12059 `text-mode-hook-identify' to the variable called `text-mode-hook' and
12060 then adds `turn-on-auto-fill' to the variable.
12061
12062 `turn-on-auto-fill' is the name of a program, that, you guessed it!,
12063 turns on Auto Fill mode. `text-mode-hook-identify' is a function
12064 that tells `toggle-text-mode-auto-fill' which buffers are in Text
12065 mode.
12066
12067 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
12068 onto Text mode. So every time Emacs turns on Text mode, Emacs also
12069 turns on Auto Fill mode.
12070
12071 In brief, the first line causes Emacs to enter Text mode when you edit
12072 a file, unless the file name extension, first non-blank line, or local
12073 variables tell Emacs otherwise.
12074
12075 Text mode among other actions, sets the syntax table to work
12076 conveniently for writers. In Text mode, Emacs considers an apostrophe
12077 as part of a word like a letter; but Emacs does not consider a period
12078 or a space as part of a word. Thus, `M-f' moves you over `it's'. On
12079 the other hand, in C mode, `M-f' stops just after the `t' of `it's'.
12080
12081 The second and third lines causes Emacs to turn on Auto Fill mode when
12082 it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
12083 a line that is too wide and brings the excessively wide part of the
12084 line down to the next line. Emacs breaks lines between words, not
12085 within them.
12086
12087 When Auto Fill mode is turned off, lines continue to the right as you
12088 type them. Depending on how you set the value of `truncate-lines',
12089 the words you type either disappear off the right side of the screen,
12090 or else are shown, in a rather ugly and unreadable manner, as a
12091 continuation line on the screen.
12092
12093 In addition, in this part of my `.emacs' file, I tell the Emacs fill
12094 commands to insert two spaces after a colon:
12095
12096 (setq colon-double-space t)
12097
12098 Mail Aliases
12099 ============
12100
12101 Here is a `setq' that `turns on' mail aliases, along with more
12102 reminders.
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
12111 This `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
12113 aliases."
12114
12115 Mail aliases are convenient short names for long email addresses or
12116 for lists of email addresses. The file where you keep your `aliases'
12117 is `~/.mailrc'. You write an alias like this:
12118
12119 alias geo george@foobar.wiz.edu
12120
12121 When you write a message to George, address it to `geo'; the mailer
12122 will automatically expand `geo' to the full address.
12123
12124 Indent Tabs Mode
12125 ================
12126
12127 By default, Emacs inserts tabs in place of multiple spaces when it
12128 formats a region. (For example, you might indent many lines of text
12129 all at once with the `indent-region' command.) Tabs look fine on a
12130 terminal or with ordinary printing, but they produce badly indented
12131 output when you use TeX or Texinfo since TeX ignores tabs.
12132
12133 The following turns off Indent Tabs mode:
12134
12135 ;;; Prevent Extraneous Tabs
12136 (setq-default indent-tabs-mode nil)
12137
12138 Note that this line uses `setq-default' rather than the `setq'
12139 command that we have seen before. The `setq-default' command sets
12140 values only in buffers that do not have their own local values for
12141 the variable.
12142
12143 *Note Tabs vs. Spaces: (emacs)Just Spaces.
12144
12145 *Note Local Variables in Files: (emacs)File Variables.
12146
12147 Some Keybindings
12148 ================
12149
12150 Now 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
12156 current window with text in the next window. It makes the comparison
12157 by starting at point in each window, moving over text in each window
12158 as far as they match. I use this command all the time.
12159
12160 This also shows how to set a key globally, for all modes.
12161
12162 The command is `global-set-key'. It is followed by the keybinding.
12163 In a `.emacs' file, the keybinding is written as shown: `\C-c' stands
12164 for `control-c', which means `press the control key and the `c' key
12165 at the same time'. The `w' means `press the `w' key'. The
12166 keybinding is surrounded by double quotation marks. In
12167 documentation, you would write this as `C-c w'. (If you were binding
12168 a <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
12170 Rebinding, for details.)
12171
12172 The command invoked by the keys is `compare-windows'. Note that
12173 `compare-windows' is preceded by a single quote; otherwise, Emacs
12174 would first try to evaluate the symbol to determine its value.
12175
12176 These three things, the double quotation marks, the backslash before
12177 the `C', and the single quote mark are necessary parts of keybinding
12178 that I tend to forget. Fortunately, I have come to remember that I
12179 should look at my existing `.emacs' file, and adapt what is there.
12180
12181 As 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
12184 individuals' own use. (I call these `own' keys, since these are for
12185 my own use.) You should always be able to create such a keybinding
12186 for your own use without stomping on someone else's keybinding. If
12187 you ever write an extension to Emacs, please avoid taking any of
12188 these keys for public use. Create a key like `C-c C-w' instead.
12189 Otherwise, we will run out of `own' keys.
12190
12191 Here 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
12197 The `occur' command shows all the lines in the current buffer that
12198 contain a match for a regular expression. Matching lines are shown
12199 in a buffer called `*Occur*'. That buffer serves as a menu to jump
12200 to occurrences.
12201
12202 Here is how to unbind a key, so it does not work:
12203
12204 ;;; Unbind `C-x f'
12205 (global-unset-key "\C-xf")
12206
12207 There 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
12209 I intended, I accidentally set the width for filled text, almost
12210 always to a width I did not want. Since I hardly ever reset my
12211 default width, I simply unbound the key.
12212
12213 The 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
12218 By default, `C-x C-b' runs the `list-buffers' command. This command
12219 lists your buffers in _another_ window. Since I almost always want
12220 to do something in that window, I prefer the `buffer-menu' command,
12221 which not only lists the buffers, but moves point into that window.
12222
12223 Keymaps
12224 =======
12225
12226 Emacs uses "keymaps" to record which keys call which commands. When
12227 you use `global-set-key' to set the keybinding for a single command
12228 in all parts of Emacs, you are specifying the keybinding in
12229 `current-global-map'.
12230
12231 Specific modes, such as C mode or Text mode, have their own keymaps;
12232 the mode-specific keymaps override the global map that is shared by
12233 all buffers.
12234
12235 The `global-set-key' function binds, or rebinds, the global keymap.
12236 For 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
12241 Mode-specific keymaps are bound using the `define-key' function,
12242 which takes a specific keymap as an argument, as well as the key and
12243 the command. For example, my `.emacs' file contains the following
12244 expression 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
12248 The `texinfo-insert-@group' function itself is a little extension to
12249 Texinfo mode that inserts `@group' into a Texinfo file. I use this
12250 command all the time and prefer to type the three strokes `C-c C-c g'
12251 rather than the six strokes `@ g r o u p'. (`@group' and its
12252 matching `@end group' are commands that keep all enclosed text
12253 together on one page; many multi-line examples in this book are
12254 surrounded by `@group ... @end group'.)
12255
12256 Here 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
12265 write a function to insert a word; but I prefer key strokes consistent
12266 with other Texinfo mode key bindings.)
12267
12268 You will see numerous `define-key' expressions in `loaddefs.el' as
12269 well 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
12273 Keymaps: (elisp)Keymaps, for more information about keymaps.
12274
12275 Loading Files
12276 =============
12277
12278 Many people in the GNU Emacs community have written extensions to
12279 Emacs. As time goes by, these extensions are often included in new
12280 releases. For example, the Calendar and Diary packages are now part
12281 of the standard GNU Emacs.
12282
12283 (Calc, which I consider a vital part of Emacs, would be part of the
12284 standard distribution except that it was so large it was packaged
12285 separately and no one has changed that.)
12286
12287 You can use a `load' command to evaluate a complete file and thereby
12288 install all the functions and variables in the file into Emacs. For
12289 example:
12290
12291 (load "~/emacs/slowsplit")
12292
12293 This evaluates, i.e. loads, the `slowsplit.el' file or if it exists,
12294 the faster, byte compiled `slowsplit.elc' file from the `emacs'
12295 sub-directory of your home directory. The file contains the function
12296 `split-window-quietly', which John Robinson wrote in 1989.
12297
12298 The `split-window-quietly' function splits a window with the minimum
12299 of redisplay. I installed it in 1989 because it worked well with the
12300 slow 1200 baud terminals I was then using. Nowadays, I only
12301 occasionally come across such a slow connection, but I continue to use
12302 the function because I like the way it leaves the bottom half of a
12303 buffer in the lower of the new windows and the top half in the upper
12304 window.
12305
12306 To replace the key binding for the default `split-window-vertically',
12307 you 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
12313 If you load many extensions, as I do, then instead of specifying the
12314 exact location of the extension file, as shown above, you can specify
12315 that directory as part of Emacs' `load-path'. Then, when Emacs loads
12316 a file, it will search that directory as well as its default list of
12317 directories. (The default list is specified in `paths.h' when Emacs
12318 is built.)
12319
12320 The following command adds your `~/emacs' directory to the existing
12321 load path:
12322
12323 ;;; Emacs Load Path
12324 (setq load-path (cons "~/emacs" load-path))
12325
12326 Incidentally, `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
12335 The 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
12339 Another interactive command that does a slightly different job is
12340 `load-file'. *Note Libraries of Lisp Code for Emacs: (emacs)Lisp
12341 Libraries, for information on the distinction between `load-library'
12342 and this command.
12343
12344 Autoloading
12345 ===========
12346
12347 Instead of installing a function by loading the file that contains it,
12348 or by evaluating the function definition, you can make the function
12349 available but not actually install it until it is first called. This
12350 is called "autoloading".
12351
12352 When you execute an autoloaded function, Emacs automatically evaluates
12353 the file that contains the definition, and then calls the function.
12354
12355 Emacs starts quicker with autoloaded functions, since their libraries
12356 are not loaded right away; but you need to wait a moment when you
12357 first use such a function, while its containing file is evaluated.
12358
12359 Rarely used functions are frequently autoloaded. The `loaddefs.el'
12360 library 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
12363 function's file with a `load' expression in your `.emacs' file.
12364
12365 In my `.emacs' file for Emacs version 21, I load 12 libraries that
12366 contain functions that would otherwise be autoloaded. (Actually, it
12367 would have been better to include these files in my `dumped' Emacs
12368 when I built it, but I forgot. *Note Building Emacs: (elisp)Building
12369 Emacs, and the `INSTALL' file for more about dumping.)
12370
12371 You may also want to include autoloaded expressions in your `.emacs'
12372 file. `autoload' is a built-in function that takes up to five
12373 arguments, the final three of which are optional. The first argument
12374 is the name of the function to be autoloaded; the second is the name
12375 of the file to be loaded. The third argument is documentation for the
12376 function, and the fourth tells whether the function can be called
12377 interactively. The fifth argument tells what type of
12378 object--`autoload' can handle a keymap or macro as well as a function
12379 (the default is a function).
12380
12381 Here 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
12387 standard part of the distribution).
12388
12389 This expression autoloads the `html-helper-mode' function. It takes
12390 it from the `html-helper-mode.el' file (or from the byte compiled
12391 file `html-helper-mode.elc', if it exists.) The file must be located
12392 in a directory specified by `load-path'. The documentation says that
12393 this is a mode to help you edit documents written in the HyperText
12394 Markup Language. You can call this mode interactively by typing `M-x
12395 html-helper-mode'. (You need to duplicate the function's regular
12396 documentation in the autoload expression because the regular function
12397 is not yet loaded, so its documentation is not available.)
12398
12399 *Note Autoload: (elisp)Autoload, for more information.
12400
12401 A Simple Extension: `line-to-top-of-window'
12402 ===========================================
12403
12404 Here is a simple extension to Emacs that moves the line point is on to
12405 the top of the window. I use this all the time, to make text easier
12406 to read.
12407
12408 You can put the following code into a separate file and then load it
12409 from your `.emacs' file, or you can include it within your `.emacs'
12410 file.
12411
12412 Here 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
12421 Now for the keybinding.
12422
12423 Nowadays, function keys as well as mouse button events and non-ASCII
12424 characters are written within square brackets, without quotation
12425 marks. (In Emacs version 18 and before, you had to write different
12426 function key bindings for each different make of terminal.)
12427
12428 I 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
12432 For more information, see *Note Rebinding Keys in Your Init File:
12433 (emacs)Init Rebinding.
12434
12435 If you run two versions of GNU Emacs, such as versions 20 and 21, and
12436 use one `.emacs' file, you can select which code to evaluate with the
12437 following 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
12447 For example, in contrast to version 20, version 21 blinks its cursor
12448 by default. I hate such blinking, as well as some other features in
12449 version 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
12474 decided to save typing and wrote `21' as a string, `"21"', rather
12475 than convert it from an integer to a string. In this instance, this
12476 expression is better than the longer, but more general
12477 `(number-to-string 21)'. However, if you do not know ahead of time
12478 what 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
12484 or any site file, I also turn off blinking:
12485
12486 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
12487
12488 X11 Colors
12489 ==========
12490
12491 You can specify colors when you use Emacs with the MIT X Windowing
12492 system.
12493
12494 I dislike the default colors and specify my own.
12495
12496 Here 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
12525 The various shades of blue soothe my eye and prevent me from seeing
12526 the screen flicker.
12527
12528 Alternatively, I could have set my specifications in various X
12529 initialization files. For example, I could set the foreground,
12530 background, 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
12538 In any event, since it is not part of Emacs, I set the root color of
12539 my 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
12547 with GNOME, Enlightenment, SCWM, or KDE; in those cases, I often
12548 specify an image rather than a plain color.
12549
12550 Miscellaneous Settings for a `.emacs' File
12551 ==========================================
12552
12553 Here 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
12570 A Modified Mode Line
12571 ====================
12572
12573 Finally, a feature I really like: a modified mode line.
12574
12575 When I work over a network, I forget which machine I am using. Also,
12576 I tend to I lose track of where I am, and which line point is on.
12577
12578 So I reset my mode line to look like this:
12579
12580 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
12581
12582 I am visiting a file called `foo.texi', on my machine `rattlesnake'
12583 in my `/home/bob' buffer. I am on line 1, in Texinfo mode, and am at
12584 the top of the buffer.
12585
12586 My `.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
12622 Here, I redefine the default mode line. Most of the parts are from
12623 the original; but I make a few changes. I set the _default_ mode
12624 line format so as to permit various modes, such as Info, to override
12625 it.
12626
12627 Many elements in the list are self-explanatory: `mode-line-modified'
12628 is a variable that tells whether the buffer has been modified,
12629 `mode-name' tells the name of the mode, and so on. However, the
12630 format looks complicated because of two features we have not
12631 discussed.
12632
12633 The first string in the mode line is a dash or hyphen, `-'. In the
12634 old days, it would have been specified simply as `"-"'. But
12635 nowadays, Emacs can add properties to a string, such as highlighting
12636 or, as in this case, a help feature. If you place your mouse cursor
12637 over the hyphen, some help information appears (By default, you must
12638 wait one second before the information appears. You can change that
12639 timing by changing the value of `tooltip-delay'.)
12640
12641 The new string format has a special syntax:
12642
12643 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
12644
12645 The `#(' begins a list. The first element of the list is the string
12646 itself, just one `-'. The second and third elements specify the
12647 range over which the fourth element applies. A range starts _after_
12648 a character, so a zero means the range starts just before the first
12649 character; a 1 means that the range ends just after the first
12650 character. The third element is the property for the range. It
12651 consists of a property list, a property name, in this case,
12652 `help-echo', followed by a value, in this case, a string. The
12653 second, third, and fourth elements of this new string format can be
12654 repeated.
12655
12656 *Note Text Properties in String: (elisp)Text Props and Strings, and
12657 see *Note Mode Line Format: (elisp)Mode Line Format, for more
12658 information.
12659
12660 `mode-line-buffer-identification' displays the current buffer name.
12661 It is a list beginning `(#("%12b" 0 4 ...'. The `#(' begins the list.
12662
12663 The `"%12b"' displays the current buffer name, using the
12664 `buffer-name' function with which we are familiar; the `12' specifies
12665 the maximum number of characters that will be displayed. When a name
12666 has fewer characters, whitespace is added to fill out to this number.
12667 (Buffer names can and often should be longer than 12 characters;
12668 this 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
12671 evaluate the following form and use the result as a string to display.
12672 In this case, the expression displays the first component of the full
12673 system name. The end of the first component is a `.' (`period'), so
12674 I use the `string-match' function to tell me the length of the first
12675 component. The substring from the zeroth character to that length is
12676 the name of the machine.
12677
12678 This 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
12684 recursive editing level. `%n' says `Narrow' when narrowing is in
12685 effect. `%P' tells you the percentage of the buffer that is above
12686 the bottom of the window, or `Top', `Bottom', or `All'. (A lower
12687 case `p' tell you the percentage above the _top_ of the window.)
12688 `%-' inserts enough dashes to fill out the line.
12689
12690 Remember, "You don't have to like Emacs to like it" -- your own Emacs
12691 can have different colors, different commands, and different keys
12692 than a default Emacs.
12693
12694 On the other hand, if you want to bring up a plain `out of the box'
12695 Emacs, with no customization, type:
12696
12697 emacs -q
12698
12699 This will start an Emacs that does _not_ load your `~/.emacs'
12700 initialization file. A plain, default Emacs. Nothing more.
12701
12702 Debugging
12703 *********
12704
12705 GNU Emacs has two debuggers, `debug' and `edebug'. The first is
12706 built into the internals of Emacs and is always with you; the second
12707 requires that you instrument a function before you can use it.
12708
12709 Both debuggers are described extensively in *Note Debugging Lisp
12710 Programs: (elisp)Debugging. In this chapter, I will walk through a
12711 short example of each.
12712
12713 `debug'
12714 =======
12715
12716 Suppose you have written a function definition that is intended to
12717 return the sum of the numbers 1 through a given number. (This is the
12718 `triangle' function discussed earlier. *Note Example with
12719 Decrementing Counter: Decrementing Example, for a discussion.)
12720
12721 However, your function definition has a bug. You have mistyped `1='
12722 for `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
12732 If you are reading this in Info, you can evaluate this definition in
12733 the normal fashion. You will see `triangle-bugged' appear in the
12734 echo area.
12735
12736 Now evaluate the `triangle-bugged' function with an argument of 4:
12737
12738 (triangle-bugged 4)
12739
12740 In GNU Emacs version 21, you will create and enter a `*Backtrace*'
12741 buffer 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
12759 long lines. As usual, you can quit the debugger by typing `q' in the
12760 `*Backtrace*' buffer.)
12761
12762 In practice, for a bug as simple as this, the `Lisp error' line will
12763 tell you what you need to know to correct the definition. The
12764 function `1=' is `void'.
12765
12766 In GNU Emacs 20 and before, you will see:
12767
12768 Symbol's function definition is void: 1=
12769
12770 which has the same meaning as the `*Backtrace*' buffer line in
12771 version 21.
12772
12773 However, suppose you are not quite certain what is going on? You can
12774 read the complete backtrace.
12775
12776 In this case, you need to run GNU Emacs 21, which automatically starts
12777 the debugger that puts you in the `*Backtrace*' buffer; or else, you
12778 need to start the debugger manually as described below.
12779
12780 Read the `*Backtrace*' buffer from the bottom up; it tells you what
12781 Emacs 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
12784 Lisp interpreter evaluated next.
12785
12786 The third line from the top of the buffer is
12787
12788 (setq number (1= number))
12789
12790 Emacs tried to evaluate this expression; in order to do so, it tried
12791 to evaluate the inner expression shown on the second line from the
12792 top:
12793
12794 (1= number)
12795
12796 This is where the error occurred; as the top line says:
12797
12798 Debugger entered--Lisp error: (void-function 1=)
12799
12800 You can correct the mistake, re-evaluate the function definition, and
12801 then run your test again.
12802
12803 `debug-on-entry'
12804 ================
12805
12806 GNU Emacs 21 starts the debugger automatically when your function has
12807 an error. GNU Emacs version 20 and before did not; it simply
12808 presented you with an error message. You had to start the debugger
12809 manually.
12810
12811 You can start the debugger manually for all versions of Emacs; the
12812 advantage is that the debugger runs even if you do not have a bug in
12813 your code. Sometimes your code will be free of bugs!
12814
12815 You can enter the debugger when you call the function by calling
12816 `debug-on-entry'.
12817
12818 Type:
12819
12820 M-x debug-on-entry RET triangle-bugged RET
12821
12822 Now, evaluate the following:
12823
12824 (triangle-bugged 5)
12825
12826 All versions of Emacs will create a `*Backtrace*' buffer and tell you
12827 that 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
12838 In the `*Backtrace*' buffer, type `d'. Emacs will evaluate the first
12839 expression 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
12852 Now, type `d' again, eight times, slowly. Each time you type `d',
12853 Emacs will evaluate another expression in the function definition.
12854
12855 Eventually, 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
12871 Finally, after you type `d' two more times, Emacs will reach the
12872 error, and the top two lines of the `*Backtrace*' buffer will look
12873 like this:
12874
12875 ---------- Buffer: *Backtrace* ----------
12876 Debugger entered--Lisp error: (void-function 1=)
12877 * (1= number)
12878 ...
12879 ---------- Buffer: *Backtrace* ----------
12880
12881 By typing `d', you were able to step through the function.
12882
12883 You can quit a `*Backtrace*' buffer by typing `q' in it; this quits
12884 the trace, but does not cancel `debug-on-entry'.
12885
12886 To 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
12896 In addition to setting `debug-on-error' or calling `debug-on-entry',
12897 there are two other ways to start `debug'.
12898
12899 You can start `debug' whenever you type `C-g' (`keyboard-quit') by
12900 setting the variable `debug-on-quit' to `t'. This is useful for
12901 debugging infinite loops.
12902
12903 Or, you can insert a line that says `(debug)' into your code where
12904 you 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
12915 The `debug' function is described in detail in *Note The Lisp
12916 Debugger: (elisp)Debugger.
12917
12918 The `edebug' Source Level Debugger
12919 ==================================
12920
12921 Edebug is a source level debugger. Edebug normally displays the
12922 source of the code you are debugging, with an arrow at the left that
12923 shows which line you are currently executing.
12924
12925 You can walk through the execution of a function, line by line, or run
12926 quickly until reaching a "breakpoint" where execution stops.
12927
12928 Edebug is described in *Note Edebug: (elisp)edebug.
12929
12930 Here is a bugged function definition for `triangle-recursively'.
12931 *Note Recursion in place of a counter: Recursive triangle function,
12932 for 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
12943 Normally, you would install this definition by positioning your cursor
12944 after the function's closing parenthesis and typing `C-x C-e'
12945 (`eval-last-sexp') or else by positioning your cursor within the
12946 definition and typing `C-M-x' (`eval-defun'). (By default, the
12947 `eval-defun' command works only in Emacs Lisp mode or in Lisp
12948 Interactive mode.)
12949
12950 However, to prepare this function definition for Edebug, you must
12951 first "instrument" the code using a different command. You can do
12952 this by positioning your cursor within the definition and typing
12953
12954 M-x edebug-defun RET
12955
12956 This will cause Emacs to load Edebug automatically if it is not
12957 already loaded, and properly instrument the function.
12958
12959 After instrumenting the function, place your cursor after the
12960 following expression and type `C-x C-e' (`eval-last-sexp'):
12961
12962 (triangle-recursively-bugged 3)
12963
12964 You will be jumped back to the source for
12965 `triangle-recursively-bugged' and the cursor positioned at the
12966 beginning of the `if' line of the function. Also, you will see an
12967 arrowhead at the left hand side of that line. The arrowhead marks
12968 the line where the function is executing. (In the following examples,
12969 we show the arrowhead with `=>'; in a windowing system, you may see
12970 the arrowhead as a solid triangle in the window `fringe'.)
12971
12972 =>-!-(if (= number 1)
12973
12974 In the example, the location of point is displayed as `-!-' (in a
12975 printed book, it is displayed with a five pointed star).
12976
12977 If you now press <SPC>, point will move to the next expression to be
12978 executed; the line will look like this:
12979
12980 =>(if -!-(= number 1)
12981
12982 As you continue to press <SPC>, point will move from expression to
12983 expression. At the same time, whenever an expression returns a value,
12984 that value will be displayed in the echo area. For example, after you
12985 move point past `number', you will see the following:
12986
12987 Result: 3 = C-c
12988
12989 This means the value of `number' is 3, which is ASCII `control-c'
12990 (the third letter of the alphabet).
12991
12992 You can continue moving through the code until you reach the line with
12993 the error. Before evaluation, that line looks like this:
12994
12995 => -!-(1= number))))) ; Error here.
12996
12997 When you press <SPC> once again, you will produce an error message
12998 that says:
12999
13000 Symbol's function definition is void: 1=
13001
13002 This is the bug.
13003
13004 Press `q' to quit Edebug.
13005
13006 To remove instrumentation from a function definition, simply
13007 re-evaluate it with a command that does not instrument it. For
13008 example, you could place your cursor after the definition's closing
13009 parenthesis and type `C-x C-e'.
13010
13011 Edebug does a great deal more than walk with you through a function.
13012 You can set it so it races through on its own, stopping only at an
13013 error or at specified stopping points; you can cause it to display the
13014 changing values of various expressions; you can find out how many
13015 times a function is called, and more.
13016
13017 Edebug is described in *Note Edebug: (elisp)edebug.
13018
13019 Debugging 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
13054 Conclusion
13055 **********
13056
13057 We have now reached the end of this Introduction. You have now
13058 learned enough about programming in Emacs Lisp to set values, to write
13059 simple `.emacs' files for yourself and your friends, and write simple
13060 customizations and extensions to Emacs.
13061
13062 This is a place to stop. Or, if you wish, you can now go onward, and
13063 teach yourself.
13064
13065 You have learned some of the basic nuts and bolts of programming. But
13066 only some. There are a great many more brackets and hinges that are
13067 easy to use that we have not touched.
13068
13069 A path you can follow right now lies among the sources to GNU Emacs
13070 and in *Note The GNU Emacs Lisp Reference Manual: (elisp)Top.
13071
13072 The Emacs Lisp sources are an adventure. When you read the sources
13073 and come across a function or expression that is unfamiliar, you need
13074 to figure out or find out what it does.
13075
13076 Go to the Reference Manual. It is a thorough, complete, and fairly
13077 easy-to-read description of Emacs Lisp. It is written not only for
13078 experts, but for people who know what you know. (The `Reference
13079 Manual' comes with the standard GNU Emacs distribution. Like this
13080 introduction, it comes as a Texinfo source file, so you can read it
13081 on-line and as a typeset, printed book.)
13082
13083 Go to the other on-line help that is part of GNU Emacs: the on-line
13084 documentation for all functions, and `find-tags', the program that
13085 takes you to sources.
13086
13087 Here 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
13089 happens some of the functions in `simple.el' are complicated, or at
13090 least look complicated at first sight. The `open-line' function, for
13091 example, looks complicated.
13092
13093 You may want to walk through this function slowly, as we did with the
13094 `forward-sentence' function. (*Note forward-sentence::.) Or you may
13095 want to skip that function and look at another, such as `split-line'.
13096 You don't need to read all the functions. According to
13097 `count-words-in-defun', the `split-line' function contains 27 words
13098 and symbols.
13099
13100 Even though it is short, `split-line' contains four expressions we
13101 have not studied: `skip-chars-forward', `indent-to', `current-column'
13102 and `?\n'.
13103
13104 Consider the `skip-chars-forward' function. (It is part of the
13105 function definition for `back-to-indentation', which is shown in
13106 *Note Review: Review.)
13107
13108 In GNU Emacs, you can find out more about `skip-chars-forward' by
13109 typing `C-h f' (`describe-function') and the name of the function.
13110 This gives you the function documentation.
13111
13112 You 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
13115 those long, but decipherable functions. You can look up
13116 `describe-function' using the `C-h f' command!
13117
13118 In this instance, since the code is Lisp, the `*Help*' buffer
13119 contains the name of the library containing the function's source.
13120 You can put point over the name of the library and press the RET key,
13121 which in this situation is bound to `help-follow', and be taken
13122 directly to the source, in the same way as `M-.' (`find-tag').
13123
13124 The definition for `describe-function' illustrates how to customize
13125 the `interactive' expression without using the standard character
13126 codes; and it shows how to create a temporary buffer.
13127
13128 (The `indent-to' function is written in C rather than Emacs Lisp; it
13129 is a `built-in' function. `help-follow' only provides you with the
13130 documentation of a built-in function; it does not take you to the
13131 source. But `find-tag' will take you to the source, if properly set
13132 up.)
13133
13134 You can look at a function's source using `find-tag', which is bound
13135 to `M-.' Finally, you can find out what the Reference Manual has to
13136 say by visiting the manual in Info, and typing `i' (`Info-index') and
13137 the name of the function, or by looking up `skip-chars-forward' in
13138 the index to a printed copy of the manual.
13139
13140 Similarly, you can find out what is meant by `?\n'. You can try
13141 using `Info-index' with `?\n'. It turns out that this action won't
13142 help; but don't give up. If you search the index for `\n' without
13143 the `?', you will be taken directly to the relevant section of the
13144 manual. (*Note Character Type: (elisp)Character Type. `?\n' stands
13145 for the newline character.)
13146
13147 Other interesting source files include `paragraphs.el',
13148 `loaddefs.el', and `loadup.el'. The `paragraphs.el' file includes
13149 short, easily understood functions as well as longer ones. The
13150 `loaddefs.el' file contains the many standard autoloads and many
13151 keymaps. I have never looked at it all; only at parts. `loadup.el'
13152 is the file that loads the standard parts of Emacs; it tells you a
13153 great deal about how Emacs is built. (*Note Building Emacs:
13154 (elisp)Building Emacs, for more about building.)
13155
13156 As I said, you have learned some nuts and bolts; however, and very
13157 importantly, we have hardly touched major aspects of programming; I
13158 have said nothing about how to sort information, except to use the
13159 predefined `sort' function; I have said nothing about how to store
13160 information, except to use variables and lists; I have said nothing
13161 about how to write programs that write programs. These are topics for
13162 another, and different kind of book, a different kind of learning.
13163
13164 What you have done is learn enough for much practical work with GNU
13165 Emacs. What you have done is get started. This is the end of a
13166 beginning.
13167
13168 The `the-the' Function
13169 **********************
13170
13171 Sometimes when you you write text, you duplicate words--as with "you
13172 you" near the beginning of this sentence. I find that most
13173 frequently, I duplicate "the'; hence, I call the function for
13174 detecting duplicated words, `the-the'.
13175
13176 As a first step, you could use the following regular expression to
13177 search for duplicates:
13178
13179 \\(\\w+[ \t\n]+\\)\\1
13180
13181 This regexp matches one or more word-constituent characters followed
13182 by one or more spaces, tabs, or newlines. However, it does not detect
13183 duplicated words on different lines, since the ending of the first
13184 word, the end of the line, is different from the ending of the second
13185 word, a space. (For more information about regular expressions, see
13186 *Note Regular Expression Searches: Regexp Search, as well as *Note
13187 Syntax of Regular Expressions: (emacs)Regexps, and *Note Regular
13188 Expressions: (elisp)Regular Expressions.)
13189
13190 You might try searching just for duplicated word-constituent
13191 characters but that does not work since the pattern detects doubles
13192 such as the two occurrences of `th' in `with the'.
13193
13194 Another possible regexp searches for word-constituent characters
13195 followed by non-word-constituent characters, reduplicated. Here,
13196 `\\w+' matches one or more word-constituent characters and `\\W*'
13197 matches zero or more non-word-constituent characters.
13198
13199 \\(\\(\\w+\\)\\W*\\)\\1
13200
13201 Again, not useful.
13202
13203 Here 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
13205 end of a word; `[^@ \n\t]+' matches one or more occurrences of any
13206 characters that are _not_ an @-sign, space, newline, or tab.
13207
13208 \\b\\([^@ \n\t]+\\)[ \n\t]+\\1\\b
13209
13210 One can write more complicated expressions, but I found that this
13211 expression is good enough, so I use it.
13212
13213 Here is the `the-the' function, as I include it in my `.emacs' file,
13214 along 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
13232 Here is test text:
13233
13234 one two two three four five
13235 five six seven
13236
13237 You can substitute the other regular expressions shown above in the
13238 function definition and try each of them on this list.
13239
13240 Handling the Kill Ring
13241 **********************
13242
13243 The kill ring is a list that is transformed into a ring by the
13244 workings of the `rotate-yank-pointer' function. The `yank' and
13245 `yank-pop' commands use the `rotate-yank-pointer' function. This
13246 appendix describes the `rotate-yank-pointer' function as well as both
13247 the `yank' and the `yank-pop' commands.
13248
13249 The `rotate-yank-pointer' Function
13250 ==================================
13251
13252 The `rotate-yank-pointer' function changes the element in the kill
13253 ring to which `kill-ring-yank-pointer' points. For example, it can
13254 change `kill-ring-yank-pointer' from pointing to the second element
13255 to point to the third element.
13256
13257 Here 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
13278 The `rotate-yank-pointer' function looks complex, but as usual, it
13279 can be understood by taking it apart piece by piece. First look at
13280 it 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
13288 This function takes one argument, called `arg'. It has a brief
13289 documentation string; and it is interactive with a small `p', which
13290 means that the argument must be a processed prefix passed to the
13291 function as a number.
13292
13293 The body of the function definition is a `let' expression, which
13294 itself has a body as well as a VARLIST.
13295
13296 The `let' expression declares a variable that will be only usable
13297 within the bounds of this function. This variable is called `length'
13298 and is bound to a value that is equal to the number of items in the
13299 kill 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
13302 other is to name the variable. The two are quite distinct.
13303 Similarly, an English speaker will distinguish between the meanings
13304 of the word `ship' when he says: "I must ship this package
13305 immediately." and "I must get aboard the ship immediately.")
13306
13307 The function `length' tells the number of items there are in a list,
13308 so `(length kill-ring)' returns the number of items there are in the
13309 kill ring.
13310
13311 The Body of `rotate-yank-pointer'
13312 ---------------------------------
13313
13314 The body of `rotate-yank-pointer' is a `let' expression and the body
13315 of the `let' expression is an `if' expression.
13316
13317 The purpose of the `if' expression is to find out whether there is
13318 anything in the kill ring. If the kill ring is empty, the `error'
13319 function stops evaluation of the function and prints a message in the
13320 echo area. On the other hand, if the kill ring has something in it,
13321 the work of the function is done.
13322
13323 Here 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
13329 If there is not anything in the kill ring, its length must be zero and
13330 an error message sent to the user: `Kill ring is empty'. The `if'
13331 expression uses the function `zerop' which returns true if the value
13332 it 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
13334 function `error', which is a function that is similar to the
13335 `message' function (*note message::), in that it prints a one-line
13336 message in the echo area. However, in addition to printing a
13337 message, `error' also stops evaluation of the function within which
13338 it is embedded. This means that the rest of the function will not be
13339 evaluated if the length of the kill ring is zero.
13340
13341 Digression about the word `error'
13342 .................................
13343
13344 (In my opinion, it is slightly misleading, at least to humans, to use
13345 the term `error' as the name of the `error' function. A better term
13346 would be `cancel'. Strictly speaking, of course, you cannot point
13347 to, much less rotate a pointer to a list that has no length, so from
13348 the point of view of the computer, the word `error' is correct. But
13349 a human expects to attempt this sort of thing, if only to find out
13350 whether the kill ring is full or empty. This is an act of
13351 exploration.
13352
13353 (From the human point of view, the act of exploration and discovery is
13354 not necessarily an error, and therefore should not be labelled as one,
13355 even in the bowels of a computer. As it is, the code in Emacs implies
13356 that a human who is acting virtuously, by exploring his or her
13357 environment, is making an error. This is bad. Even though the
13358 computer takes the same steps as it does when there is an `error', a
13359 term such as `cancel' would have a clearer connotation.)
13360
13361 The else-part of the `if' expression
13362 ....................................
13363
13364 The else-part of the `if' expression is dedicated to setting the
13365 value of `kill-ring-yank-pointer' when the kill ring has something in
13366 it. 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
13375 This needs some examination. Clearly, `kill-ring-yank-pointer' is
13376 being set to be equal to some CDR of the kill ring, using the
13377 `nthcdr' function that is described in an earlier section. (*Note
13378 copy-region-as-kill::.) But exactly how does it do this?
13379
13380 Before looking at the details of the code let's first consider the
13381 purpose of the `rotate-yank-pointer' function.
13382
13383 The `rotate-yank-pointer' function changes what
13384 `kill-ring-yank-pointer' points to. If `kill-ring-yank-pointer'
13385 starts 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
13387 if `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
13389 if `rotate-yank-pointer' is given an argument greater than 1, it
13390 jumps the pointer that many elements.)
13391
13392 The `rotate-yank-pointer' function uses `setq' to reset what the
13393 `kill-ring-yank-pointer' points to. If `kill-ring-yank-pointer'
13394 points to the first element of the kill ring, then, in the simplest
13395 case, the `rotate-yank-pointer' function must cause it to point to
13396 the second element. Put another way, `kill-ring-yank-pointer' must
13397 be reset to have a value equal to the CDR of the kill ring.
13398
13399 That 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
13407 the code should do this:
13408
13409 (setq kill-ring-yank-pointer (cdr kill-ring))
13410
13411 As 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
13416 The actual `setq' expression uses the `nthcdr' function to do the job.
13417
13418 As we have seen before (*note nthcdr::), the `nthcdr' function works
13419 by repeatedly taking the CDR of a list--it takes the CDR of the CDR
13420 of the CDR ...
13421
13422 The 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
13428 In the `rotate-yank-pointer' function, however, the first argument to
13429 `nthcdr' is a rather complex looking expression with lots of
13430 arithmetic inside of it:
13431
13432 (% (+ arg
13433 (- length
13434 (length kill-ring-yank-pointer)))
13435 length)
13436
13437 As usual, we need to look at the most deeply embedded expression first
13438 and then work our way towards the light.
13439
13440 The most deeply embedded expression is `(length
13441 kill-ring-yank-pointer)'. This finds the length of the current value
13442 of the `kill-ring-yank-pointer'. (Remember that the
13443 `kill-ring-yank-pointer' is the name of a variable whose value is a
13444 list.)
13445
13446 The measurement of the length is inside the expression:
13447
13448 (- length (length kill-ring-yank-pointer))
13449
13450 In this expression, the first `length' is the variable that was
13451 assigned the length of the kill ring in the `let' statement at the
13452 beginning of the function. (One might think this function would be
13453 clearer if the variable `length' were named `length-of-kill-ring'
13454 instead; but if you look at the text of the whole function, you will
13455 see that it is so short that naming this variable `length' is not a
13456 bother, unless you are pulling the function apart into very tiny
13457 pieces as we are doing here.)
13458
13459 So the line `(- length (length kill-ring-yank-pointer))' tells the
13460 difference between the length of the kill ring and the length of the
13461 list whose name is `kill-ring-yank-pointer'.
13462
13463 To see how all this fits into the `rotate-yank-pointer' function,
13464 let's begin by analyzing the case where `kill-ring-yank-pointer'
13465 points to the first element of the kill ring, just as `kill-ring'
13466 does, and see what happens when `rotate-yank-pointer' is called with
13467 an argument of 1.
13468
13469 The variable `length' and the value of the expression `(length
13470 kill-ring-yank-pointer)' will be the same since the variable `length'
13471 is the length of the kill ring and the `kill-ring-yank-pointer' is
13472 pointing to the whole kill ring. Consequently, the value of
13473
13474 (- length (length kill-ring-yank-pointer))
13475
13476 will be zero. Since the value of `arg' will be 1, this will mean
13477 that the value of the whole expression
13478
13479 (+ arg (- length (length kill-ring-yank-pointer)))
13480
13481 will be 1.
13482
13483 Consequently, the argument to `nthcdr' will be found as the result of
13484 the expression
13485
13486 (% 1 length)
13487
13488 The `%' remainder function
13489 ..........................
13490
13491 To understand `(% 1 length)', we need to understand `%'. According
13492 to its documentation (which I just found by typing `C-h f % <RET>'),
13493 the `%' function returns the remainder of its first argument divided
13494 by its second argument. For example, the remainder of 5 divided by 2
13495 is 1. (2 goes into 5 twice with a remainder of 1.)
13496
13497 What surprises people who don't often do arithmetic is that a smaller
13498 number can be divided by a larger number and have a remainder. In the
13499 example we just used, 5 was divided by 2. We can reverse that and
13500 ask, what is the result of dividing 2 by 5? If you can use
13501 fractions, the answer is obviously 2/5 or .4; but if, as here, you
13502 can only use whole numbers, the result has to be something different.
13503 Clearly, 5 can go into 2 zero times, but what of the remainder? To
13504 see what the answer is, consider a case that has to be familiar from
13505 childhood:
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
13519 By 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
13527 and so on.
13528
13529 So, in this code, if the value of `length' is 5, then the result of
13530 evaluating
13531
13532 (% 1 5)
13533
13534 is 1. (I just checked this by placing the cursor after the expression
13535 and typing `C-x C-e'. Indeed, 1 is printed in the echo area.)
13536
13537 Using `%' in `rotate-yank-pointer'
13538 ..................................
13539
13540 When the `kill-ring-yank-pointer' points to the beginning of the kill
13541 ring, and the argument passed to `rotate-yank-pointer' is 1, the `%'
13542 expression returns 1:
13543
13544 (- length (length kill-ring-yank-pointer))
13545 => 0
13546
13547 therefore,
13548
13549 (+ arg (- length (length kill-ring-yank-pointer)))
13550 => 1
13551
13552 and consequently:
13553
13554 (% (+ arg (- length (length kill-ring-yank-pointer)))
13555 length)
13556 => 1
13557
13558 regardless of the value of `length'.
13559
13560 As a result of this, the `setq kill-ring-yank-pointer' expression
13561 simplifies to:
13562
13563 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
13564
13565 What it does is now easy to understand. Instead of pointing as it did
13566 to the first element of the kill ring, the `kill-ring-yank-pointer'
13567 is set to point to the second element.
13568
13569 Clearly, if the argument passed to `rotate-yank-pointer' is two, then
13570 the `kill-ring-yank-pointer' is set to `(nthcdr 2 kill-ring)'; and so
13571 on for different values of the argument.
13572
13573 Similarly, if the `kill-ring-yank-pointer' starts out pointing to the
13574 second element of the kill ring, its length is shorter than the
13575 length of the kill ring by 1, so the computation of the remainder is
13576 based on the expression `(% (+ arg 1) length)'. This means that the
13577 `kill-ring-yank-pointer' is moved from the second element of the kill
13578 ring to the third element if the argument passed to
13579 `rotate-yank-pointer' is 1.
13580
13581 Pointing to the last element
13582 ............................
13583
13584 The final question is, what happens if the `kill-ring-yank-pointer'
13585 is 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
13587 kill ring? The answer is no. What happens is different and useful.
13588 The `kill-ring-yank-pointer' is set to point to the beginning of the
13589 kill ring instead.
13590
13591 Let's see how this works by looking at the code, assuming the length
13592 of the kill ring is 5 and the argument passed to
13593 `rotate-yank-pointer' is 1. When the `kill-ring-yank-pointer' points
13594 to the last element of the kill ring, its length is 1. The code
13595 looks like this:
13596
13597 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
13598
13599 When the variables are replaced by their numeric values, the
13600 expression looks like this:
13601
13602 (% (+ 1 (- 5 1)) 5)
13603
13604 This expression can be evaluated by looking at the most embedded inner
13605 expression first and working outwards: The value of `(- 5 1)' is 4;
13606 the sum of `(+ 1 4)' is 5; and the remainder of dividing 5 by 5 is
13607 zero. So what `rotate-yank-pointer' will do is
13608
13609 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
13610
13611 which will set the `kill-ring-yank-pointer' to point to the beginning
13612 of the kill ring.
13613
13614 So what happens with successive calls to `rotate-yank-pointer' is that
13615 it moves the `kill-ring-yank-pointer' from element to element in the
13616 kill ring until it reaches the end; then it jumps back to the
13617 beginning. And this is why the kill ring is called a ring, since by
13618 jumping back to the beginning, it is as if the list has no end! (And
13619 what is a ring, but an entity with no end?)
13620
13621 `yank'
13622 ======
13623
13624 After learning about `rotate-yank-pointer', the code for the `yank'
13625 function is almost easy. It has only one tricky part, which is the
13626 computation of the argument to be passed to `rotate-yank-pointer'.
13627
13628 The 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
13648 Glancing over this code, we can understand the last few lines readily
13649 enough. The mark is pushed, that is, remembered; then the first
13650 element (the CAR) of what the `kill-ring-yank-pointer' points to is
13651 inserted; and then, if the argument passed the function is a `cons',
13652 point and mark are exchanged so the point is put in the front of the
13653 inserted text rather than at the end. This option is explained in
13654 the documentation. The function itself is interactive with `"*P"'.
13655 This means it will not work on a read-only buffer, and that the
13656 unprocessed prefix argument is passed to the function.
13657
13658 Passing the argument
13659 ....................
13660
13661 The hard part of `yank' is understanding the computation that
13662 determines the value of the argument passed to `rotate-yank-pointer'.
13663 Fortunately, it is not so difficult as it looks at first sight.
13664
13665 What happens is that the result of evaluating one or both of the `if'
13666 expressions will be a number and that number will be the argument
13667 passed to `rotate-yank-pointer'.
13668
13669 Laid 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
13677 This code consists of two `if' expression, one the else-part of the
13678 other.
13679
13680 The first or outer `if' expression tests whether the argument passed
13681 to `yank' is a list. Oddly enough, this will be true if `yank' is
13682 called without an argument--because then it will be passed the value
13683 of `nil' for the optional argument and an evaluation of `(listp nil)'
13684 returns true! So, if no argument is passed to `yank', the argument
13685 passed to `rotate-yank-pointer' inside of `yank' is zero. This means
13686 the pointer is not moved and the first element to which
13687 `kill-ring-yank-pointer' points is inserted, as we expect.
13688 Similarly, if the argument for `yank' is `C-u', this will be read as
13689 a 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
13691 list of one element.) At the same time, later in the function, this
13692 argument will be read as a `cons' so point will be put in the front
13693 and mark at the end of the insertion. (The `P' argument to
13694 `interactive' is designed to provide these values for the case when
13695 an optional argument is not provided or when it is `C-u'.)
13696
13697 The then-part of the outer `if' expression handles the case when
13698 there is no argument or when it is `C-u'. The else-part handles the
13699 other situations. The else-part is itself another `if' expression.
13700
13701 The 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,
13703 or the <ESC> key and then the `-' key). In this case, the
13704 `rotate-yank-pointer' function is passed `-1' as an argument. This
13705 moves the `kill-ring-yank-pointer' backwards, which is what is
13706 desired.
13707
13708 If the true-or-false-test of the inner `if' expression is false (that
13709 is, if the argument is not a minus sign), the else-part of the
13710 expression is evaluated. This is the expression `(1- arg)'. Because
13711 of the two `if' expressions, it will only occur when the argument is
13712 a positive number or when it is a negative number (not just a minus
13713 sign on its own). What `(1- arg)' does is decrement the number and
13714 return it. (The `1-' function subtracts one from its argument.)
13715 This means that if the argument to `rotate-yank-pointer' is 1, it is
13716 reduced to zero, which means the first element to which
13717 `kill-ring-yank-pointer' points is yanked back, as you would expect.
13718
13719 Passing a negative argument
13720 ...........................
13721
13722 Finally, the question arises, what happens if either the remainder
13723 function, `%', or the `nthcdr' function is passed a negative
13724 argument, as they quite well may?
13725
13726 The answers can be found by a quick test. When `(% -1 5)' is
13727 evaluated, a negative number is returned; and if `nthcdr' is called
13728 with a negative number, it returns the same value as if it were
13729 called with a first argument of zero. This can be seen by evaluating
13730 the following code.
13731
13732 Here the `=>' points to the result of evaluating the code preceding
13733 it. This was done by positioning the cursor after the code and
13734 typing `C-x C-e' (`eval-last-sexp') in the usual fashion. You can do
13735 this 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
13752 So, 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
13754 beginning of the list. Then it stays there. Unlike the other case,
13755 when it jumps from the end of the list to the beginning of the list,
13756 making a ring, it stops. This makes sense. You often want to get
13757 back to the most recently clipped out piece of text, but you don't
13758 usually want to insert text from as many as thirty kill commands ago.
13759 So you need to work through the ring to get to the end, but won't
13760 cycle around it inadvertently if you are trying to come back to the
13761 beginning.
13762
13763 Incidentally, any number passed to `yank' with a minus sign preceding
13764 it will be treated as -1. This is evidently a simplification for
13765 writing the program. You don't need to jump back towards the
13766 beginning of the kill ring more than one place at a time and doing
13767 this is easier than writing a function to determine the magnitude of
13768 the number that follows the minus sign.
13769
13770 `yank-pop'
13771 ==========
13772
13773 After understanding `yank', the `yank-pop' function is easy. Leaving
13774 out 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
13788 The function is interactive with a small `p' so the prefix argument
13789 is processed and passed to the function. The command can only be
13790 used after a previous yank; otherwise an error message is sent. This
13791 check uses the variable `last-command' which is discussed elsewhere.
13792 (*Note copy-region-as-kill::.)
13793
13794 The `let' clause sets the variable `before' to true or false
13795 depending whether point is before or after mark and then the region
13796 between point and mark is deleted. This is the region that was just
13797 inserted by the previous yank and it is this text that will be
13798 replaced. Next the `kill-ring-yank-pointer' is rotated so that the
13799 previously inserted text is not reinserted yet again. Mark is set at
13800 the beginning of the place the new text will be inserted and then the
13801 first element to which `kill-ring-yank-pointer' points is inserted.
13802 This leaves point after the new text. If in the previous yank, point
13803 was left before the inserted text, point and mark are now exchanged
13804 so point is again left in front of the newly inserted text. That is
13805 all there is to it!
13806
13807 A Graph with Labelled Axes
13808 **************************
13809
13810 Printed axes help you understand a graph. They convey scale. In an
13811 earlier chapter (*note Readying a Graph: Readying a Graph.), we wrote
13812 the code to print the body of a graph. Here we write the code for
13813 printing and labelling vertical and horizontal axes, along with the
13814 body itself.
13815
13816 Labelled Example Graph
13817 ======================
13818
13819 Since insertions fill a buffer to the right and below point, the new
13820 graph printing function should first print the Y or vertical axis,
13821 then the body of the graph, and finally the X or horizontal axis.
13822 This 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
13832 Here 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
13847 In this graph, both the vertical and the horizontal axes are labelled
13848 with numbers. However, in some graphs, the horizontal axis is time
13849 and would be better labelled with months, like this:
13850
13851 5 - *
13852 * ** *
13853 *******
13854 ********** **
13855 1 - **************
13856 | ^ |
13857 Jan June Jan
13858
13859 Indeed, with a little thought, we can easily come up with a variety of
13860 vertical and horizontal labelling schemes. Our task could become
13861 complicated. But complications breed confusion. Rather than permit
13862 this, it is better choose a simple labelling scheme for our first
13863 effort, and to modify or replace it later.
13864
13865 These 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
13876 We can work on each part of the `print-graph' function definition in
13877 turn.
13878
13879 The `print-graph' Varlist
13880 =========================
13881
13882 In writing the `print-graph' function, the first task is to write the
13883 varlist in the `let' expression. (We will leave aside for the moment
13884 any thoughts about making the function interactive or about the
13885 contents of its documentation string.)
13886
13887 The varlist should set several values. Clearly, the top of the label
13888 for the vertical axis must be at least the height of the graph, which
13889 means that we must obtain this information here. Note that the
13890 `print-graph-body' function also requires this information. There is
13891 no reason to calculate the height of the graph in two different
13892 places, so we should change `print-graph-body' from the way we
13893 defined it earlier to take advantage of the calculation.
13894
13895 Similarly, 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
13897 each symbol. We can perform the calculation here and change the
13898 definition for `print-graph-body' from the way we defined it in the
13899 previous chapter.
13900
13901 The length of the label for the horizontal axis must be at least as
13902 long as the graph. However, this information is used only in the
13903 function that prints the horizontal axis, so it does not need to be
13904 calculated here.
13905
13906 These thoughts lead us directly to the following form for the varlist
13907 in the `let' for `print-graph':
13908
13909 (let ((height (apply 'max numbers-list)) ; First version.
13910 (symbol-width (length graph-blank)))
13911
13912 As we shall see, this expression is not quite right.
13913
13914 The `print-Y-axis' Function
13915 ===========================
13916
13917 The job of the `print-Y-axis' function is to print a label for the
13918 vertical axis that looks like this:
13919
13920 10 -
13921
13922
13923
13924
13925 5 -
13926
13927
13928
13929 1 -
13930
13931 The function should be passed the height of the graph, and then should
13932 construct and insert the appropriate numbers and marks.
13933
13934 It is easy enough to see in the figure what the Y axis label should
13935 look like; but to say in words, and then to write a function
13936 definition to do the job is another matter. It is not quite true to
13937 say that we want a number and a tic every five lines: there are only
13938 three lines between the `1' and the `5' (lines 2, 3, and 4), but four
13939 lines between the `5' and the `10' (lines 6, 7, 8, and 9). It is
13940 better 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
13942 from the bottom and on every line that is a multiple of five.
13943
13944 What height should the label be?
13945 --------------------------------
13946
13947 The next issue is what height the label should be? Suppose the
13948 maximum height of tallest column of the graph is seven. Should the
13949 highest label on the Y axis be `5 -', and should the graph stick up
13950 above the label? Or should the highest label be `7 -', and mark the
13951 peak of the graph? Or should the highest label be `10 -', which is a
13952 multiple of five, and be higher than the topmost value of the graph?
13953
13954 The latter form is preferred. Most graphs are drawn within rectangles
13955 whose sides are an integral number of steps long--5, 10, 15, and so
13956 on for a step distance of five. But as soon as we decide to use a
13957 step height for the vertical axis, we discover that the simple
13958 expression in the varlist for computing the height is wrong. The
13959 expression is `(apply 'max numbers-list)'. This returns the precise
13960 height, not the maximum height plus whatever is necessary to round up
13961 to the nearest multiple of five. A more complex expression is
13962 required.
13963
13964 As usual in cases like this, a complex problem becomes simpler if it
13965 is divided into several smaller problems.
13966
13967 First, consider the case when the highest value of the graph is an
13968 integral multiple of five--when it is 5, 10, 15 ,or some higher
13969 multiple of five. We can use this value as the Y axis height.
13970
13971 A fairly simply way to determine whether a number is a multiple of
13972 five is to divide it by five and see if the division results in a
13973 remainder. If there is no remainder, the number is a multiple of
13974 five. Thus, seven divided by five has a remainder of two, and seven
13975 is not an integral multiple of five. Put in slightly different
13976 language, more reminiscent of the classroom, five goes into seven
13977 once, with a remainder of two. However, five goes into ten twice,
13978 with no remainder: ten is an integral multiple of five.
13979
13980 Side Trip: Compute a Remainder
13981 ------------------------------
13982
13983 In Lisp, the function for computing a remainder is `%'. The function
13984 returns the remainder of its first argument divided by its second
13985 argument. As it happens, `%' is a function in Emacs Lisp that you
13986 cannot discover using `apropos': you find nothing if you type `M-x
13987 apropos <RET> remainder <RET>'. The only way to learn of the
13988 existence of `%' is to read about it in a book such as this or in the
13989 Emacs Lisp sources. The `%' function is used in the code for
13990 `rotate-yank-pointer', which is described in an appendix. (*Note The
13991 Body of `rotate-yank-pointer': rotate-yk-ptr body.)
13992
13993 You can try the `%' function by evaluating the following two
13994 expressions:
13995
13996 (% 7 5)
13997
13998 (% 10 5)
13999
14000 The first expression returns 2 and the second expression returns 0.
14001
14002 To test whether the returned value is zero or some other number, we
14003 can use the `zerop' function. This function returns `t' if its
14004 argument, which must be a number, is zero.
14005
14006 (zerop (% 7 5))
14007 => nil
14008
14009 (zerop (% 10 5))
14010 => t
14011
14012 Thus, the following expression will return `t' if the height of the
14013 graph is evenly divisible by five:
14014
14015 (zerop (% height 5))
14016
14017 (The value of `height', of course, can be found from `(apply 'max
14018 numbers-list)'.)
14019
14020 On the other hand, if the value of `height' is not a multiple of
14021 five, we want to reset the value to the next higher multiple of five.
14022 This is straightforward arithmetic using functions with which we are
14023 already familiar. First, we divide the value of `height' by five to
14024 determine how many times five goes into the number. Thus, five goes
14025 into twelve twice. If we add one to this quotient and multiply by
14026 five, we will obtain the value of the next multiple of five that is
14027 larger than the height. Five goes into twelve twice. Add one to two,
14028 and multiply by five; the result is fifteen, which is the next
14029 multiple of five that is higher than twelve. The Lisp expression for
14030 this is:
14031
14032 (* (1+ (/ height 5)) 5)
14033
14034 For example, if you evaluate the following, the result is 15:
14035
14036 (* (1+ (/ 12 5)) 5)
14037
14038 All through this discussion, we have been using `five' as the value
14039 for spacing labels on the Y axis; but we may want to use some other
14040 value. For generality, we should replace `five' with a variable to
14041 which we can assign a value. The best name I can think of for this
14042 variable is `Y-axis-label-spacing'.
14043
14044 Using 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
14052 This expression returns the value of `height' itself if the height is
14053 an even multiple of the value of the `Y-axis-label-spacing' or else
14054 it computes and returns a value of `height' that is equal to the next
14055 higher multiple of the value of the `Y-axis-label-spacing'.
14056
14057 We 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
14076 computed once by the `(apply 'max numbers-list)' expression and then
14077 the resulting value of `height' is used to compute its final value.
14078 *Note The `let*' expression: fwd-para let, for more about `let*'.)
14079
14080 Construct a Y Axis Element
14081 --------------------------
14082
14083 When we print the vertical axis, we want to insert strings such as
14084 `5 -' and `10 - ' every five lines. Moreover, we want the numbers
14085 and dashes to line up, so shorter numbers must be padded with leading
14086 spaces. If some of the strings use two digit numbers, the strings
14087 with single digit numbers must include a leading blank space before
14088 the number.
14089
14090 To figure out the length of the number, the `length' function is
14091 used. But the `length' function works only with a string, not with a
14092 number. So the number has to be converted from being a number to
14093 being a string. This is done with the `number-to-string' function.
14094 For 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
14103 alternative name in various sources.)
14104
14105 In addition, in each label, each number is followed by a string such
14106 as ` - ', which we will call the `Y-axis-tic' marker. This variable
14107 is defined with `defvar':
14108
14109 (defvar Y-axis-tic " - "
14110 "String that follows number in a Y axis label.")
14111
14112 The length of the Y label is the sum of the length of the Y axis tic
14113 mark and the length of the number of the top of the graph.
14114
14115 (length (concat (number-to-string height) Y-axis-tic)))
14116
14117 This value will be calculated by the `print-graph' function in its
14118 varlist as `full-Y-label-width' and passed on. (Note that we did not
14119 think to include this in the varlist when we first proposed it.)
14120
14121 To make a complete vertical axis label, a tic mark is concatenated
14122 with a number; and the two together may be preceded by one or more
14123 spaces depending on how long the number is. The label consists of
14124 three parts: the (optional) leading spaces, the number, and the tic
14125 mark. The function is passed the value of the number for the specific
14126 row, 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
14144 The `Y-axis-element' function concatenates together the leading
14145 spaces, if any; the number, as a string; and the tic mark.
14146
14147 To figure out how many leading spaces the label will need, the
14148 function subtracts the actual length of the label--the length of the
14149 number plus the length of the tic mark--from the desired label width.
14150
14151 Blank spaces are inserted using the `make-string' function. This
14152 function takes two arguments: the first tells it how long the string
14153 will be and the second is a symbol for the character to insert, in a
14154 special format. The format is a question mark followed by a blank
14155 space, like this, `? '. *Note Character Type: (elisp)Character Type,
14156 for a description of the syntax for characters.
14157
14158 The `number-to-string' function is used in the concatenation
14159 expression, to convert the number to a string that is concatenated
14160 with the leading spaces and the tic mark.
14161
14162 Create a Y Axis Column
14163 ----------------------
14164
14165 The preceding functions provide all the tools needed to construct a
14166 function that generates a list of numbered and blank strings to insert
14167 as 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
14191 In this function, we start with the value of `height' and
14192 repetitively subtract one from its value. After each subtraction, we
14193 test to see whether the value is an integral multiple of the
14194 `Y-axis-label-spacing'. If it is, we construct a numbered label
14195 using the `Y-axis-element' function; if not, we construct a blank
14196 label using the `make-string' function. The base line consists of
14197 the number one followed by a tic mark.
14198
14199 The Not Quite Final Version of `print-Y-axis'
14200 ---------------------------------------------
14201
14202 The 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
14219 The `print-Y-axis' uses the `insert-rectangle' function to insert the
14220 Y axis labels created by the `Y-axis-column' function. In addition,
14221 it places point at the correct position for printing the body of the
14222 graph.
14223
14224 You 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
14248 Emacs will print labels vertically, the top one being `10 - '. (The
14249 `print-graph' function will pass the value of `height-of-top-line',
14250 which in this case would end up as 15.)
14251
14252 The `print-X-axis' Function
14253 ===========================
14254
14255 X axis labels are much like Y axis labels, except that the tics are
14256 on a line above the numbers. Labels should look like this:
14257
14258 | | | |
14259 1 5 10 15
14260
14261 The first tic is under the first column of the graph and is preceded
14262 by several blank spaces. These spaces provide room in rows above for
14263 the Y axis labels. The second, third, fourth, and subsequent tics
14264 are all spaced equally, according to the value of
14265 `X-axis-label-spacing'.
14266
14267 The second row of the X axis consists of numbers, preceded by several
14268 blank spaces and also separated according to the value of the variable
14269 `X-axis-label-spacing'.
14270
14271 The value of the variable `X-axis-label-spacing' should itself be
14272 measured in units of `symbol-width', since you may want to change the
14273 width of the symbols that you are using to print the body of the
14274 graph without changing the ways the graph is labelled.
14275
14276 Similarities and differences
14277 ----------------------------
14278
14279 The `print-X-axis' function is constructed in more or less the same
14280 fashion as the `print-Y-axis' function except that it has two lines:
14281 the line of tic marks and the numbers. We will write a separate
14282 function to print each line and then combine them within the
14283 `print-X-axis' function.
14284
14285 This 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
14297 X Axis Tic Marks
14298 ----------------
14299
14300 The first function should print the X axis tic marks. We must specify
14301 the 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'.
14309 The `boundp' predicate checks whether it has already been set;
14310 `boundp' returns `nil' if it has not. If `graph-blank' were unbound
14311 and we did not use this conditional construction, in GNU Emacs 21, we
14312 would enter the debugger and see an error message saying
14313 `Debugger entered--Lisp error: (void-variable graph-blank)'.)
14314
14315 Here 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
14320 The goal is to make a line that looks like this:
14321
14322 | | | |
14323
14324 The first tic is indented so that it is under the first column, which
14325 is indented to provide space for the Y axis labels.
14326
14327 A tic element consists of the blank spaces that stretch from one tic
14328 to the next plus a tic symbol. The number of blanks is determined by
14329 the width of the tic symbol and the `X-axis-label-spacing'.
14330
14331 The 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
14345 Next, we determine how many blanks are needed to indent the first tic
14346 mark 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
14349 The 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
14356 We also need to determine the length of the horizontal axis, which is
14357 the length of the numbers list, and the number of tics in the
14358 horizontal 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
14373 All this leads us directly to the function for printing the X axis
14374 tic 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
14394 The line of numbers is equally straightforward:
14395
14396 First, we create a numbered element with blank spaces before each
14397 number:
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
14407 Next, we create the function to print the numbered line, starting with
14408 the 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
14429 Finally, we need to write the `print-X-axis' that uses
14430 `print-X-axis-tic-line' and `print-X-axis-numbered-line'.
14431
14432 The function must determine the local values of the variables used by
14433 both `print-X-axis-tic-line' and `print-X-axis-numbered-line', and
14434 then it must call them. Also, it must print the carriage return that
14435 separates the two lines.
14436
14437 The function consists of a varlist that specifies five local
14438 variables, 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
14464 You 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
14487 Emacs will print the horizontal axis like this:
14488
14489 | | | | |
14490 1 5 10 15 20
14491
14492 Printing the Whole Graph
14493 ========================
14494
14495 Now we are nearly ready to print the whole graph.
14496
14497 The function to print the graph with the proper labels follows the
14498 outline we created earlier (*note A Graph with Labelled Axes: Full
14499 Graph.), but with additions.
14500
14501 Here 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
14511 Changes for the Final Version
14512 -----------------------------
14513
14514 The final version is different from what we planned in two ways:
14515 first, it contains additional values calculated once in the varlist;
14516 second, it carries an option to specify the labels' increment per row.
14517 This latter feature turns out to be essential; otherwise, a graph may
14518 have more rows than fit on a display or on a sheet of paper.
14519
14520 This new feature requires a change to the `Y-axis-column' function,
14521 to 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
14557 The values for the maximum height of graph and the width of a symbol
14558 are 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
14581 Finally, 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
14617 Testing `print-graph'
14618 ---------------------
14619
14620 We 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
14639 Emacs 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
14655 On the other hand, if you pass `print-graph' a `vertical-step' value
14656 of 2, by evaluating this expression:
14657
14658 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
14659
14660 The 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
14677 feature? If you think it is a bug, and should be a `1' instead, (or
14678 even a `0'), you can modify the sources.)
14679
14680 Graphing Numbers of Words and Symbols
14681 -------------------------------------
14682
14683 Now for the graph for which all this code was written: a graph that
14684 shows how many function definitions contain fewer than 10 words and
14685 symbols, how many contain between 10 and 19 words and symbols, how
14686 many contain between 20 and 29 words and symbols, and so on.
14687
14688 This is a multi-step process. First make sure you have loaded all the
14689 requisite code.
14690
14691 It is a good idea to reset the value of `top-of-ranges' in case you
14692 have 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
14702 Next create a list of the number of words and symbols in each range.
14703
14704 Evaluate 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
14715 On my machine, this takes about an hour. It looks though 303 Lisp
14716 files in my copy of Emacs version 19.23. After all that computing,
14717 the `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
14722 This means that my copy of Emacs has 537 function definitions with
14723 fewer than 10 words or symbols in them, 1,027 function definitions
14724 with 10 to 19 words or symbols in them, 955 function definitions with
14725 20 to 29 words or symbols in them, and so on.
14726
14727 Clearly, just by looking at this list we can see that most function
14728 definitions contain ten to thirty words and symbols.
14729
14730 Now for printing. We do _not_ want to print a graph that is 1,030
14731 lines high ... Instead, we should print a graph that is fewer than
14732 twenty-five lines high. A graph that height can be displayed on
14733 almost any monitor, and easily printed on a sheet of paper.
14734
14735 This means that each value in `list-for-graph' must be reduced to
14736 one-fiftieth its present value.
14737
14738 Here is a short function to do just that, using two functions we have
14739 not 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
14745 A `lambda' Expression: Useful Anonymity
14746 ---------------------------------------
14747
14748 `lambda' is the symbol for an anonymous function, a function without
14749 a name. Every time you use an anonymous function, you need to
14750 include its whole body.
14751
14752 Thus,
14753
14754 (lambda (arg) (/ arg 50))
14755
14756 is a function definition that says `return the value resulting from
14757 dividing whatever is passed to me as `arg' by 50'.
14758
14759 Earlier, for example, we had a function `multiply-by-seven'; it
14760 multiplied its argument by 7. This function is similar, except it
14761 divides its argument by 50; and, it has no name. The anonymous
14762 equivalent of `multiply-by-seven' is:
14763
14764 (lambda (number) (* 7 number))
14765
14766 (*Note The `defun' Special Form: defun.)
14767
14768 If we want to multiply 3 by 7, we can write:
14769
14770 (multiply-by-seven 3)
14771 \_______________/ ^
14772 | |
14773 function argument
14774
14775
14776
14777 This expression returns 21.
14778
14779 Similarly, we can write:
14780
14781 ((lambda (number) (* 7 number)) 3)
14782 \____________________________/ ^
14783 | |
14784 anonymous function argument
14785
14786
14787
14788 If 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
14797 This expression returns 2. The 100 is passed to the function, which
14798 divides 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
14802 Calculus.
14803
14804 The `mapcar' Function
14805 ---------------------
14806
14807 `mapcar' is a function that calls its first argument with each
14808 element of its second argument, in turn. The second argument must be
14809 a sequence.
14810
14811 The `map' part of the name comes from the mathematical phrase,
14812 `mapping over a domain', meaning to apply a function to each of the
14813 elements in a domain. The mathematical phrase is based on the
14814 metaphor of a surveyor walking, one step at a time, over an area he is
14815 mapping. And `car', of course, comes from the Lisp notion of the
14816 first of a list.
14817
14818 For example,
14819
14820 (mapcar '1+ '(2 4 6))
14821 => (3 5 7)
14822
14823 The function `1+' which adds one to its argument, is executed on
14824 _each_ element of the list, and a new list is returned.
14825
14826 Contrast this with `apply', which applies its first argument to all
14827 the remaining. (*Note Readying a Graph: Readying a Graph, for a
14828 explanation of `apply'.)
14829
14830 In the definition of `one-fiftieth', the first argument is the
14831 anonymous function:
14832
14833 (lambda (arg) (/ arg 50))
14834
14835 and the second argument is `full-range', which will be bound to
14836 `list-for-graph'.
14837
14838 The 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
14845 Using the `one-fiftieth' function, we can generate a list in which
14846 each 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
14852 The 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
14857 This, we are almost ready to print! (We also notice the loss of
14858 information: many of the higher ranges are 0, meaning that fewer than
14859 50 defuns had that many words or symbols--but not necessarily meaning
14860 that none had that many words or symbols.)
14861
14862 Another Bug ... Most Insidious
14863 ------------------------------
14864
14865 I 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
14867 a `horizontal-step' option. The `top-of-range' scale goes from 10 to
14868 300 by tens. But the `print-graph' function will print only by ones.
14869
14870 This is a classic example of what some consider the most insidious
14871 type of bug, the bug of omission. This is not the kind of bug you can
14872 find by studying the code, for it is not in the code; it is an omitted
14873 feature. Your best actions are to try your program early and often;
14874 and try to arrange, as much as you can, to write code that is easy to
14875 understand and easy to change. Try to be aware, whenever you can,
14876 that whatever you have written, _will_ be rewritten, if not soon,
14877 eventually. A hard maxim to follow.
14878
14879 It is the `print-X-axis-numbered-line' function that needs the work;
14880 and then the `print-X-axis' and the `print-graph' functions need to
14881 be adapted. Not much needs to be done; there is one nicety: the
14882 numbers ought to line up under the tic marks. This takes a little
14883 thought.
14884
14885 Here 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
14918 If 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
14920 this in a printed book, you can see the changed lines here (the full
14921 text 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
14991 The Printed Graph
14992 -----------------
14993
14994 When made and installed, you can call the `print-graph' command like
14995 this:
14996
14997 (print-graph fiftieth-list-for-graph 50 10)
14998
14999 Here 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
15028 The largest group of functions contain 10 - 19 words and symbols each.
15029
15030 GNU 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
15390 Index
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''.
15413 Accumulate, type of recursive pattern:
15414 See ``Recursive Pattern: _accumulate_''.
15415 add-hook:
15416 See ``Text and Auto Fill Mode''.
15417 and <1>:
15418 See ``The `let*' expression''.
15419 and:
15420 See ``The `kill-new' function''.
15421 and, introduced:
15422 See ``The `kill-new' function''.
15423 Anonymous function:
15424 See ``A `lambda' Expression: Useful Anonymity''.
15425 append-to-buffer:
15426 See ``The Definition of `append-to-buffer'''.
15427 apply:
15428 See ``Printing the Columns of a Graph''.
15429 apropos:
15430 See ``Printing the Columns of a Graph''.
15431 Argument as local variable:
15432 See ``Putting the function definition together''.
15433 argument defined:
15434 See ``Arguments''.
15435 argument list defined:
15436 See ``The `defun' Special Form''.
15437 Argument, wrong type of:
15438 See ``Using the Wrong Type Object as an Argument''.
15439 Arguments:
15440 See ``Arguments''.
15441 Arguments' data types:
15442 See ``Arguments' Data Types''.
15443 Arguments, variable number of:
15444 See ``Variable Number of Arguments''.
15445 Asterisk for read-only buffer:
15446 See ``A Read-only Buffer''.
15447 Auto Fill mode turned on:
15448 See ``Text and Auto Fill Mode''.
15449 autoload:
15450 See ``Autoloading''.
15451 Automatic mode selection:
15452 See ``Text and Auto Fill Mode''.
15453 Axis, print horizontal:
15454 See ``The `print-X-axis' Function''.
15455 Axis, print vertical:
15456 See ``The `print-Y-axis' Function''.
15457 beginning-of-buffer:
15458 See ``Complete Definition of `beginning-of-buffer'''.
15459 bind defined:
15460 See ``Setting the Value of a Variable''.
15461 body defined:
15462 See ``The `defun' Special Form''.
15463 Body of graph:
15464 See ``Readying a Graph''.
15465 Buffer size:
15466 See ``Buffer Size and the Location of Point''.
15467 Buffer, history of word:
15468 See ``Buffer Names''.
15469 buffer-file-name:
15470 See ``Buffer Names''.
15471 buffer-menu, bound to key:
15472 See ``Some Keybindings''.
15473 buffer-name:
15474 See ``Buffer Names''.
15475 Bug, most insidious type:
15476 See ``Another Bug ... Most Insidious''.
15477 Building robots:
15478 See ``Building Robots: Extending the Metaphor''.
15479 Building Tags in the Emacs sources:
15480 See ``Create Your Own `TAGS' File''.
15481 Byte compiling:
15482 See ``Byte Compiling''.
15483 C language primitives:
15484 See ``An Aside about Primitive Functions''.
15485 C, a digression into:
15486 See ``Digression into C''.
15487 call defined:
15488 See ``Switching Buffers''.
15489 cancel-debug-on-entry:
15490 See ```debug-on-entry'''.
15491 car, introduced:
15492 See ```car', `cdr', `cons': Fundamental Functions''.
15493 cdr, introduced:
15494 See ```car', `cdr', `cons': Fundamental Functions''.
15495 Changing a function definition:
15496 See ``Change a Function Definition''.
15497 Chest of Drawers, metaphor for a symbol:
15498 See ``Symbols as a Chest of Drawers''.
15499 Clipping text:
15500 See ``Cutting and Storing Text''.
15501 Code installation:
15502 See ``Install Code Permanently''.
15503 command defined:
15504 See ``How to Evaluate''.
15505 Comments in Lisp code:
15506 See ``Change a Function Definition''.
15507 Common Lisp:
15508 See ``Lisp History''.
15509 compare-windows:
15510 See ``Some Keybindings''.
15511 concat:
15512 See ``Arguments' Data Types''.
15513 cond:
15514 See ``Recursion Example Using `cond'''.
15515 condition-case:
15516 See ```condition-case'''.
15517 Conditional 'twixt two versions of Emacs:
15518 See ``A Simple Extension: `line-to-top-of-window'''.
15519 Conditional with if:
15520 See ``The `if' Special Form''.
15521 cons, example:
15522 See ``The `kill-new' function''.
15523 cons, introduced:
15524 See ```cons'''.
15525 copy-region-as-kill:
15526 See ```copy-region-as-kill'''.
15527 copy-to-buffer:
15528 See ``The Definition of `copy-to-buffer'''.
15529 Count words recursively:
15530 See ``Count Words Recursively''.
15531 count-words-in-defun:
15532 See ``The `count-words-in-defun' Function''.
15533 count-words-region:
15534 See ``The `count-words-region' Function''.
15535 Counting:
15536 See ``Counting''.
15537 Counting words in a defun <1>:
15538 See ``The `count-words-in-defun' Function''.
15539 Counting words in a defun:
15540 See ``Counting Words in a `defun'''.
15541 current-buffer:
15542 See ``Getting Buffers''.
15543 Customizing your .emacs file:
15544 See ``Your `.emacs' File''.
15545 Cutting and storing text:
15546 See ``Cutting and Storing Text''.
15547 Data types:
15548 See ``Arguments' Data Types''.
15549 debug:
15550 See ```debug'''.
15551 debug-on-entry:
15552 See ```debug-on-entry'''.
15553 debug-on-quit:
15554 See ```debug-on-quit' and `(debug)'''.
15555 debugging:
15556 See ``Debugging''.
15557 default-mode-line-format:
15558 See ``A Modified Mode Line''.
15559 default.el init file:
15560 See ``Site-wide Initialization Files''.
15561 defcustom:
15562 See ``Specifying Variables using `defcustom'''.
15563 Deferment in recursion:
15564 See ``Recursion without Deferments''.
15565 Defermentless solution:
15566 See ``No Deferment Solution''.
15567 Definition installation:
15568 See ``Install a Function Definition''.
15569 Definition writing:
15570 See ``How To Write Function Definitions''.
15571 Definition, how to change:
15572 See ``Change a Function Definition''.
15573 defun:
15574 See ``The `defun' Special Form''.
15575 defvar:
15576 See ``Initializing a Variable with `defvar'''.
15577 defvar for a user customizable variable:
15578 See ```defvar' and an asterisk''.
15579 defvar with an asterisk:
15580 See ```defvar' and an asterisk''.
15581 delete-and-extract-region <1>:
15582 See ``Digression into C''.
15583 delete-and-extract-region:
15584 See ```delete-and-extract-region'''.
15585 Deleting text:
15586 See ``Cutting and Storing Text''.
15587 describe-function:
15588 See ``A Simplified `beginning-of-buffer' Definition''.
15589 describe-function, introduced:
15590 See ``Finding More Information''.
15591 Digression into C:
15592 See ``Digression into C''.
15593 directory-files:
15594 See ``Making a List of Files''.
15595 Division:
15596 See ``What happens in a large buffer''.
15597 dolist:
15598 See ``The `dolist' Macro''.
15599 dotimes:
15600 See ``The `dotimes' Macro''.
15601 Drawers, Chest of, metaphor for a symbol:
15602 See ``Symbols as a Chest of Drawers''.
15603 Duplicated words function:
15604 See ``The `the-the' Function''.
15605 edebug:
15606 See ``The `edebug' Source Level Debugger''.
15607 edit-options:
15608 See ```defvar' and an asterisk''.
15609 Else:
15610 See ``If-then-else Expressions''.
15611 Emacs version, choosing:
15612 See ``A Simple Extension: `line-to-top-of-window'''.
15613 empty list defined:
15614 See ``Lisp Atoms''.
15615 empty string defined:
15616 See ``Review''.
15617 eobp:
15618 See ``Between paragraphs''.
15619 eq:
15620 See ``Review''.
15621 eq (example of use):
15622 See ```last-command' and `this-command'''.
15623 equal:
15624 See ``Review''.
15625 Erasing text:
15626 See ``Cutting and Storing Text''.
15627 error:
15628 See ``The Body of `rotate-yank-pointer'''.
15629 Error for symbol without function:
15630 See ``Error Message for a Symbol Without a Function''.
15631 Error for symbol without value:
15632 See ``Error Message for a Symbol Without a Value''.
15633 Error message generation:
15634 See ``Generate an Error Message''.
15635 etags:
15636 See ``Create Your Own `TAGS' File''.
15637 evaluate defined:
15638 See ``Run a Program''.
15639 Evaluating inner lists:
15640 See ``Evaluating Inner Lists''.
15641 Evaluation:
15642 See ``Evaluation''.
15643 Evaluation practice:
15644 See ``Practicing Evaluation''.
15645 Every, type of recursive pattern:
15646 See ``Recursive Pattern: _every_''.
15647 Example variable, fill-column:
15648 See ```fill-column', an Example Variable''.
15649 expression defined:
15650 See ``Lisp Atoms''.
15651 Falsehood and truth in Emacs Lisp:
15652 See ``Truth and Falsehood in Emacs Lisp''.
15653 FDL, GNU Free Documentation License:
15654 See ``GNU Free Documentation License''.
15655 files-in-below-directory:
15656 See ``Making a List of Files''.
15657 fill-column, an example variable:
15658 See ```fill-column', an Example Variable''.
15659 Find a File:
15660 See ``Find a File''.
15661 Find function documentation:
15662 See ``Finding More Information''.
15663 Find source of function:
15664 See ``Finding More Information''.
15665 find-tags:
15666 See ``Finding More Information''.
15667 Flowers in a field:
15668 See ``Lisp Lists''.
15669 Focusing attention (narrowing):
15670 See ``Narrowing and Widening''.
15671 form defined:
15672 See ``Lisp Atoms''.
15673 Formatting convention:
15674 See ```save-excursion' in `append-to-buffer'''.
15675 Formatting help:
15676 See ``GNU Emacs Helps You Type Lists''.
15677 forward-paragraph:
15678 See ```forward-paragraph': a Goldmine of Functions''.
15679 forward-sentence:
15680 See ```forward-sentence'''.
15681 function defined:
15682 See ``Generate an Error Message''.
15683 function definition defined:
15684 See ``The `defun' Special Form''.
15685 Function definition installation:
15686 See ``Install a Function Definition''.
15687 Function definition writing:
15688 See ``How To Write Function Definitions''.
15689 Function definition, how to change:
15690 See ``Change a Function Definition''.
15691 Functions, primitive:
15692 See ``An Aside about Primitive Functions''.
15693 Generate an error message:
15694 See ``Generate an Error Message''.
15695 Getting a buffer:
15696 See ``Getting Buffers''.
15697 Global set key:
15698 See ``Some Keybindings''.
15699 global-set-key:
15700 See ``Some Keybindings''.
15701 global-unset-key:
15702 See ``Some Keybindings''.
15703 Graph prototype:
15704 See ``Readying a Graph''.
15705 Graph, printing all:
15706 See ``Printing the Whole Graph''.
15707 graph-body-print:
15708 See ``The `graph-body-print' Function''.
15709 graph-body-print Final version.:
15710 See ``Changes for the Final Version''.
15711 Handling the kill ring:
15712 See ``Handling the Kill Ring''.
15713 Help typing lists:
15714 See ``GNU Emacs Helps You Type Lists''.
15715 Horizontal axis printing:
15716 See ``The `print-X-axis' Function''.
15717 if:
15718 See ``The `if' Special Form''.
15719 if-part defined:
15720 See ```if' in more detail''.
15721 indent-tabs-mode:
15722 See ``Indent Tabs Mode''.
15723 Indentation for formatting:
15724 See ```save-excursion' in `append-to-buffer'''.
15725 Initialization file:
15726 See ``Your `.emacs' File''.
15727 Initializing a variable:
15728 See ``Initializing a Variable with `defvar'''.
15729 Inner list evaluation:
15730 See ``Evaluating Inner Lists''.
15731 insert-buffer:
15732 See ``The Definition of `insert-buffer'''.
15733 insert-buffer-substring:
15734 See ``An Overview of `append-to-buffer'''.
15735 Insidious type of bug:
15736 See ``Another Bug ... Most Insidious''.
15737 Install a Function Definition:
15738 See ``Install a Function Definition''.
15739 Install code permanently:
15740 See ``Install Code Permanently''.
15741 interactive:
15742 See ``Make a Function Interactive''.
15743 interactive function defined:
15744 See ``How to Evaluate''.
15745 Interactive functions:
15746 See ``Make a Function Interactive''.
15747 Interactive options:
15748 See ``Different Options for `interactive'''.
15749 interactive, example use of:
15750 See ``The Interactive Expression in `insert-buffer'''.
15751 Interpreter, Lisp, explained:
15752 See ``Run a Program''.
15753 Interpreter, what it does:
15754 See ``The Lisp Interpreter''.
15755 Keep, type of recursive pattern:
15756 See ``Recursive Pattern: _keep_''.
15757 Key setting globally:
15758 See ``Some Keybindings''.
15759 Key unbinding:
15760 See ``Some Keybindings''.
15761 Keymaps:
15762 See ``Keymaps''.
15763 Keyword:
15764 See ``Optional Arguments''.
15765 Kill ring handling:
15766 See ``Handling the Kill Ring''.
15767 Kill ring overview:
15768 See ``Kill Ring Overview''.
15769 kill-append:
15770 See ``The `kill-append' function''.
15771 kill-new:
15772 See ``The `kill-new' function''.
15773 kill-region:
15774 See ```kill-region'''.
15775 Killing text:
15776 See ``Cutting and Storing Text''.
15777 lambda:
15778 See ``A `lambda' Expression: Useful Anonymity''.
15779 length:
15780 See ``Find the Length of a List: `length'''.
15781 lengths-list-file:
15782 See ```lengths-list-file' in Detail''.
15783 lengths-list-many-files:
15784 See ``Determine the lengths of `defuns'''.
15785 let:
15786 See ```let'''.
15787 let expression sample:
15788 See ``Sample `let' Expression''.
15789 let expression, parts of:
15790 See ``The Parts of a `let' Expression''.
15791 let variables uninitialized:
15792 See ``Uninitialized Variables in a `let' Statement''.
15793 Library, as term for `file':
15794 See ``Finding More Information''.
15795 line-to-top-of-window:
15796 See ``A Simple Extension: `line-to-top-of-window'''.
15797 Lisp Atoms:
15798 See ``Lisp Atoms''.
15799 Lisp history:
15800 See ``Lisp History''.
15801 Lisp interpreter, explained:
15802 See ``Run a Program''.
15803 Lisp interpreter, what it does:
15804 See ``The Lisp Interpreter''.
15805 Lisp Lists:
15806 See ``Lisp Lists''.
15807 Lisp macro:
15808 See ```delete-and-extract-region'''.
15809 list-buffers, rebound:
15810 See ``Some Keybindings''.
15811 Lists in a computer:
15812 See ``How Lists are Implemented''.
15813 load-library:
15814 See ``Loading Files''.
15815 load-path:
15816 See ``Loading Files''.
15817 Loading files:
15818 See ``Loading Files''.
15819 local variable defined:
15820 See ```let' Prevents Confusion''.
15821 Local variables list, per-buffer,:
15822 See ``Text and Auto Fill Mode''.
15823 Location of point:
15824 See ``Buffer Size and the Location of Point''.
15825 looking-at:
15826 See ``Between paragraphs''.
15827 Loops:
15828 See ```while'''.
15829 Loops and recursion:
15830 See ``Loops and Recursion''.
15831 Maclisp:
15832 See ``Lisp History''.
15833 Macro, lisp:
15834 See ```delete-and-extract-region'''.
15835 Mail aliases:
15836 See ``Mail Aliases''.
15837 make tags:
15838 See ``Create Your Own `TAGS' File''.
15839 make-string:
15840 See ``Construct a Y Axis Element''.
15841 mapcar:
15842 See ``The `mapcar' Function''.
15843 mark:
15844 See ```save-excursion'''.
15845 mark-whole-buffer:
15846 See ``The Definition of `mark-whole-buffer'''.
15847 match-beginning:
15848 See ``No fill prefix''.
15849 max:
15850 See ``Printing the Columns of a Graph''.
15851 message:
15852 See ``The `message' Function''.
15853 min:
15854 See ``Printing the Columns of a Graph''.
15855 Mode line format:
15856 See ``A Modified Mode Line''.
15857 Mode selection, automatic:
15858 See ``Text and Auto Fill Mode''.
15859 Motion by sentence and paragraph:
15860 See ``Regular Expression Searches''.
15861 Narrowing:
15862 See ``Narrowing and Widening''.
15863 narrowing defined:
15864 See ``Buffer Size and the Location of Point''.
15865 nil:
15866 See ``Truth and Falsehood in Emacs Lisp''.
15867 nil, history of word:
15868 See ``Buffer Names''.
15869 No deferment solution:
15870 See ``No Deferment Solution''.
15871 nreverse:
15872 See ``Counting function definitions''.
15873 nth:
15874 See ```nth'''.
15875 nthcdr <1>:
15876 See ```copy-region-as-kill'''.
15877 nthcdr:
15878 See ```nthcdr'''.
15879 nthcdr, example:
15880 See ``The `kill-new' function''.
15881 number-to-string:
15882 See ``Construct a Y Axis Element''.
15883 occur:
15884 See ``Some Keybindings''.
15885 optional:
15886 See ``Optional Arguments''.
15887 Optional arguments:
15888 See ``Optional Arguments''.
15889 Options for interactive:
15890 See ``Different Options for `interactive'''.
15891 or:
15892 See ``The `or' in the Body''.
15893 other-buffer:
15894 See ``Getting Buffers''.
15895 Paragraphs, movement by:
15896 See ``Regular Expression Searches''.
15897 Parts of a Recursive Definition:
15898 See ``The Parts of a Recursive Definition''.
15899 Parts of let expression:
15900 See ``The Parts of a `let' Expression''.
15901 Passing information to functions:
15902 See ``Arguments''.
15903 Pasting text:
15904 See ``Yanking Text Back''.
15905 Patterns, searching for:
15906 See ``Regular Expression Searches''.
15907 Per-buffer, local variables list:
15908 See ``Text and Auto Fill Mode''.
15909 Permanent code installation:
15910 See ``Install Code Permanently''.
15911 point:
15912 See ```save-excursion'''.
15913 point defined:
15914 See ``Buffer Size and the Location of Point''.
15915 Point location:
15916 See ``Buffer Size and the Location of Point''.
15917 Point, mark, buffer preservation:
15918 See ```save-excursion'''.
15919 Practicing evaluation:
15920 See ``Practicing Evaluation''.
15921 Preserving point, mark, and buffer:
15922 See ```save-excursion'''.
15923 Primitive functions:
15924 See ``An Aside about Primitive Functions''.
15925 Primitives written in C:
15926 See ``An Aside about Primitive Functions''.
15927 Print horizontal axis:
15928 See ``The `print-X-axis' Function''.
15929 Print vertical axis:
15930 See ``The `print-Y-axis' Function''.
15931 print-elements-of-list:
15932 See ``An Example: `print-elements-of-list'''.
15933 print-elements-recursively:
15934 See ``Recursion with a List''.
15935 print-graph Final version.:
15936 See ``Changes for the Final Version''.
15937 print-graph varlist:
15938 See ``The `print-graph' Varlist''.
15939 print-X-axis:
15940 See ``X Axis Tic Marks''.
15941 print-X-axis-numbered-line:
15942 See ``X Axis Tic Marks''.
15943 print-X-axis-tic-line:
15944 See ``X Axis Tic Marks''.
15945 print-Y-axis:
15946 See ``The Not Quite Final Version of `print-Y-axis'''.
15947 Printing the whole graph:
15948 See ``Printing the Whole Graph''.
15949 prog1:
15950 See ``Between paragraphs''.
15951 progn:
15952 See ``The `progn' Special Form''.
15953 Program, running one:
15954 See ``Run a Program''.
15955 Prototype graph:
15956 See ``Readying a Graph''.
15957 re-search-forward:
15958 See ``The `re-search-forward' Function''.
15959 Read-only buffer:
15960 See ``A Read-only Buffer''.
15961 Readying a graph:
15962 See ``Readying a Graph''.
15963 Rebinding keys:
15964 See ``Keymaps''.
15965 Recursion:
15966 See ``Recursion''.
15967 Recursion and loops:
15968 See ``Loops and Recursion''.
15969 Recursion without Deferments:
15970 See ``Recursion without Deferments''.
15971 Recursive Definition Parts:
15972 See ``The Parts of a Recursive Definition''.
15973 Recursive pattern: accumulate:
15974 See ``Recursive Pattern: _accumulate_''.
15975 Recursive pattern: every:
15976 See ``Recursive Pattern: _every_''.
15977 Recursive pattern: keep:
15978 See ``Recursive Pattern: _keep_''.
15979 Recursive Patterns:
15980 See ``Recursive Patterns''.
15981 recursive-count-words:
15982 See ``Count Words Recursively''.
15983 recursive-graph-body-print:
15984 See ``The `recursive-graph-body-print' Function''.
15985 recursive-lengths-list-many-files:
15986 See ``Recursively Count Words in Different Files''.
15987 Recursively counting words:
15988 See ``Count Words Recursively''.
15989 regexp-quote:
15990 See ``The `let*' expression''.
15991 Region, what it is:
15992 See ```save-excursion'''.
15993 Regular expression searches:
15994 See ``Regular Expression Searches''.
15995 Regular expressions for word counting:
15996 See ``Counting: Repetition and Regexps''.
15997 Remainder function, %:
15998 See ``Side Trip: Compute a Remainder''.
15999 Repetition (loops):
16000 See ``Loops and Recursion''.
16001 Repetition for word counting:
16002 See ``Counting: Repetition and Regexps''.
16003 Retrieving text:
16004 See ``Yanking Text Back''.
16005 reverse:
16006 See ``Counting function definitions''.
16007 Ring, making a list like a:
16008 See ``Handling the Kill Ring''.
16009 Robots, building:
16010 See ``Building Robots: Extending the Metaphor''.
16011 rotate-yank-pointer <1>:
16012 See ``The `rotate-yank-pointer' Function''.
16013 rotate-yank-pointer:
16014 See ``Yanking Text Back''.
16015 Run a program:
16016 See ``Run a Program''.
16017 Sample let expression:
16018 See ``Sample `let' Expression''.
16019 save-excursion:
16020 See ```save-excursion'''.
16021 save-restriction:
16022 See ``The `save-restriction' Special Form''.
16023 search-forward:
16024 See ``The `search-forward' Function''.
16025 Searches, illustrating:
16026 See ``Regular Expression Searches''.
16027 sentence-end:
16028 See ``The Regular Expression for `sentence-end'''.
16029 Sentences, movement by:
16030 See ``Regular Expression Searches''.
16031 set:
16032 See ``Using `set'''.
16033 set-buffer:
16034 See ``Switching Buffers''.
16035 setcar:
16036 See ```setcar'''.
16037 setcdr:
16038 See ```setcdr'''.
16039 setcdr, example:
16040 See ``The `kill-new' function''.
16041 setq:
16042 See ``Using `setq'''.
16043 Setting a key globally:
16044 See ``Some Keybindings''.
16045 Setting value of variable:
16046 See ``Setting the Value of a Variable''.
16047 side effect defined:
16048 See ``Evaluation''.
16049 Simple extension in .emacs file:
16050 See ``A Simple Extension: `line-to-top-of-window'''.
16051 simplified-beginning-of-buffer:
16052 See ``A Simplified `beginning-of-buffer' Definition''.
16053 site-init.el init file:
16054 See ``Site-wide Initialization Files''.
16055 site-load.el init file:
16056 See ``Site-wide Initialization Files''.
16057 Size of buffer:
16058 See ``Buffer Size and the Location of Point''.
16059 Solution without deferment:
16060 See ``No Deferment Solution''.
16061 sort:
16062 See ``Sorting Lists''.
16063 Source level debugger:
16064 See ``The `edebug' Source Level Debugger''.
16065 Special form:
16066 See ``Complications''.
16067 Special form of defun:
16068 See ``The `defun' Special Form''.
16069 Storing and cutting text:
16070 See ``Cutting and Storing Text''.
16071 string defined:
16072 See ``Lisp Atoms''.
16073 switch-to-buffer:
16074 See ``Switching Buffers''.
16075 Switching to a buffer:
16076 See ``Switching Buffers''.
16077 Symbol names:
16078 See ``Symbol Names and Function Definitions''.
16079 Symbol without function error:
16080 See ``Error Message for a Symbol Without a Function''.
16081 Symbol without value error:
16082 See ``Error Message for a Symbol Without a Value''.
16083 Symbolic expressions, introduced:
16084 See ``Lisp Atoms''.
16085 Symbols as a Chest of Drawers:
16086 See ``Symbols as a Chest of Drawers''.
16087 Syntax categories and tables:
16088 See ``What Constitutes a Word or Symbol?''.
16089 Tabs, preventing:
16090 See ``Indent Tabs Mode''.
16091 TAGS file, create own:
16092 See ``Create Your Own `TAGS' File''.
16093 Tags in the Emacs sources:
16094 See ``Create Your Own `TAGS' File''.
16095 TAGS table, specifying:
16096 See ``Finding More Information''.
16097 Text between double quotation marks:
16098 See ``Lisp Atoms''.
16099 Text Mode turned on:
16100 See ``Text and Auto Fill Mode''.
16101 Text retrieval:
16102 See ``Yanking Text Back''.
16103 the-the:
16104 See ``The `the-the' Function''.
16105 then-part defined:
16106 See ```if' in more detail''.
16107 top-of-ranges:
16108 See ``Counting function definitions''.
16109 triangle-bugged:
16110 See ```debug'''.
16111 triangle-recursively:
16112 See ``Recursion in Place of a Counter''.
16113 Truth and falsehood in Emacs Lisp:
16114 See ``Truth and Falsehood in Emacs Lisp''.
16115 Types of data:
16116 See ``Arguments' Data Types''.
16117 Unbinding key:
16118 See ``Some Keybindings''.
16119 Uninitialized let variables:
16120 See ``Uninitialized Variables in a `let' Statement''.
16121 Variable initialization:
16122 See ``Initializing a Variable with `defvar'''.
16123 Variable number of arguments:
16124 See ``Variable Number of Arguments''.
16125 Variable, example of, fill-column:
16126 See ```fill-column', an Example Variable''.
16127 Variable, setting value:
16128 See ``Setting the Value of a Variable''.
16129 Variables:
16130 See ``Variables''.
16131 varlist defined:
16132 See ``The Parts of a `let' Expression''.
16133 Version of Emacs, choosing:
16134 See ``A Simple Extension: `line-to-top-of-window'''.
16135 Vertical axis printing:
16136 See ``The `print-Y-axis' Function''.
16137 what-line:
16138 See ```what-line'''.
16139 while:
16140 See ```while'''.
16141 Whitespace in lists:
16142 See ``Whitespace in Lists''.
16143 Whole graph printing:
16144 See ``Printing the Whole Graph''.
16145 Widening:
16146 See ``Narrowing and Widening''.
16147 Widening, example of:
16148 See ```what-line'''.
16149 Word counting in a defun:
16150 See ``Counting Words in a `defun'''.
16151 Words and symbols in defun:
16152 See ``What to Count?''.
16153 Words, counted recursively:
16154 See ``Count Words Recursively''.
16155 Words, duplicated:
16156 See ``The `the-the' Function''.
16157 Writing a function definition:
16158 See ``How To Write Function Definitions''.
16159 Wrong type of argument:
16160 See ``Using the Wrong Type Object as an Argument''.
16161 X axis printing:
16162 See ``The `print-X-axis' Function''.
16163 X-axis-element:
16164 See ``X Axis Tic Marks''.
16165 Y axis printing:
16166 See ``The `print-Y-axis' Function''.
16167 Y-axis-column:
16168 See ``Create a Y Axis Column''.
16169 Y-axis-column Final version.:
16170 See ``Changes for the Final Version''.
16171 Y-axis-label-spacing:
16172 See ``Side Trip: Compute a Remainder''.
16173 Y-axis-tic:
16174 See ``Construct a Y Axis Element''.
16175 yank <1>:
16176 See ```yank'''.
16177 yank:
16178 See ``Yanking Text Back''.
16179 yank-pop:
16180 See ```yank-pop'''.
16181 zap-to-char:
16182 See ```zap-to-char'''.
16183 zerop:
16184 See ``The Body of `rotate-yank-pointer'''.
16185 About 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