aboutsummaryrefslogtreecommitdiffstats
path: root/info
diff options
context:
space:
mode:
authorRobert J. Chassell2006-10-31 17:00:13 +0000
committerRobert J. Chassell2006-10-31 17:00:13 +0000
commit9497a8e60b426d96087fef053f74ce6025f77034 (patch)
treeaf7a92ceec1f5dc7382d8e5f0c13bc36bf43421c /info
parentb91f80459f69e692a9dfb702315f7034111a0ee1 (diff)
downloademacs-9497a8e60b426d96087fef053f74ce6025f77034.tar.gz
emacs-9497a8e60b426d96087fef053f74ce6025f77034.zip
info/eintr-1: Updated Info file to Third Edition for
`Introduction to Programming in Emacs Lisp'
Diffstat (limited to 'info')
-rw-r--r--info/eintr-17313
1 files changed, 7313 insertions, 0 deletions
diff --git a/info/eintr-1 b/info/eintr-1
new file mode 100644
index 00000000000..391572a9ad4
--- /dev/null
+++ b/info/eintr-1
@@ -0,0 +1,7313 @@
1This is ../info/eintr, produced by makeinfo version 4.8 from
2emacs-lisp-intro.texi.
3
4INFO-DIR-SECTION Emacs
5START-INFO-DIR-ENTRY
6* Emacs Lisp Intro: (eintr).
7 A simple introduction to Emacs Lisp programming.
8END-INFO-DIR-ENTRY
9
10This is an `Introduction to Programming in Emacs Lisp', for people who
11are not programmers.
12
13Edition 3.00, 2006 Oct 31
14
15Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002,
162003, 2004, 2005, 2006 Free Software Foundation, Inc.
17
18Published by the:
19
20 GNU Press, Website: http://www.gnupress.org
21 a division of the General: press@gnu.org
22 Free Software Foundation, Inc. Orders: sales@gnu.org
23 51 Franklin Street, Fifth Floor Tel: +1 (617) 542-5942
24 Boston, MA 02110-1301 USA Fax: +1 (617) 542-2652
25
26
27ISBN 1-882114-43-4
28
29Permission is granted to copy, distribute and/or modify this document
30under the terms of the GNU Free Documentation License, Version 1.2 or
31any later version published by the Free Software Foundation; there
32being no Invariant Section, with the Front-Cover Texts being "A GNU
33Manual", and with the Back-Cover Texts as in (a) below. A copy of the
34license is included in the section entitled "GNU Free Documentation
35License".
36
37(a) The FSF's Back-Cover Text is: "You have freedom to copy and modify
38this GNU Manual, like GNU software. Copies published by the Free
39Software Foundation raise funds for GNU development."
40
41
42File: eintr, Node: Top, Next: Preface, Prev: (dir), Up: (dir)
43
44An Introduction to Programming in Emacs Lisp
45********************************************
46
47This is an `Introduction to Programming in Emacs Lisp', for people who
48are not programmers.
49
50Edition 3.00, 2006 Oct 31
51
52Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002,
532003, 2004, 2005, 2006 Free Software Foundation, Inc.
54
55Published by the:
56
57 GNU Press, Website: http://www.gnupress.org
58 a division of the General: press@gnu.org
59 Free Software Foundation, Inc. Orders: sales@gnu.org
60 51 Franklin Street, Fifth Floor Tel: +1 (617) 542-5942
61 Boston, MA 02110-1301 USA Fax: +1 (617) 542-2652
62
63
64ISBN 1-882114-43-4
65
66Permission is granted to copy, distribute and/or modify this document
67under the terms of the GNU Free Documentation License, Version 1.2 or
68any later version published by the Free Software Foundation; there
69being no Invariant Section, with the Front-Cover Texts being "A GNU
70Manual", and with the Back-Cover Texts as in (a) below. A copy of the
71license is included in the section entitled "GNU Free Documentation
72License".
73
74(a) The FSF's Back-Cover Text is: "You have freedom to copy and modify
75this GNU Manual, like GNU software. Copies published by the Free
76Software Foundation raise funds for GNU development."
77
78This master menu first lists each chapter and index; then it lists
79every node in every chapter.
80
81* Menu:
82
83* Preface:: What to look for.
84* List Processing:: What is Lisp?
85* Practicing Evaluation:: Running several programs.
86* Writing Defuns:: How to write function definitions.
87* Buffer Walk Through:: Exploring a few buffer-related functions.
88* More Complex:: A few, even more complex functions.
89* Narrowing & Widening:: Restricting your and Emacs attention to
90 a region.
91* car cdr & cons:: Fundamental functions in Lisp.
92* Cutting & Storing Text:: Removing text and saving it.
93* List Implementation:: How lists are implemented in the computer.
94* Yanking:: Pasting stored text.
95* Loops & Recursion:: How to repeat a process.
96* Regexp Search:: Regular expression searches.
97* Counting Words:: A review of repetition and regexps.
98* Words in a defun:: Counting words in a `defun'.
99* Readying a Graph:: A prototype graph printing function.
100* Emacs Initialization:: How to write a `.emacs' file.
101* Debugging:: How to run the Emacs Lisp debuggers.
102* Conclusion:: Now you have the basics.
103* the-the:: An appendix: how to find reduplicated words.
104* Kill Ring:: An appendix: how the kill ring works.
105* Full Graph:: How to create a graph with labelled axes.
106* Free Software and Free Manuals::
107* GNU Free Documentation License::
108* Index::
109* About the Author::
110
111 --- The Detailed Node Listing ---
112
113Preface
114
115* Why:: Why learn Emacs Lisp?
116* On Reading this Text:: Read, gain familiarity, pick up habits....
117* Who You Are:: For whom this is written.
118* Lisp History::
119* Note for Novices:: You can read this as a novice.
120* Thank You::
121
122List Processing
123
124* Lisp Lists:: What are lists?
125* Run a Program:: Any list in Lisp is a program ready to run.
126* Making Errors:: Generating an error message.
127* Names & Definitions:: Names of symbols and function definitions.
128* Lisp Interpreter:: What the Lisp interpreter does.
129* Evaluation:: Running a program.
130* Variables:: Returning a value from a variable.
131* Arguments:: Passing information to a function.
132* set & setq:: Setting the value of a variable.
133* Summary:: The major points.
134* Error Message Exercises::
135
136Lisp Lists
137
138* Numbers Lists:: List have numbers, other lists, in them.
139* Lisp Atoms:: Elemental entities.
140* Whitespace in Lists:: Formatting lists to be readable.
141* Typing Lists:: How GNU Emacs helps you type lists.
142
143The Lisp Interpreter
144
145* Complications:: Variables, Special forms, Lists within.
146* Byte Compiling:: Specially processing code for speed.
147
148Evaluation
149
150* Evaluating Inner Lists:: Lists within lists...
151
152Variables
153
154* fill-column Example::
155* Void Function:: The error message for a symbol
156 without a function.
157* Void Variable:: The error message for a symbol without a value.
158
159Arguments
160
161* Data types:: Types of data passed to a function.
162* Args as Variable or List:: An argument can be the value
163 of a variable or list.
164* Variable Number of Arguments:: Some functions may take a
165 variable number of arguments.
166* Wrong Type of Argument:: Passing an argument of the wrong type
167 to a function.
168* message:: A useful function for sending messages.
169
170Setting the Value of a Variable
171
172* Using set:: Setting values.
173* Using setq:: Setting a quoted value.
174* Counting:: Using `setq' to count.
175
176Practicing Evaluation
177
178* How to Evaluate:: Typing editing commands or C-x C-e
179 causes evaluation.
180* Buffer Names:: Buffers and files are different.
181* Getting Buffers:: Getting a buffer itself, not merely its name.
182* Switching Buffers:: How to change to another buffer.
183* Buffer Size & Locations:: Where point is located and the size of
184 the buffer.
185* Evaluation Exercise::
186
187How To Write Function Definitions
188
189* Primitive Functions::
190* defun:: The `defun' special form.
191* Install:: Install a function definition.
192* Interactive:: Making a function interactive.
193* Interactive Options:: Different options for `interactive'.
194* Permanent Installation:: Installing code permanently.
195* let:: Creating and initializing local variables.
196* if:: What if?
197* else:: If--then--else expressions.
198* Truth & Falsehood:: What Lisp considers false and true.
199* save-excursion:: Keeping track of point, mark, and buffer.
200* Review::
201* defun Exercises::
202
203Install a Function Definition
204
205* Effect of installation::
206* Change a defun:: How to change a function definition.
207
208Make a Function Interactive
209
210* Interactive multiply-by-seven:: An overview.
211* multiply-by-seven in detail:: The interactive version.
212
213`let'
214
215* Prevent confusion::
216* Parts of let Expression::
217* Sample let Expression::
218* Uninitialized let Variables::
219
220The `if' Special Form
221
222* if in more detail::
223* type-of-animal in detail:: An example of an `if' expression.
224
225Truth and Falsehood in Emacs Lisp
226
227* nil explained:: `nil' has two meanings.
228
229`save-excursion'
230
231* Point and mark:: A review of various locations.
232* Template for save-excursion::
233
234A Few Buffer--Related Functions
235
236* Finding More:: How to find more information.
237* simplified-beginning-of-buffer:: Shows `goto-char',
238 `point-min', and `push-mark'.
239* mark-whole-buffer:: Almost the same as `beginning-of-buffer'.
240* append-to-buffer:: Uses `save-excursion' and
241 `insert-buffer-substring'.
242* Buffer Related Review:: Review.
243* Buffer Exercises::
244
245The Definition of `mark-whole-buffer'
246
247* mark-whole-buffer overview::
248* Body of mark-whole-buffer:: Only three lines of code.
249
250The Definition of `append-to-buffer'
251
252* append-to-buffer overview::
253* append interactive:: A two part interactive expression.
254* append-to-buffer body:: Incorporates a `let' expression.
255* append save-excursion:: How the `save-excursion' works.
256
257A Few More Complex Functions
258
259* copy-to-buffer:: With `set-buffer', `get-buffer-create'.
260* insert-buffer:: Read-only, and with `or'.
261* beginning-of-buffer:: Shows `goto-char',
262 `point-min', and `push-mark'.
263* Second Buffer Related Review::
264* optional Exercise::
265
266The Definition of `insert-buffer'
267
268* insert-buffer code::
269* insert-buffer interactive:: When you can read, but not write.
270* insert-buffer body:: The body has an `or' and a `let'.
271* if & or:: Using an `if' instead of an `or'.
272* Insert or:: How the `or' expression works.
273* Insert let:: Two `save-excursion' expressions.
274* New insert-buffer::
275
276The Interactive Expression in `insert-buffer'
277
278* Read-only buffer:: When a buffer cannot be modified.
279* b for interactive:: An existing buffer or else its name.
280
281Complete Definition of `beginning-of-buffer'
282
283* Optional Arguments::
284* beginning-of-buffer opt arg:: Example with optional argument.
285* beginning-of-buffer complete::
286
287`beginning-of-buffer' with an Argument
288
289* Disentangle beginning-of-buffer::
290* Large buffer case::
291* Small buffer case::
292
293Narrowing and Widening
294
295* Narrowing advantages:: The advantages of narrowing
296* save-restriction:: The `save-restriction' special form.
297* what-line:: The number of the line that point is on.
298* narrow Exercise::
299
300`car', `cdr', `cons': Fundamental Functions
301
302* Strange Names:: An historical aside: why the strange names?
303* car & cdr:: Functions for extracting part of a list.
304* cons:: Constructing a list.
305* nthcdr:: Calling `cdr' repeatedly.
306* nth::
307* setcar:: Changing the first element of a list.
308* setcdr:: Changing the rest of a list.
309* cons Exercise::
310
311`cons'
312
313* Build a list::
314* length:: How to find the length of a list.
315
316Cutting and Storing Text
317
318* Storing Text:: Text is stored in a list.
319* zap-to-char:: Cutting out text up to a character.
320* kill-region:: Cutting text out of a region.
321* copy-region-as-kill:: A definition for copying text.
322* Digression into C:: Minor note on C programming language macros.
323* defvar:: How to give a variable an initial value.
324* cons & search-fwd Review::
325* search Exercises::
326
327`zap-to-char'
328
329* Complete zap-to-char:: The complete implementation.
330* zap-to-char interactive:: A three part interactive expression.
331* zap-to-char body:: A short overview.
332* search-forward:: How to search for a string.
333* progn:: The `progn' special form.
334* Summing up zap-to-char:: Using `point' and `search-forward'.
335
336`kill-region'
337
338* Complete kill-region:: The function definition.
339* condition-case:: Dealing with a problem.
340* Lisp macro::
341
342`copy-region-as-kill'
343
344* Complete copy-region-as-kill:: The complete function definition.
345* copy-region-as-kill body:: The body of `copy-region-as-kill'.
346
347The Body of `copy-region-as-kill'
348
349* last-command & this-command::
350* kill-append function::
351* kill-new function::
352
353Initializing a Variable with `defvar'
354
355* See variable current value::
356* defvar and asterisk::
357
358How Lists are Implemented
359
360* Lists diagrammed::
361* Symbols as Chest:: Exploring a powerful metaphor.
362* List Exercise::
363
364Yanking Text Back
365
366* Kill Ring Overview::
367* kill-ring-yank-pointer:: The kill ring is a list.
368* yank nthcdr Exercises:: The `kill-ring-yank-pointer' variable.
369
370Loops and Recursion
371
372* while:: Causing a stretch of code to repeat.
373* dolist dotimes::
374* Recursion:: Causing a function to call itself.
375* Looping exercise::
376
377`while'
378
379* Looping with while:: Repeat so long as test returns true.
380* Loop Example:: A `while' loop that uses a list.
381* print-elements-of-list:: Uses `while', `car', `cdr'.
382* Incrementing Loop:: A loop with an incrementing counter.
383* Decrementing Loop:: A loop with a decrementing counter.
384
385A Loop with an Incrementing Counter
386
387* Incrementing Example:: Counting pebbles in a triangle.
388* Inc Example parts:: The parts of the function definition.
389* Inc Example altogether:: Putting the function definition together.
390
391Loop with a Decrementing Counter
392
393* Decrementing Example:: More pebbles on the beach.
394* Dec Example parts:: The parts of the function definition.
395* Dec Example altogether:: Putting the function definition together.
396
397Save your time: `dolist' and `dotimes'
398
399* dolist::
400* dotimes::
401
402Recursion
403
404* Building Robots:: Same model, different serial number ...
405* Recursive Definition Parts:: Walk until you stop ...
406* Recursion with list:: Using a list as the test whether to recurse.
407* Recursive triangle function::
408* Recursion with cond::
409* Recursive Patterns:: Often used templates.
410* No Deferment:: Don't store up work ...
411* No deferment solution::
412
413Recursion in Place of a Counter
414
415* Recursive Example arg of 1 or 2::
416* Recursive Example arg of 3 or 4::
417
418Recursive Patterns
419
420* Every::
421* Accumulate::
422* Keep::
423
424Regular Expression Searches
425
426* sentence-end:: The regular expression for `sentence-end'.
427* re-search-forward:: Very similar to `search-forward'.
428* forward-sentence:: A straightforward example of regexp search.
429* forward-paragraph:: A somewhat complex example.
430* etags:: How to create your own `TAGS' table.
431* Regexp Review::
432* re-search Exercises::
433
434`forward-sentence'
435
436* Complete forward-sentence::
437* fwd-sentence while loops:: Two `while' loops.
438* fwd-sentence re-search:: A regular expression search.
439
440`forward-paragraph': a Goldmine of Functions
441
442* forward-paragraph in brief:: Key parts of the function definition.
443* fwd-para let:: The `let*' expression.
444* fwd-para while:: The forward motion `while' loop.
445
446Counting: Repetition and Regexps
447
448* Why Count Words::
449* count-words-region:: Use a regexp, but find a problem.
450* recursive-count-words:: Start with case of no words in region.
451* Counting Exercise::
452
453The `count-words-region' Function
454
455* Design count-words-region:: The definition using a `while' loop.
456* Whitespace Bug:: The Whitespace Bug in `count-words-region'.
457
458Counting Words in a `defun'
459
460* Divide and Conquer::
461* Words and Symbols:: What to count?
462* Syntax:: What constitutes a word or symbol?
463* count-words-in-defun:: Very like `count-words'.
464* Several defuns:: Counting several defuns in a file.
465* Find a File:: Do you want to look at a file?
466* lengths-list-file:: A list of the lengths of many definitions.
467* Several files:: Counting in definitions in different files.
468* Several files recursively:: Recursively counting in different files.
469* Prepare the data:: Prepare the data for display in a graph.
470
471Count Words in `defuns' in Different Files
472
473* lengths-list-many-files:: Return a list of the lengths of defuns.
474* append:: Attach one list to another.
475
476Prepare the Data for Display in a Graph
477
478* Sorting:: Sorting lists.
479* Files List:: Making a list of files.
480* Counting function definitions::
481
482Readying a Graph
483
484* Columns of a graph::
485* graph-body-print:: How to print the body of a graph.
486* recursive-graph-body-print::
487* Printed Axes::
488* Line Graph Exercise::
489
490Your `.emacs' File
491
492* Default Configuration::
493* Site-wide Init:: You can write site-wide init files.
494* defcustom:: Emacs will write code for you.
495* Beginning a .emacs File:: How to write a `.emacs file'.
496* Text and Auto-fill:: Automatically wrap lines.
497* Mail Aliases:: Use abbreviations for email addresses.
498* Indent Tabs Mode:: Don't use tabs with TeX
499* Keybindings:: Create some personal keybindings.
500* Keymaps:: More about key binding.
501* Loading Files:: Load (i.e., evaluate) files automatically.
502* Autoload:: Make functions available.
503* Simple Extension:: Define a function; bind it to a key.
504* X11 Colors:: Colors in version 19 in X.
505* Miscellaneous::
506* Mode Line:: How to customize your mode line.
507
508Debugging
509
510* debug:: How to use the built-in debugger.
511* debug-on-entry:: Start debugging when you call a function.
512* debug-on-quit:: Start debugging when you quit with C-g.
513* edebug:: How to use Edebug, a source level debugger.
514* Debugging Exercises::
515
516Handling the Kill Ring
517
518* current-kill::
519* yank:: Paste a copy of a clipped element.
520* yank-pop:: Insert element pointed to.
521* ring file::
522
523The `current-kill' Function
524
525* Understanding current-kill::
526
527`current-kill' in Outline
528
529* Digression concerning error:: How to mislead humans, but not computers.
530* Determining the Element::
531
532A Graph with Labelled Axes
533
534* Labelled Example::
535* print-graph Varlist:: `let' expression in `print-graph'.
536* print-Y-axis:: Print a label for the vertical axis.
537* print-X-axis:: Print a horizontal label.
538* Print Whole Graph:: The function to print a complete graph.
539
540The `print-Y-axis' Function
541
542* Height of label:: What height for the Y axis?
543* Compute a Remainder:: How to compute the remainder of a division.
544* Y Axis Element:: Construct a line for the Y axis.
545* Y-axis-column:: Generate a list of Y axis labels.
546* print-Y-axis Penultimate:: A not quite final version.
547
548The `print-X-axis' Function
549
550* Similarities differences:: Much like `print-Y-axis', but not exactly.
551* X Axis Tic Marks:: Create tic marks for the horizontal axis.
552
553Printing the Whole Graph
554
555* The final version:: A few changes.
556* Test print-graph:: Run a short test.
557* Graphing words in defuns:: Executing the final code.
558* lambda:: How to write an anonymous function.
559* mapcar:: Apply a function to elements of a list.
560* Another Bug:: Yet another bug ... most insidious.
561* Final printed graph:: The graph itself!
562
563
564File: eintr, Node: Preface, Next: List Processing, Prev: Top, Up: Top
565
566Preface
567*******
568
569Most of the GNU Emacs integrated environment is written in the
570programming language called Emacs Lisp. The code written in this
571programming language is the software--the sets of instructions--that
572tell the computer what to do when you give it commands. Emacs is
573designed so that you can write new code in Emacs Lisp and easily
574install it as an extension to the editor.
575
576(GNU Emacs is sometimes called an "extensible editor", but it does much
577more than provide editing capabilities. It is better to refer to Emacs
578as an "extensible computing environment". However, that phrase is
579quite a mouthful. It is easier to refer to Emacs simply as an editor.
580Moreover, everything you do in Emacs--find the Mayan date and phases of
581the moon, simplify polynomials, debug code, manage files, read letters,
582write books--all these activities are kinds of editing in the most
583general sense of the word.)
584
585* Menu:
586
587* Why::
588* On Reading this Text::
589* Who You Are::
590* Lisp History::
591* Note for Novices::
592* Thank You::
593
594
595File: eintr, Node: Why, Next: On Reading this Text, Prev: Preface, Up: Preface
596
597Why Study Emacs Lisp?
598=====================
599
600Although Emacs Lisp is usually thought of in association only with
601Emacs, it is a full computer programming language. You can use Emacs
602Lisp as you would any other programming language.
603
604Perhaps you want to understand programming; perhaps you want to extend
605Emacs; or perhaps you want to become a programmer. This introduction to
606Emacs Lisp is designed to get you started: to guide you in learning the
607fundamentals of programming, and more importantly, to show you how you
608can teach yourself to go further.
609
610
611File: eintr, Node: On Reading this Text, Next: Who You Are, Prev: Why, Up: Preface
612
613On Reading this Text
614====================
615
616All through this document, you will see little sample programs you can
617run inside of Emacs. If you read this document in Info inside of GNU
618Emacs, you can run the programs as they appear. (This is easy to do and
619is explained when the examples are presented.) Alternatively, you can
620read this introduction as a printed book while sitting beside a computer
621running Emacs. (This is what I like to do; I like printed books.) If
622you don't have a running Emacs beside you, you can still read this book,
623but in this case, it is best to treat it as a novel or as a travel guide
624to a country not yet visited: interesting, but not the same as being
625there.
626
627Much of this introduction is dedicated to walk-throughs or guided tours
628of code used in GNU Emacs. These tours are designed for two purposes:
629first, to give you familiarity with real, working code (code you use
630every day); and, second, to give you familiarity with the way Emacs
631works. It is interesting to see how a working environment is
632implemented. Also, I hope that you will pick up the habit of browsing
633through source code. You can learn from it and mine it for ideas.
634Having GNU Emacs is like having a dragon's cave of treasures.
635
636In addition to learning about Emacs as an editor and Emacs Lisp as a
637programming language, the examples and guided tours will give you an
638opportunity to get acquainted with Emacs as a Lisp programming
639environment. GNU Emacs supports programming and provides tools that
640you will want to become comfortable using, such as `M-.' (the key which
641invokes the `find-tag' command). You will also learn about buffers and
642other objects that are part of the environment. Learning about these
643features of Emacs is like learning new routes around your home town.
644
645Finally, I hope to convey some of the skills for using Emacs to learn
646aspects of programming that you don't know. You can often use Emacs to
647help you understand what puzzles you or to find out how to do something
648new. This self-reliance is not only a pleasure, but an advantage.
649
650
651File: eintr, Node: Who You Are, Next: Lisp History, Prev: On Reading this Text, Up: Preface
652
653For Whom This is Written
654========================
655
656This text is written as an elementary introduction for people who are
657not programmers. If you are a programmer, you may not be satisfied with
658this primer. The reason is that you may have become expert at reading
659reference manuals and be put off by the way this text is organized.
660
661An expert programmer who reviewed this text said to me:
662
663 I prefer to learn from reference manuals. I "dive into" each
664 paragraph, and "come up for air" between paragraphs.
665
666 When I get to the end of a paragraph, I assume that that subject is
667 done, finished, that I know everything I need (with the possible
668 exception of the case when the next paragraph starts talking about
669 it in more detail). I expect that a well written reference manual
670 will not have a lot of redundancy, and that it will have excellent
671 pointers to the (one) place where the information I want is.
672
673This introduction is not written for this person!
674
675Firstly, I try to say everything at least three times: first, to
676introduce it; second, to show it in context; and third, to show it in a
677different context, or to review it.
678
679Secondly, I hardly ever put all the information about a subject in one
680place, much less in one paragraph. To my way of thinking, that imposes
681too heavy a burden on the reader. Instead I try to explain only what
682you need to know at the time. (Sometimes I include a little extra
683information so you won't be surprised later when the additional
684information is formally introduced.)
685
686When you read this text, you are not expected to learn everything the
687first time. Frequently, you need only make, as it were, a `nodding
688acquaintance' with some of the items mentioned. My hope is that I have
689structured the text and given you enough hints that you will be alert to
690what is important, and concentrate on it.
691
692You will need to "dive into" some paragraphs; there is no other way to
693read them. But I have tried to keep down the number of such
694paragraphs. This book is intended as an approachable hill, rather than
695as a daunting mountain.
696
697This introduction to `Programming in Emacs Lisp' has a companion
698document, *Note The GNU Emacs Lisp Reference Manual: (elisp)Top. The
699reference manual has more detail than this introduction. In the
700reference manual, all the information about one topic is concentrated
701in one place. You should turn to it if you are like the programmer
702quoted above. And, of course, after you have read this `Introduction',
703you will find the `Reference Manual' useful when you are writing your
704own programs.
705
706
707File: eintr, Node: Lisp History, Next: Note for Novices, Prev: Who You Are, Up: Preface
708
709Lisp History
710============
711
712Lisp was first developed in the late 1950s at the Massachusetts
713Institute of Technology for research in artificial intelligence. The
714great power of the Lisp language makes it superior for other purposes as
715well, such as writing editor commands and integrated environments.
716
717GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
718in the 1960s. It is somewhat inspired by Common Lisp, which became a
719standard in the 1980s. However, Emacs Lisp is much simpler than Common
720Lisp. (The standard Emacs distribution contains an optional extensions
721file, `cl.el', that adds many Common Lisp features to Emacs Lisp.)
722
723
724File: eintr, Node: Note for Novices, Next: Thank You, Prev: Lisp History, Up: Preface
725
726A Note for Novices
727==================
728
729If you don't know GNU Emacs, you can still read this document
730profitably. However, I recommend you learn Emacs, if only to learn to
731move around your computer screen. You can teach yourself how to use
732Emacs with the on-line tutorial. To use it, type `C-h t'. (This means
733you press and release the <CTRL> key and the `h' at the same time, and
734then press and release `t'.)
735
736Also, I often refer to one of Emacs' standard commands by listing the
737keys which you press to invoke the command and then giving the name of
738the command in parentheses, like this: `M-C-\' (`indent-region'). What
739this means is that the `indent-region' command is customarily invoked
740by typing `M-C-\'. (You can, if you wish, change the keys that are
741typed to invoke the command; this is called "rebinding". *Note
742Keymaps: Keymaps.) The abbreviation `M-C-\' means that you type your
743<META> key, <CTRL> key and <\> key all at the same time. (On many
744modern keyboards the <META> key is labelled <ALT>.) Sometimes a
745combination like this is called a keychord, since it is similar to the
746way you play a chord on a piano. If your keyboard does not have a
747<META> key, the <ESC> key prefix is used in place of it. In this case,
748`M-C-\' means that you press and release your <ESC> key and then type
749the <CTRL> key and the <\> key at the same time. But usually `M-C-\'
750means press the <CTRL> key along with the key that is labelled <ALT>
751and, at the same time, press the <\> key.
752
753In addition to typing a lone keychord, you can prefix what you type
754with `C-u', which is called the `universal argument'. The `C-u'
755keychord passes an argument to the subsequent command. Thus, to indent
756a region of plain text by 6 spaces, mark the region, and then type
757`C-u 6 M-C-\'. (If you do not specify a number, Emacs either passes
758the number 4 to the command or otherwise runs the command differently
759than it would otherwise.) *Note Numeric Arguments: (emacs)Arguments.
760
761If you are reading this in Info using GNU Emacs, you can read through
762this whole document just by pressing the space bar, <SPC>. (To learn
763about Info, type `C-h i' and then select Info.)
764
765A note on terminology: when I use the word Lisp alone, I often am
766referring to the various dialects of Lisp in general, but when I speak
767of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
768
769
770File: eintr, Node: Thank You, Prev: Note for Novices, Up: Preface
771
772Thank You
773=========
774
775My thanks to all who helped me with this book. My especial thanks to
776Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
777Randy Smith, Richard M. Stallman, and Melissa Weisshaus. My thanks
778also go to both Philip Johnson and David Stampe for their patient
779encouragement. My mistakes are my own.
780
781 Robert J. Chassell
782
783
784File: eintr, Node: List Processing, Next: Practicing Evaluation, Prev: Preface, Up: Top
785
7861 List Processing
787*****************
788
789To the untutored eye, Lisp is a strange programming language. In Lisp
790code there are parentheses everywhere. Some people even claim that the
791name stands for `Lots of Isolated Silly Parentheses'. But the claim is
792unwarranted. Lisp stands for LISt Processing, and the programming
793language handles _lists_ (and lists of lists) by putting them between
794parentheses. The parentheses mark the boundaries of the list.
795Sometimes a list is preceded by a single apostrophe or quotation mark,
796`''(1) Lists are the basis of Lisp.
797
798* Menu:
799
800* Lisp Lists::
801* Run a Program::
802* Making Errors::
803* Names & Definitions::
804* Lisp Interpreter::
805* Evaluation::
806* Variables::
807* Arguments::
808* set & setq::
809* Summary::
810* Error Message Exercises::
811
812---------- Footnotes ----------
813
814(1) The single apostrophe or quotation mark is an abbreviation for the
815function `quote'; you need not think about functions now; functions are
816defined in *Note Generate an Error Message: Making Errors.
817
818
819File: eintr, Node: Lisp Lists, Next: Run a Program, Prev: List Processing, Up: List Processing
820
8211.1 Lisp Lists
822==============
823
824In Lisp, a list looks like this: `'(rose violet daisy buttercup)'.
825This list is preceded by a single apostrophe. It could just as well be
826written as follows, which looks more like the kind of list you are
827likely to be familiar with:
828
829 '(rose
830 violet
831 daisy
832 buttercup)
833
834The elements of this list are the names of the four different flowers,
835separated from each other by whitespace and surrounded by parentheses,
836like flowers in a field with a stone wall around them.
837
838* Menu:
839
840* Numbers Lists::
841* Lisp Atoms::
842* Whitespace in Lists::
843* Typing Lists::
844
845
846File: eintr, Node: Numbers Lists, Next: Lisp Atoms, Prev: Lisp Lists, Up: Lisp Lists
847
848Numbers, Lists inside of Lists
849------------------------------
850
851Lists can also have numbers in them, as in this list: `(+ 2 2)'. This
852list has a plus-sign, `+', followed by two `2's, each separated by
853whitespace.
854
855In Lisp, both data and programs are represented the same way; that is,
856they are both lists of words, numbers, or other lists, separated by
857whitespace and surrounded by parentheses. (Since a program looks like
858data, one program may easily serve as data for another; this is a very
859powerful feature of Lisp.) (Incidentally, these two parenthetical
860remarks are _not_ Lisp lists, because they contain `;' and `.' as
861punctuation marks.)
862
863Here is another list, this time with a list inside of it:
864
865 '(this list has (a list inside of it))
866
867The components of this list are the words `this', `list', `has', and
868the list `(a list inside of it)'. The interior list is made up of the
869words `a', `list', `inside', `of', `it'.
870
871
872File: eintr, Node: Lisp Atoms, Next: Whitespace in Lists, Prev: Numbers Lists, Up: Lisp Lists
873
8741.1.1 Lisp Atoms
875----------------
876
877In Lisp, what we have been calling words are called "atoms". This term
878comes from the historical meaning of the word atom, which means
879`indivisible'. As far as Lisp is concerned, the words we have been
880using in the lists cannot be divided into any smaller parts and still
881mean the same thing as part of a program; likewise with numbers and
882single character symbols like `+'. On the other hand, unlike an
883ancient atom, a list can be split into parts. (*Note `car' `cdr' &
884`cons' Fundamental Functions: car cdr & cons.)
885
886In a list, atoms are separated from each other by whitespace. They can
887be right next to a parenthesis.
888
889Technically speaking, a list in Lisp consists of parentheses surrounding
890atoms separated by whitespace or surrounding other lists or surrounding
891both atoms and other lists. A list can have just one atom in it or
892have nothing in it at all. A list with nothing in it looks like this:
893`()', and is called the "empty list". Unlike anything else, an empty
894list is considered both an atom and a list at the same time.
895
896The printed representation of both atoms and lists are called "symbolic
897expressions" or, more concisely, "s-expressions". The word
898"expression" by itself can refer to either the printed representation,
899or to the atom or list as it is held internally in the computer.
900Often, people use the term "expression" indiscriminately. (Also, in
901many texts, the word "form" is used as a synonym for expression.)
902
903Incidentally, the atoms that make up our universe were named such when
904they were thought to be indivisible; but it has been found that physical
905atoms are not indivisible. Parts can split off an atom or it can
906fission into two parts of roughly equal size. Physical atoms were named
907prematurely, before their truer nature was found. In Lisp, certain
908kinds of atom, such as an array, can be separated into parts; but the
909mechanism for doing this is different from the mechanism for splitting a
910list. As far as list operations are concerned, the atoms of a list are
911unsplittable.
912
913As in English, the meanings of the component letters of a Lisp atom are
914different from the meaning the letters make as a word. For example,
915the word for the South American sloth, the `ai', is completely
916different from the two words, `a', and `i'.
917
918There are many kinds of atom in nature but only a few in Lisp: for
919example, "numbers", such as 37, 511, or 1729, and "symbols", such as
920`+', `foo', or `forward-line'. The words we have listed in the
921examples above are all symbols. In everyday Lisp conversation, the
922word "atom" is not often used, because programmers usually try to be
923more specific about what kind of atom they are dealing with. Lisp
924programming is mostly about symbols (and sometimes numbers) within
925lists. (Incidentally, the preceding three word parenthetical remark is
926a proper list in Lisp, since it consists of atoms, which in this case
927are symbols, separated by whitespace and enclosed by parentheses,
928without any non-Lisp punctuation.)
929
930In addition, text between double quotation marks--even sentences or
931paragraphs--is an atom. Here is an example:
932
933 '(this list includes "text between quotation marks.")
934
935In Lisp, all of the quoted text including the punctuation mark and the
936blank spaces is a single atom. This kind of atom is called a "string"
937(for `string of characters') and is the sort of thing that is used for
938messages that a computer can print for a human to read. Strings are a
939different kind of atom than numbers or symbols and are used differently.
940
941
942File: eintr, Node: Whitespace in Lists, Next: Typing Lists, Prev: Lisp Atoms, Up: Lisp Lists
943
9441.1.2 Whitespace in Lists
945-------------------------
946
947The amount of whitespace in a list does not matter. From the point of
948view of the Lisp language,
949
950 '(this list
951 looks like this)
952
953is exactly the same as this:
954
955 '(this list looks like this)
956
957Both examples show what to Lisp is the same list, the list made up of
958the symbols `this', `list', `looks', `like', and `this' in that order.
959
960Extra whitespace and newlines are designed to make a list more readable
961by humans. When Lisp reads the expression, it gets rid of all the extra
962whitespace (but it needs to have at least one space between atoms in
963order to tell them apart.)
964
965Odd as it seems, the examples we have seen cover almost all of what Lisp
966lists look like! Every other list in Lisp looks more or less like one
967of these examples, except that the list may be longer and more complex.
968In brief, a list is between parentheses, a string is between quotation
969marks, a symbol looks like a word, and a number looks like a number.
970(For certain situations, square brackets, dots and a few other special
971characters may be used; however, we will go quite far without them.)
972
973
974File: eintr, Node: Typing Lists, Prev: Whitespace in Lists, Up: Lisp Lists
975
9761.1.3 GNU Emacs Helps You Type Lists
977------------------------------------
978
979When you type a Lisp expression in GNU Emacs using either Lisp
980Interaction mode or Emacs Lisp mode, you have available to you several
981commands to format the Lisp expression so it is easy to read. For
982example, pressing the <TAB> key automatically indents the line the
983cursor is on by the right amount. A command to properly indent the
984code in a region is customarily bound to `M-C-\'. Indentation is
985designed so that you can see which elements of a list belong to which
986list--elements of a sub-list are indented more than the elements of the
987enclosing list.
988
989In addition, when you type a closing parenthesis, Emacs momentarily
990jumps the cursor back to the matching opening parenthesis, so you can
991see which one it is. This is very useful, since every list you type in
992Lisp must have its closing parenthesis match its opening parenthesis.
993(*Note Major Modes: (emacs)Major Modes, for more information about
994Emacs' modes.)
995
996
997File: eintr, Node: Run a Program, Next: Making Errors, Prev: Lisp Lists, Up: List Processing
998
9991.2 Run a Program
1000=================
1001
1002A list in Lisp--any list--is a program ready to run. If you run it
1003(for which the Lisp jargon is "evaluate"), the computer will do one of
1004three things: do nothing except return to you the list itself; send you
1005an error message; or, treat the first symbol in the list as a command
1006to do something. (Usually, of course, it is the last of these three
1007things that you really want!)
1008
1009The single apostrophe, `'', that I put in front of some of the example
1010lists in preceding sections is called a "quote"; when it precedes a
1011list, it tells Lisp to do nothing with the list, other than take it as
1012it is written. But if there is no quote preceding a list, the first
1013item of the list is special: it is a command for the computer to obey.
1014(In Lisp, these commands are called _functions_.) The list `(+ 2 2)'
1015shown above did not have a quote in front of it, so Lisp understands
1016that the `+' is an instruction to do something with the rest of the
1017list: add the numbers that follow.
1018
1019If you are reading this inside of GNU Emacs in Info, here is how you can
1020evaluate such a list: place your cursor immediately after the right
1021hand parenthesis of the following list and then type `C-x C-e':
1022
1023 (+ 2 2)
1024
1025You will see the number `4' appear in the echo area. (In the jargon,
1026what you have just done is "evaluate the list." The echo area is the
1027line at the bottom of the screen that displays or "echoes" text.) Now
1028try the same thing with a quoted list: place the cursor right after
1029the following list and type `C-x C-e':
1030
1031 '(this is a quoted list)
1032
1033You will see `(this is a quoted list)' appear in the echo area.
1034
1035In both cases, what you are doing is giving a command to the program
1036inside of GNU Emacs called the "Lisp interpreter"--giving the
1037interpreter a command to evaluate the expression. The name of the Lisp
1038interpreter comes from the word for the task done by a human who comes
1039up with the meaning of an expression--who "interprets" it.
1040
1041You can also evaluate an atom that is not part of a list--one that is
1042not surrounded by parentheses; again, the Lisp interpreter translates
1043from the humanly readable expression to the language of the computer.
1044But before discussing this (*note Variables::), we will discuss what the
1045Lisp interpreter does when you make an error.
1046
1047
1048File: eintr, Node: Making Errors, Next: Names & Definitions, Prev: Run a Program, Up: List Processing
1049
10501.3 Generate an Error Message
1051=============================
1052
1053Partly so you won't worry if you do it accidentally, we will now give a
1054command to the Lisp interpreter that generates an error message. This
1055is a harmless activity; and indeed, we will often try to generate error
1056messages intentionally. Once you understand the jargon, error messages
1057can be informative. Instead of being called "error" messages, they
1058should be called "help" messages. They are like signposts to a
1059traveller in a strange country; deciphering them can be hard, but once
1060understood, they can point the way.
1061
1062The error message is generated by a built-in GNU Emacs debugger. We
1063will `enter the debugger'. You get out of the debugger by typing `q'.
1064
1065What we will do is evaluate a list that is not quoted and does not have
1066a meaningful command as its first element. Here is a list almost
1067exactly the same as the one we just used, but without the single-quote
1068in front of it. Position the cursor right after it and type `C-x C-e':
1069
1070 (this is an unquoted list)
1071
1072What you see depends on which version of Emacs you are running. GNU
1073Emacs version 22 provides more information than version 20 and before.
1074First, the more recent result of generating an error; then the earlier,
1075version 20 result.
1076
1077In GNU Emacs version 22, a `*Backtrace*' window will open up and you
1078will see the following in it:
1079
1080 ---------- Buffer: *Backtrace* ----------
1081 Debugger entered--Lisp error: (void-function this)
1082 (this is an unquoted list)
1083 eval((this is an unquoted list))
1084 eval-last-sexp-1(nil)
1085 eval-last-sexp(nil)
1086 call-interactively(eval-last-sexp)
1087 ---------- Buffer: *Backtrace* ----------
1088
1089Your cursor will be in this window (you may have to wait a few seconds
1090before it becomes visible). To quit the debugger and make the debugger
1091window go away, type:
1092
1093 q
1094
1095Please type `q' right now, so you become confident that you can get out
1096of the debugger. Then, type `C-x C-e' again to re-enter it.
1097
1098Based on what we already know, we can almost read this error message.
1099
1100You read the `*Backtrace*' buffer from the bottom up; it tells you what
1101Emacs did. When you typed `C-x C-e', you made an interactive call to
1102the command `eval-last-sexp'. `eval' is an abbreviation for `evaluate'
1103and `sexp' is an abbreviation for `symbolic expression'. The command
1104means `evaluate last symbolic expression', which is the expression just
1105before your cursor.
1106
1107Each line above tells you what the Lisp interpreter evaluated next.
1108The most recent action is at the top. The buffer is called the
1109`*Backtrace*' buffer because it enables you to track Emacs backwards.
1110
1111At the top of the `*Backtrace*' buffer, you see the line:
1112
1113 Debugger entered--Lisp error: (void-function this)
1114
1115The Lisp interpreter tried to evaluate the first atom of the list, the
1116word `this'. It is this action that generated the error message
1117`void-function this'.
1118
1119The message contains the words `void-function' and `this'.
1120
1121The word `function' was mentioned once before. It is a very important
1122word. For our purposes, we can define it by saying that a "function"
1123is a set of instructions to the computer that tell the computer to do
1124something.
1125
1126Now we can begin to understand the error message: `void-function this'.
1127The function (that is, the word `this') does not have a definition of
1128any set of instructions for the computer to carry out.
1129
1130The slightly odd word, `void-function', is designed to cover the way
1131Emacs Lisp is implemented, which is that when a symbol does not have a
1132function definition attached to it, the place that should contain the
1133instructions is `void'.
1134
1135On the other hand, since we were able to add 2 plus 2 successfully, by
1136evaluating `(+ 2 2)', we can infer that the symbol `+' must have a set
1137of instructions for the computer to obey and those instructions must be
1138to add the numbers that follow the `+'.
1139
1140In GNU Emacs version 20, and in earlier versions, you will see only one
1141line of error message; it will appear in the echo area and look like
1142this:
1143
1144 Symbol's function definition is void: this
1145
1146(Also, your terminal may beep at you--some do, some don't; and others
1147blink. This is just a device to get your attention.) The message goes
1148away as soon as you type another key, even just to move the cursor.
1149
1150We know the meaning of the word `Symbol'. It refers to the first atom
1151of the list, the word `this'. The word `function' refers to the
1152instructions that tell the computer what to do. (Technically, the
1153symbol tells the computer where to find the instructions, but this is a
1154complication we can ignore for the moment.)
1155
1156The error message can be understood: `Symbol's function definition is
1157void: this'. The symbol (that is, the word `this') lacks instructions
1158for the computer to carry out.
1159
1160
1161File: eintr, Node: Names & Definitions, Next: Lisp Interpreter, Prev: Making Errors, Up: List Processing
1162
11631.4 Symbol Names and Function Definitions
1164=========================================
1165
1166We can articulate another characteristic of Lisp based on what we have
1167discussed so far--an important characteristic: a symbol, like `+', is
1168not itself the set of instructions for the computer to carry out.
1169Instead, the symbol is used, perhaps temporarily, as a way of locating
1170the definition or set of instructions. What we see is the name through
1171which the instructions can be found. Names of people work the same
1172way. I can be referred to as `Bob'; however, I am not the letters `B',
1173`o', `b' but am, or was, the consciousness consistently associated with
1174a particular life-form. The name is not me, but it can be used to
1175refer to me.
1176
1177In Lisp, one set of instructions can be attached to several names. For
1178example, the computer instructions for adding numbers can be linked to
1179the symbol `plus' as well as to the symbol `+' (and are in some
1180dialects of Lisp). Among humans, I can be referred to as `Robert' as
1181well as `Bob' and by other words as well.
1182
1183On the other hand, a symbol can have only one function definition
1184attached to it at a time. Otherwise, the computer would be confused as
1185to which definition to use. If this were the case among people, only
1186one person in the world could be named `Bob'. However, the function
1187definition to which the name refers can be changed readily. (*Note
1188Install a Function Definition: Install.)
1189
1190Since Emacs Lisp is large, it is customary to name symbols in a way
1191that identifies the part of Emacs to which the function belongs. Thus,
1192all the names for functions that deal with Texinfo start with
1193`texinfo-' and those for functions that deal with reading mail start
1194with `rmail-'.
1195
1196
1197File: eintr, Node: Lisp Interpreter, Next: Evaluation, Prev: Names & Definitions, Up: List Processing
1198
11991.5 The Lisp Interpreter
1200========================
1201
1202Based on what we have seen, we can now start to figure out what the
1203Lisp interpreter does when we command it to evaluate a list. First, it
1204looks to see whether there is a quote before the list; if there is, the
1205interpreter just gives us the list. On the other hand, if there is no
1206quote, the interpreter looks at the first element in the list and sees
1207whether it has a function definition. If it does, the interpreter
1208carries out the instructions in the function definition. Otherwise,
1209the interpreter prints an error message.
1210
1211This is how Lisp works. Simple. There are added complications which we
1212will get to in a minute, but these are the fundamentals. Of course, to
1213write Lisp programs, you need to know how to write function definitions
1214and attach them to names, and how to do this without confusing either
1215yourself or the computer.
1216
1217* Menu:
1218
1219* Complications::
1220* Byte Compiling::
1221
1222
1223File: eintr, Node: Complications, Next: Byte Compiling, Prev: Lisp Interpreter, Up: Lisp Interpreter
1224
1225Complications
1226-------------
1227
1228Now, for the first complication. In addition to lists, the Lisp
1229interpreter can evaluate a symbol that is not quoted and does not have
1230parentheses around it. The Lisp interpreter will attempt to determine
1231the symbol's value as a "variable". This situation is described in the
1232section on variables. (*Note Variables::.)
1233
1234The second complication occurs because some functions are unusual and do
1235not work in the usual manner. Those that don't are called "special
1236forms". They are used for special jobs, like defining a function, and
1237there are not many of them. In the next few chapters, you will be
1238introduced to several of the more important special forms.
1239
1240The third and final complication is this: if the function that the Lisp
1241interpreter is looking at is not a special form, and if it is part of a
1242list, the Lisp interpreter looks to see whether the list has a list
1243inside of it. If there is an inner list, the Lisp interpreter first
1244figures out what it should do with the inside list, and then it works on
1245the outside list. If there is yet another list embedded inside the
1246inner list, it works on that one first, and so on. It always works on
1247the innermost list first. The interpreter works on the innermost list
1248first, to evaluate the result of that list. The result may be used by
1249the enclosing expression.
1250
1251Otherwise, the interpreter works left to right, from one expression to
1252the next.
1253
1254
1255File: eintr, Node: Byte Compiling, Prev: Complications, Up: Lisp Interpreter
1256
12571.5.1 Byte Compiling
1258--------------------
1259
1260One other aspect of interpreting: the Lisp interpreter is able to
1261interpret two kinds of entity: humanly readable code, on which we will
1262focus exclusively, and specially processed code, called "byte compiled"
1263code, which is not humanly readable. Byte compiled code runs faster
1264than humanly readable code.
1265
1266You can transform humanly readable code into byte compiled code by
1267running one of the compile commands such as `byte-compile-file'. Byte
1268compiled code is usually stored in a file that ends with a `.elc'
1269extension rather than a `.el' extension. You will see both kinds of
1270file in the `emacs/lisp' directory; the files to read are those with
1271`.el' extensions.
1272
1273As a practical matter, for most things you might do to customize or
1274extend Emacs, you do not need to byte compile; and I will not discuss
1275the topic here. *Note Byte Compilation: (elisp)Byte Compilation, for a
1276full description of byte compilation.
1277
1278
1279File: eintr, Node: Evaluation, Next: Variables, Prev: Lisp Interpreter, Up: List Processing
1280
12811.6 Evaluation
1282==============
1283
1284When the Lisp interpreter works on an expression, the term for the
1285activity is called "evaluation". We say that the interpreter
1286`evaluates the expression'. I've used this term several times before.
1287The word comes from its use in everyday language, `to ascertain the
1288value or amount of; to appraise', according to `Webster's New
1289Collegiate Dictionary'.
1290
1291After evaluating an expression, the Lisp interpreter will most likely
1292"return" the value that the computer produces by carrying out the
1293instructions it found in the function definition, or perhaps it will
1294give up on that function and produce an error message. (The interpreter
1295may also find itself tossed, so to speak, to a different function or it
1296may attempt to repeat continually what it is doing for ever and ever in
1297what is called an `infinite loop'. These actions are less common; and
1298we can ignore them.) Most frequently, the interpreter returns a value.
1299
1300At the same time the interpreter returns a value, it may do something
1301else as well, such as move a cursor or copy a file; this other kind of
1302action is called a "side effect". Actions that we humans think are
1303important, such as printing results, are often "side effects" to the
1304Lisp interpreter. The jargon can sound peculiar, but it turns out that
1305it is fairly easy to learn to use side effects.
1306
1307In summary, evaluating a symbolic expression most commonly causes the
1308Lisp interpreter to return a value and perhaps carry out a side effect;
1309or else produce an error.
1310
1311* Menu:
1312
1313* Evaluating Inner Lists::
1314
1315
1316File: eintr, Node: Evaluating Inner Lists, Prev: Evaluation, Up: Evaluation
1317
13181.6.1 Evaluating Inner Lists
1319----------------------------
1320
1321If evaluation applies to a list that is inside another list, the outer
1322list may use the value returned by the first evaluation as information
1323when the outer list is evaluated. This explains why inner expressions
1324are evaluated first: the values they return are used by the outer
1325expressions.
1326
1327We can investigate this process by evaluating another addition example.
1328Place your cursor after the following expression and type `C-x C-e':
1329
1330 (+ 2 (+ 3 3))
1331
1332The number 8 will appear in the echo area.
1333
1334What happens is that the Lisp interpreter first evaluates the inner
1335expression, `(+ 3 3)', for which the value 6 is returned; then it
1336evaluates the outer expression as if it were written `(+ 2 6)', which
1337returns the value 8. Since there are no more enclosing expressions to
1338evaluate, the interpreter prints that value in the echo area.
1339
1340Now it is easy to understand the name of the command invoked by the
1341keystrokes `C-x C-e': the name is `eval-last-sexp'. The letters `sexp'
1342are an abbreviation for `symbolic expression', and `eval' is an
1343abbreviation for `evaluate'. The command means `evaluate last symbolic
1344expression'.
1345
1346As an experiment, you can try evaluating the expression by putting the
1347cursor at the beginning of the next line immediately following the
1348expression, or inside the expression.
1349
1350Here is another copy of the expression:
1351
1352 (+ 2 (+ 3 3))
1353
1354If you place the cursor at the beginning of the blank line that
1355immediately follows the expression and type `C-x C-e', you will still
1356get the value 8 printed in the echo area. Now try putting the cursor
1357inside the expression. If you put it right after the next to last
1358parenthesis (so it appears to sit on top of the last parenthesis), you
1359will get a 6 printed in the echo area! This is because the command
1360evaluates the expression `(+ 3 3)'.
1361
1362Now put the cursor immediately after a number. Type `C-x C-e' and you
1363will get the number itself. In Lisp, if you evaluate a number, you get
1364the number itself--this is how numbers differ from symbols. If you
1365evaluate a list starting with a symbol like `+', you will get a value
1366returned that is the result of the computer carrying out the
1367instructions in the function definition attached to that name. If a
1368symbol by itself is evaluated, something different happens, as we will
1369see in the next section.
1370
1371
1372File: eintr, Node: Variables, Next: Arguments, Prev: Evaluation, Up: List Processing
1373
13741.7 Variables
1375=============
1376
1377In Emacs Lisp, a symbol can have a value attached to it just as it can
1378have a function definition attached to it. The two are different. The
1379function definition is a set of instructions that a computer will obey.
1380A value, on the other hand, is something, such as number or a name,
1381that can vary (which is why such a symbol is called a variable). The
1382value of a symbol can be any expression in Lisp, such as a symbol,
1383number, list, or string. A symbol that has a value is often called a
1384"variable".
1385
1386A symbol can have both a function definition and a value attached to it
1387at the same time. Or it can have just one or the other. The two are
1388separate. This is somewhat similar to the way the name Cambridge can
1389refer to the city in Massachusetts and have some information attached
1390to the name as well, such as "great programming center".
1391
1392Another way to think about this is to imagine a symbol as being a chest
1393of drawers. The function definition is put in one drawer, the value in
1394another, and so on. What is put in the drawer holding the value can be
1395changed without affecting the contents of the drawer holding the
1396function definition, and vice-verse.
1397
1398* Menu:
1399
1400* fill-column Example::
1401* Void Function::
1402* Void Variable::
1403
1404
1405File: eintr, Node: fill-column Example, Next: Void Function, Prev: Variables, Up: Variables
1406
1407`fill-column', an Example Variable
1408----------------------------------
1409
1410The variable `fill-column' illustrates a symbol with a value attached
1411to it: in every GNU Emacs buffer, this symbol is set to some value,
1412usually 72 or 70, but sometimes to some other value. To find the value
1413of this symbol, evaluate it by itself. If you are reading this in Info
1414inside of GNU Emacs, you can do this by putting the cursor after the
1415symbol and typing `C-x C-e':
1416
1417 fill-column
1418
1419After I typed `C-x C-e', Emacs printed the number 72 in my echo area.
1420This is the value for which `fill-column' is set for me as I write
1421this. It may be different for you in your Info buffer. Notice that
1422the value returned as a variable is printed in exactly the same way as
1423the value returned by a function carrying out its instructions. From
1424the point of view of the Lisp interpreter, a value returned is a value
1425returned. What kind of expression it came from ceases to matter once
1426the value is known.
1427
1428A symbol can have any value attached to it or, to use the jargon, we can
1429"bind" the variable to a value: to a number, such as 72; to a string,
1430`"such as this"'; to a list, such as `(spruce pine oak)'; we can even
1431bind a variable to a function definition.
1432
1433A symbol can be bound to a value in several ways. *Note Setting the
1434Value of a Variable: set & setq, for information about one way to do
1435this.
1436
1437
1438File: eintr, Node: Void Function, Next: Void Variable, Prev: fill-column Example, Up: Variables
1439
14401.7.1 Error Message for a Symbol Without a Function
1441---------------------------------------------------
1442
1443When we evaluated `fill-column' to find its value as a variable, we did
1444not place parentheses around the word. This is because we did not
1445intend to use it as a function name.
1446
1447If `fill-column' were the first or only element of a list, the Lisp
1448interpreter would attempt to find the function definition attached to
1449it. But `fill-column' has no function definition. Try evaluating this:
1450
1451 (fill-column)
1452
1453In GNU Emacs version 22, you will create a `*Backtrace*' buffer that
1454says:
1455
1456 ---------- Buffer: *Backtrace* ----------
1457 Debugger entered--Lisp error: (void-function fill-column)
1458 (fill-column)
1459 eval((fill-column))
1460 eval-last-sexp-1(nil)
1461 eval-last-sexp(nil)
1462 call-interactively(eval-last-sexp)
1463 ---------- Buffer: *Backtrace* ----------
1464
1465(Remember, to quit the debugger and make the debugger window go away,
1466type `q' in the `*Backtrace*' buffer.)
1467
1468
1469File: eintr, Node: Void Variable, Prev: Void Function, Up: Variables
1470
14711.7.2 Error Message for a Symbol Without a Value
1472------------------------------------------------
1473
1474If you attempt to evaluate a symbol that does not have a value bound to
1475it, you will receive an error message. You can see this by
1476experimenting with our 2 plus 2 addition. In the following expression,
1477put your cursor right after the `+', before the first number 2, type
1478`C-x C-e':
1479
1480 (+ 2 2)
1481
1482In GNU Emacs 22, you will create a `*Backtrace*' buffer that says:
1483
1484 ---------- Buffer: *Backtrace* ----------
1485 Debugger entered--Lisp error: (void-variable +)
1486 eval(+)
1487 eval-last-sexp-1(nil)
1488 eval-last-sexp(nil)
1489 call-interactively(eval-last-sexp)
1490 ---------- Buffer: *Backtrace* ----------
1491
1492(As with the other times we entered the debugger, you can quit by
1493typing `q' in the `*Backtrace*' buffer.)
1494
1495This backtrace is different from the very first error message we saw,
1496which said, `Debugger entered--Lisp error: (void-function this)'. In
1497this case, the function does not have a value as a variable; while in
1498the other error message, the function (the word `this') did not have a
1499definition.
1500
1501In this experiment with the `+', what we did was cause the Lisp
1502interpreter to evaluate the `+' and look for the value of the variable
1503instead of the function definition. We did this by placing the cursor
1504right after the symbol rather than after the parenthesis of the
1505enclosing list as we did before. As a consequence, the Lisp interpreter
1506evaluated the preceding s-expression, which in this case was the `+' by
1507itself.
1508
1509Since `+' does not have a value bound to it, just the function
1510definition, the error message reported that the symbol's value as a
1511variable was void.
1512
1513
1514File: eintr, Node: Arguments, Next: set & setq, Prev: Variables, Up: List Processing
1515
15161.8 Arguments
1517=============
1518
1519To see how information is passed to functions, let's look again at our
1520old standby, the addition of two plus two. In Lisp, this is written as
1521follows:
1522
1523 (+ 2 2)
1524
1525If you evaluate this expression, the number 4 will appear in your echo
1526area. What the Lisp interpreter does is add the numbers that follow
1527the `+'.
1528
1529The numbers added by `+' are called the "arguments" of the function
1530`+'. These numbers are the information that is given to or "passed" to
1531the function.
1532
1533The word `argument' comes from the way it is used in mathematics and
1534does not refer to a disputation between two people; instead it refers to
1535the information presented to the function, in this case, to the `+'.
1536In Lisp, the arguments to a function are the atoms or lists that follow
1537the function. The values returned by the evaluation of these atoms or
1538lists are passed to the function. Different functions require
1539different numbers of arguments; some functions require none at all.(1)
1540
1541* Menu:
1542
1543* Data types::
1544* Args as Variable or List::
1545* Variable Number of Arguments::
1546* Wrong Type of Argument::
1547* message::
1548
1549---------- Footnotes ----------
1550
1551(1) It is curious to track the path by which the word `argument' came
1552to have two different meanings, one in mathematics and the other in
1553everyday English. According to the `Oxford English Dictionary', the
1554word derives from the Latin for `to make clear, prove'; thus it came to
1555mean, by one thread of derivation, `the evidence offered as proof',
1556which is to say, `the information offered', which led to its meaning in
1557Lisp. But in the other thread of derivation, it came to mean `to
1558assert in a manner against which others may make counter assertions',
1559which led to the meaning of the word as a disputation. (Note here that
1560the English word has two different definitions attached to it at the
1561same time. By contrast, in Emacs Lisp, a symbol cannot have two
1562different function definitions at the same time.)
1563
1564
1565File: eintr, Node: Data types, Next: Args as Variable or List, Prev: Arguments, Up: Arguments
1566
15671.8.1 Arguments' Data Types
1568---------------------------
1569
1570The type of data that should be passed to a function depends on what
1571kind of information it uses. The arguments to a function such as `+'
1572must have values that are numbers, since `+' adds numbers. Other
1573functions use different kinds of data for their arguments.
1574
1575For example, the `concat' function links together or unites two or more
1576strings of text to produce a string. The arguments are strings.
1577Concatenating the two character strings `abc', `def' produces the
1578single string `abcdef'. This can be seen by evaluating the following:
1579
1580 (concat "abc" "def")
1581
1582The value produced by evaluating this expression is `"abcdef"'.
1583
1584A function such as `substring' uses both a string and numbers as
1585arguments. The function returns a part of the string, a substring of
1586the first argument. This function takes three arguments. Its first
1587argument is the string of characters, the second and third arguments are
1588numbers that indicate the beginning and end of the substring. The
1589numbers are a count of the number of characters (including spaces and
1590punctuations) from the beginning of the string.
1591
1592For example, if you evaluate the following:
1593
1594 (substring "The quick brown fox jumped." 16 19)
1595
1596you will see `"fox"' appear in the echo area. The arguments are the
1597string and the two numbers.
1598
1599Note that the string passed to `substring' is a single atom even though
1600it is made up of several words separated by spaces. Lisp counts
1601everything between the two quotation marks as part of the string,
1602including the spaces. You can think of the `substring' function as a
1603kind of `atom smasher' since it takes an otherwise indivisible atom and
1604extracts a part. However, `substring' is only able to extract a
1605substring from an argument that is a string, not from another type of
1606atom such as a number or symbol.
1607
1608
1609File: eintr, Node: Args as Variable or List, Next: Variable Number of Arguments, Prev: Data types, Up: Arguments
1610
16111.8.2 An Argument as the Value of a Variable or List
1612----------------------------------------------------
1613
1614An argument can be a symbol that returns a value when it is evaluated.
1615For example, when the symbol `fill-column' by itself is evaluated, it
1616returns a number. This number can be used in an addition.
1617
1618Position the cursor after the following expression and type `C-x C-e':
1619
1620 (+ 2 fill-column)
1621
1622The value will be a number two more than what you get by evaluating
1623`fill-column' alone. For me, this is 74, because my value of
1624`fill-column' is 72.
1625
1626As we have just seen, an argument can be a symbol that returns a value
1627when evaluated. In addition, an argument can be a list that returns a
1628value when it is evaluated. For example, in the following expression,
1629the arguments to the function `concat' are the strings `"The "' and
1630`" red foxes."' and the list `(number-to-string (+ 2 fill-column))'.
1631
1632 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
1633
1634If you evaluate this expression--and if, as with my Emacs,
1635`fill-column' evaluates to 72--`"The 74 red foxes."' will appear in the
1636echo area. (Note that you must put spaces after the word `The' and
1637before the word `red' so they will appear in the final string. The
1638function `number-to-string' converts the integer that the addition
1639function returns to a string. `number-to-string' is also known as
1640`int-to-string'.)
1641
1642
1643File: eintr, Node: Variable Number of Arguments, Next: Wrong Type of Argument, Prev: Args as Variable or List, Up: Arguments
1644
16451.8.3 Variable Number of Arguments
1646----------------------------------
1647
1648Some functions, such as `concat', `+' or `*', take any number of
1649arguments. (The `*' is the symbol for multiplication.) This can be
1650seen by evaluating each of the following expressions in the usual way.
1651What you will see in the echo area is printed in this text after `=>',
1652which you may read as `evaluates to'.
1653
1654In the first set, the functions have no arguments:
1655
1656 (+) => 0
1657
1658 (*) => 1
1659
1660In this set, the functions have one argument each:
1661
1662 (+ 3) => 3
1663
1664 (* 3) => 3
1665
1666In this set, the functions have three arguments each:
1667
1668 (+ 3 4 5) => 12
1669
1670 (* 3 4 5) => 60
1671
1672
1673File: eintr, Node: Wrong Type of Argument, Next: message, Prev: Variable Number of Arguments, Up: Arguments
1674
16751.8.4 Using the Wrong Type Object as an Argument
1676------------------------------------------------
1677
1678When a function is passed an argument of the wrong type, the Lisp
1679interpreter produces an error message. For example, the `+' function
1680expects the values of its arguments to be numbers. As an experiment we
1681can pass it the quoted symbol `hello' instead of a number. Position
1682the cursor after the following expression and type `C-x C-e':
1683
1684 (+ 2 'hello)
1685
1686When you do this you will generate an error message. What has happened
1687is that `+' has tried to add the 2 to the value returned by `'hello',
1688but the value returned by `'hello' is the symbol `hello', not a number.
1689Only numbers can be added. So `+' could not carry out its addition.
1690
1691In GNU Emacs version 22, you will create and enter a `*Backtrace*'
1692buffer that says:
1693
1694
1695 ---------- Buffer: *Backtrace* ----------
1696 Debugger entered--Lisp error:
1697 (wrong-type-argument number-or-marker-p hello)
1698 +(2 hello)
1699 eval((+ 2 (quote hello)))
1700 eval-last-sexp-1(nil)
1701 eval-last-sexp(nil)
1702 call-interactively(eval-last-sexp)
1703 ---------- Buffer: *Backtrace* ----------
1704
1705As usual, the error message tries to be helpful and makes sense after
1706you learn how to read it.(1)
1707
1708The first part of the error message is straightforward; it says `wrong
1709type argument'. Next comes the mysterious jargon word
1710`number-or-marker-p'. This word is trying to tell you what kind of
1711argument the `+' expected.
1712
1713The symbol `number-or-marker-p' says that the Lisp interpreter is
1714trying to determine whether the information presented it (the value of
1715the argument) is a number or a marker (a special object representing a
1716buffer position). What it does is test to see whether the `+' is being
1717given numbers to add. It also tests to see whether the argument is
1718something called a marker, which is a specific feature of Emacs Lisp.
1719(In Emacs, locations in a buffer are recorded as markers. When the
1720mark is set with the `C-@' or `C-<SPC>' command, its position is kept
1721as a marker. The mark can be considered a number--the number of
1722characters the location is from the beginning of the buffer.) In Emacs
1723Lisp, `+' can be used to add the numeric value of marker positions as
1724numbers.
1725
1726The `p' of `number-or-marker-p' is the embodiment of a practice started
1727in the early days of Lisp programming. The `p' stands for `predicate'.
1728In the jargon used by the early Lisp researchers, a predicate refers
1729to a function to determine whether some property is true or false. So
1730the `p' tells us that `number-or-marker-p' is the name of a function
1731that determines whether it is true or false that the argument supplied
1732is a number or a marker. Other Lisp symbols that end in `p' include
1733`zerop', a function that tests whether its argument has the value of
1734zero, and `listp', a function that tests whether its argument is a list.
1735
1736Finally, the last part of the error message is the symbol `hello'.
1737This is the value of the argument that was passed to `+'. If the
1738addition had been passed the correct type of object, the value passed
1739would have been a number, such as 37, rather than a symbol like
1740`hello'. But then you would not have got the error message.
1741
1742---------- Footnotes ----------
1743
1744(1) `(quote hello)' is an expansion of the abbreviation `'hello'.
1745
1746
1747File: eintr, Node: message, Prev: Wrong Type of Argument, Up: Arguments
1748
17491.8.5 The `message' Function
1750----------------------------
1751
1752Like `+', the `message' function takes a variable number of arguments.
1753It is used to send messages to the user and is so useful that we will
1754describe it here.
1755
1756A message is printed in the echo area. For example, you can print a
1757message in your echo area by evaluating the following list:
1758
1759 (message "This message appears in the echo area!")
1760
1761The whole string between double quotation marks is a single argument
1762and is printed in toto. (Note that in this example, the message itself
1763will appear in the echo area within double quotes; that is because you
1764see the value returned by the `message' function. In most uses of
1765`message' in programs that you write, the text will be printed in the
1766echo area as a side-effect, without the quotes. *Note
1767`multiply-by-seven' in detail: multiply-by-seven in detail, for an
1768example of this.)
1769
1770However, if there is a `%s' in the quoted string of characters, the
1771`message' function does not print the `%s' as such, but looks to the
1772argument that follows the string. It evaluates the second argument and
1773prints the value at the location in the string where the `%s' is.
1774
1775You can see this by positioning the cursor after the following
1776expression and typing `C-x C-e':
1777
1778 (message "The name of this buffer is: %s." (buffer-name))
1779
1780In Info, `"The name of this buffer is: *info*."' will appear in the
1781echo area. The function `buffer-name' returns the name of the buffer
1782as a string, which the `message' function inserts in place of `%s'.
1783
1784To print a value as an integer, use `%d' in the same way as `%s'. For
1785example, to print a message in the echo area that states the value of
1786the `fill-column', evaluate the following:
1787
1788 (message "The value of fill-column is %d." fill-column)
1789
1790On my system, when I evaluate this list, `"The value of fill-column is
179172."' appears in my echo area(1).
1792
1793If there is more than one `%s' in the quoted string, the value of the
1794first argument following the quoted string is printed at the location
1795of the first `%s' and the value of the second argument is printed at
1796the location of the second `%s', and so on.
1797
1798For example, if you evaluate the following,
1799
1800 (message "There are %d %s in the office!"
1801 (- fill-column 14) "pink elephants")
1802
1803a rather whimsical message will appear in your echo area. On my system
1804it says, `"There are 58 pink elephants in the office!"'.
1805
1806The expression `(- fill-column 14)' is evaluated and the resulting
1807number is inserted in place of the `%d'; and the string in double
1808quotes, `"pink elephants"', is treated as a single argument and
1809inserted in place of the `%s'. (That is to say, a string between
1810double quotes evaluates to itself, like a number.)
1811
1812Finally, here is a somewhat complex example that not only illustrates
1813the computation of a number, but also shows how you can use an
1814expression within an expression to generate the text that is substituted
1815for `%s':
1816
1817 (message "He saw %d %s"
1818 (- fill-column 32)
1819 (concat "red "
1820 (substring
1821 "The quick brown foxes jumped." 16 21)
1822 " leaping."))
1823
1824In this example, `message' has three arguments: the string, `"He saw %d
1825%s"', the expression, `(- fill-column 32)', and the expression
1826beginning with the function `concat'. The value resulting from the
1827evaluation of `(- fill-column 32)' is inserted in place of the `%d';
1828and the value returned by the expression beginning with `concat' is
1829inserted in place of the `%s'.
1830
1831When your fill column is 70 and you evaluate the expression, the
1832message `"He saw 38 red foxes leaping."' appears in your echo area.
1833
1834---------- Footnotes ----------
1835
1836(1) Actually, you can use `%s' to print a number. It is non-specific.
1837`%d' prints only the part of a number left of a decimal point, and not
1838anything that is not a number.
1839
1840
1841File: eintr, Node: set & setq, Next: Summary, Prev: Arguments, Up: List Processing
1842
18431.9 Setting the Value of a Variable
1844===================================
1845
1846There are several ways by which a variable can be given a value. One of
1847the ways is to use either the function `set' or the function `setq'.
1848Another way is to use `let' (*note let::). (The jargon for this
1849process is to "bind" a variable to a value.)
1850
1851The following sections not only describe how `set' and `setq' work but
1852also illustrate how arguments are passed.
1853
1854* Menu:
1855
1856* Using set::
1857* Using setq::
1858* Counting::
1859
1860
1861File: eintr, Node: Using set, Next: Using setq, Prev: set & setq, Up: set & setq
1862
18631.9.1 Using `set'
1864-----------------
1865
1866To set the value of the symbol `flowers' to the list `'(rose violet
1867daisy buttercup)', evaluate the following expression by positioning the
1868cursor after the expression and typing `C-x C-e'.
1869
1870 (set 'flowers '(rose violet daisy buttercup))
1871
1872The list `(rose violet daisy buttercup)' will appear in the echo area.
1873This is what is _returned_ by the `set' function. As a side effect,
1874the symbol `flowers' is bound to the list; that is, the symbol
1875`flowers', which can be viewed as a variable, is given the list as its
1876value. (This process, by the way, illustrates how a side effect to the
1877Lisp interpreter, setting the value, can be the primary effect that we
1878humans are interested in. This is because every Lisp function must
1879return a value if it does not get an error, but it will only have a
1880side effect if it is designed to have one.)
1881
1882After evaluating the `set' expression, you can evaluate the symbol
1883`flowers' and it will return the value you just set. Here is the
1884symbol. Place your cursor after it and type `C-x C-e'.
1885
1886 flowers
1887
1888When you evaluate `flowers', the list `(rose violet daisy buttercup)'
1889appears in the echo area.
1890
1891Incidentally, if you evaluate `'flowers', the variable with a quote in
1892front of it, what you will see in the echo area is the symbol itself,
1893`flowers'. Here is the quoted symbol, so you can try this:
1894
1895 'flowers
1896
1897Note also, that when you use `set', you need to quote both arguments to
1898`set', unless you want them evaluated. Since we do not want either
1899argument evaluated, neither the variable `flowers' nor the list `(rose
1900violet daisy buttercup)', both are quoted. (When you use `set' without
1901quoting its first argument, the first argument is evaluated before
1902anything else is done. If you did this and `flowers' did not have a
1903value already, you would get an error message that the `Symbol's value
1904as variable is void'; on the other hand, if `flowers' did return a
1905value after it was evaluated, the `set' would attempt to set the value
1906that was returned. There are situations where this is the right thing
1907for the function to do; but such situations are rare.)
1908
1909
1910File: eintr, Node: Using setq, Next: Counting, Prev: Using set, Up: set & setq
1911
19121.9.2 Using `setq'
1913------------------
1914
1915As a practical matter, you almost always quote the first argument to
1916`set'. The combination of `set' and a quoted first argument is so
1917common that it has its own name: the special form `setq'. This special
1918form is just like `set' except that the first argument is quoted
1919automatically, so you don't need to type the quote mark yourself.
1920Also, as an added convenience, `setq' permits you to set several
1921different variables to different values, all in one expression.
1922
1923To set the value of the variable `carnivores' to the list `'(lion tiger
1924leopard)' using `setq', the following expression is used:
1925
1926 (setq carnivores '(lion tiger leopard))
1927
1928This is exactly the same as using `set' except the first argument is
1929automatically quoted by `setq'. (The `q' in `setq' means `quote'.)
1930
1931With `set', the expression would look like this:
1932
1933 (set 'carnivores '(lion tiger leopard))
1934
1935Also, `setq' can be used to assign different values to different
1936variables. The first argument is bound to the value of the second
1937argument, the third argument is bound to the value of the fourth
1938argument, and so on. For example, you could use the following to
1939assign a list of trees to the symbol `trees' and a list of herbivores
1940to the symbol `herbivores':
1941
1942 (setq trees '(pine fir oak maple)
1943 herbivores '(gazelle antelope zebra))
1944
1945(The expression could just as well have been on one line, but it might
1946not have fit on a page; and humans find it easier to read nicely
1947formatted lists.)
1948
1949Although I have been using the term `assign', there is another way of
1950thinking about the workings of `set' and `setq'; and that is to say
1951that `set' and `setq' make the symbol _point_ to the list. This latter
1952way of thinking is very common and in forthcoming chapters we shall
1953come upon at least one symbol that has `pointer' as part of its name.
1954The name is chosen because the symbol has a value, specifically a list,
1955attached to it; or, expressed another way, the symbol is set to "point"
1956to the list.
1957
1958
1959File: eintr, Node: Counting, Prev: Using setq, Up: set & setq
1960
19611.9.3 Counting
1962--------------
1963
1964Here is an example that shows how to use `setq' in a counter. You
1965might use this to count how many times a part of your program repeats
1966itself. First set a variable to zero; then add one to the number each
1967time the program repeats itself. To do this, you need a variable that
1968serves as a counter, and two expressions: an initial `setq' expression
1969that sets the counter variable to zero; and a second `setq' expression
1970that increments the counter each time it is evaluated.
1971
1972 (setq counter 0) ; Let's call this the initializer.
1973
1974 (setq counter (+ counter 1)) ; This is the incrementer.
1975
1976 counter ; This is the counter.
1977
1978(The text following the `;' are comments. *Note Change a Function
1979Definition: Change a defun.)
1980
1981If you evaluate the first of these expressions, the initializer, `(setq
1982counter 0)', and then evaluate the third expression, `counter', the
1983number `0' will appear in the echo area. If you then evaluate the
1984second expression, the incrementer, `(setq counter (+ counter 1))', the
1985counter will get the value 1. So if you again evaluate `counter', the
1986number `1' will appear in the echo area. Each time you evaluate the
1987second expression, the value of the counter will be incremented.
1988
1989When you evaluate the incrementer, `(setq counter (+ counter 1))', the
1990Lisp interpreter first evaluates the innermost list; this is the
1991addition. In order to evaluate this list, it must evaluate the variable
1992`counter' and the number `1'. When it evaluates the variable
1993`counter', it receives its current value. It passes this value and the
1994number `1' to the `+' which adds them together. The sum is then
1995returned as the value of the inner list and passed to the `setq' which
1996sets the variable `counter' to this new value. Thus, the value of the
1997variable, `counter', is changed.
1998
1999
2000File: eintr, Node: Summary, Next: Error Message Exercises, Prev: set & setq, Up: List Processing
2001
20021.10 Summary
2003============
2004
2005Learning Lisp is like climbing a hill in which the first part is the
2006steepest. You have now climbed the most difficult part; what remains
2007becomes easier as you progress onwards.
2008
2009In summary,
2010
2011 * Lisp programs are made up of expressions, which are lists or
2012 single atoms.
2013
2014 * Lists are made up of zero or more atoms or inner lists, separated
2015 by whitespace and surrounded by parentheses. A list can be empty.
2016
2017 * Atoms are multi-character symbols, like `forward-paragraph', single
2018 character symbols like `+', strings of characters between double
2019 quotation marks, or numbers.
2020
2021 * A number evaluates to itself.
2022
2023 * A string between double quotes also evaluates to itself.
2024
2025 * When you evaluate a symbol by itself, its value is returned.
2026
2027 * When you evaluate a list, the Lisp interpreter looks at the first
2028 symbol in the list and then at the function definition bound to
2029 that symbol. Then the instructions in the function definition are
2030 carried out.
2031
2032 * A single quotation mark, ' , tells the Lisp interpreter that it
2033 should return the following expression as written, and not
2034 evaluate it as it would if the quote were not there.
2035
2036 * Arguments are the information passed to a function. The arguments
2037 to a function are computed by evaluating the rest of the elements
2038 of the list of which the function is the first element.
2039
2040 * A function always returns a value when it is evaluated (unless it
2041 gets an error); in addition, it may also carry out some action
2042 called a "side effect". In many cases, a function's primary
2043 purpose is to create a side effect.
2044
2045
2046File: eintr, Node: Error Message Exercises, Prev: Summary, Up: List Processing
2047
20481.11 Exercises
2049==============
2050
2051A few simple exercises:
2052
2053 * Generate an error message by evaluating an appropriate symbol that
2054 is not within parentheses.
2055
2056 * Generate an error message by evaluating an appropriate symbol that
2057 is between parentheses.
2058
2059 * Create a counter that increments by two rather than one.
2060
2061 * Write an expression that prints a message in the echo area when
2062 evaluated.
2063
2064
2065File: eintr, Node: Practicing Evaluation, Next: Writing Defuns, Prev: List Processing, Up: Top
2066
20672 Practicing Evaluation
2068***********************
2069
2070Before learning how to write a function definition in Emacs Lisp, it is
2071useful to spend a little time evaluating various expressions that have
2072already been written. These expressions will be lists with the
2073functions as their first (and often only) element. Since some of the
2074functions associated with buffers are both simple and interesting, we
2075will start with those. In this section, we will evaluate a few of
2076these. In another section, we will study the code of several other
2077buffer-related functions, to see how they were written.
2078
2079* Menu:
2080
2081* How to Evaluate::
2082* Buffer Names::
2083* Getting Buffers::
2084* Switching Buffers::
2085* Buffer Size & Locations::
2086* Evaluation Exercise::
2087
2088
2089File: eintr, Node: How to Evaluate, Next: Buffer Names, Prev: Practicing Evaluation, Up: Practicing Evaluation
2090
2091How to Evaluate
2092===============
2093
2094Whenever you give an editing command to Emacs Lisp, such as the command
2095to move the cursor or to scroll the screen, you are evaluating an
2096expression, the first element of which is a function. This is how
2097Emacs works.
2098
2099When you type keys, you cause the Lisp interpreter to evaluate an
2100expression and that is how you get your results. Even typing plain text
2101involves evaluating an Emacs Lisp function, in this case, one that uses
2102`self-insert-command', which simply inserts the character you typed.
2103The functions you evaluate by typing keystrokes are called
2104"interactive" functions, or "commands"; how you make a function
2105interactive will be illustrated in the chapter on how to write function
2106definitions. *Note Making a Function Interactive: Interactive.
2107
2108In addition to typing keyboard commands, we have seen a second way to
2109evaluate an expression: by positioning the cursor after a list and
2110typing `C-x C-e'. This is what we will do in the rest of this section.
2111There are other ways to evaluate an expression as well; these will be
2112described as we come to them.
2113
2114Besides being used for practicing evaluation, the functions shown in the
2115next few sections are important in their own right. A study of these
2116functions makes clear the distinction between buffers and files, how to
2117switch to a buffer, and how to determine a location within it.
2118
2119
2120File: eintr, Node: Buffer Names, Next: Getting Buffers, Prev: How to Evaluate, Up: Practicing Evaluation
2121
21222.1 Buffer Names
2123================
2124
2125The two functions, `buffer-name' and `buffer-file-name', show the
2126difference between a file and a buffer. When you evaluate the
2127following expression, `(buffer-name)', the name of the buffer appears
2128in the echo area. When you evaluate `(buffer-file-name)', the name of
2129the file to which the buffer refers appears in the echo area. Usually,
2130the name returned by `(buffer-name)' is the same as the name of the
2131file to which it refers, and the name returned by `(buffer-file-name)'
2132is the full path-name of the file.
2133
2134A file and a buffer are two different entities. A file is information
2135recorded permanently in the computer (unless you delete it). A buffer,
2136on the other hand, is information inside of Emacs that will vanish at
2137the end of the editing session (or when you kill the buffer). Usually,
2138a buffer contains information that you have copied from a file; we say
2139the buffer is "visiting" that file. This copy is what you work on and
2140modify. Changes to the buffer do not change the file, until you save
2141the buffer. When you save the buffer, the buffer is copied to the file
2142and is thus saved permanently.
2143
2144If you are reading this in Info inside of GNU Emacs, you can evaluate
2145each of the following expressions by positioning the cursor after it and
2146typing `C-x C-e'.
2147
2148 (buffer-name)
2149
2150 (buffer-file-name)
2151
2152When I do this in Info, the value returned by evaluating
2153`(buffer-name)' is `"*info*"', and the value returned by evaluating
2154`(buffer-file-name)' is `nil'.
2155
2156On the other hand, while I am writing this Introduction, the value
2157returned by evaluating `(buffer-name)' is `"introduction.texinfo"', and
2158the value returned by evaluating `(buffer-file-name)' is
2159`"/gnu/work/intro/introduction.texinfo"'.
2160
2161The former is the name of the buffer and the latter is the name of the
2162file. In Info, the buffer name is `"*info*"'. Info does not point to
2163any file, so the result of evaluating `(buffer-file-name)' is `nil'.
2164The symbol `nil' is from the Latin word for `nothing'; in this case, it
2165means that the buffer is not associated with any file. (In Lisp, `nil'
2166is also used to mean `false' and is a synonym for the empty list, `()'.)
2167
2168When I am writing, the name of my buffer is `"introduction.texinfo"'.
2169The name of the file to which it points is
2170`"/gnu/work/intro/introduction.texinfo"'.
2171
2172(In the expressions, the parentheses tell the Lisp interpreter to treat
2173`buffer-name' and `buffer-file-name' as functions; without the
2174parentheses, the interpreter would attempt to evaluate the symbols as
2175variables. *Note Variables::.)
2176
2177In spite of the distinction between files and buffers, you will often
2178find that people refer to a file when they mean a buffer and vice-verse.
2179Indeed, most people say, "I am editing a file," rather than saying, "I
2180am editing a buffer which I will soon save to a file." It is almost
2181always clear from context what people mean. When dealing with computer
2182programs, however, it is important to keep the distinction in mind,
2183since the computer is not as smart as a person.
2184
2185The word `buffer', by the way, comes from the meaning of the word as a
2186cushion that deadens the force of a collision. In early computers, a
2187buffer cushioned the interaction between files and the computer's
2188central processing unit. The drums or tapes that held a file and the
2189central processing unit were pieces of equipment that were very
2190different from each other, working at their own speeds, in spurts. The
2191buffer made it possible for them to work together effectively.
2192Eventually, the buffer grew from being an intermediary, a temporary
2193holding place, to being the place where work is done. This
2194transformation is rather like that of a small seaport that grew into a
2195great city: once it was merely the place where cargo was warehoused
2196temporarily before being loaded onto ships; then it became a business
2197and cultural center in its own right.
2198
2199Not all buffers are associated with files. For example, a `*scratch*'
2200buffer does not visit any file. Similarly, a `*Help*' buffer is not
2201associated with any file.
2202
2203In the old days, when you lacked a `~/.emacs' file and started an Emacs
2204session by typing the command `emacs' alone, without naming any files,
2205Emacs started with the `*scratch*' buffer visible. Nowadays, you will
2206see a splash screen. You can follow one of the commands suggested on
2207the splash screen, visit a file, or press the spacebar to reach the
2208`*scratch*' buffer.
2209
2210If you switch to the `*scratch*' buffer, type `(buffer-name)', position
2211the cursor after it, and then type `C-x C-e' to evaluate the
2212expression. The name `"*scratch*"' will be returned and will appear in
2213the echo area. `"*scratch*"' is the name of the buffer. When you type
2214`(buffer-file-name)' in the `*scratch*' buffer and evaluate that, `nil'
2215will appear in the echo area, just as it does when you evaluate
2216`(buffer-file-name)' in Info.
2217
2218Incidentally, if you are in the `*scratch*' buffer and want the value
2219returned by an expression to appear in the `*scratch*' buffer itself
2220rather than in the echo area, type `C-u C-x C-e' instead of `C-x C-e'.
2221This causes the value returned to appear after the expression. The
2222buffer will look like this:
2223
2224 (buffer-name)"*scratch*"
2225
2226You cannot do this in Info since Info is read-only and it will not allow
2227you to change the contents of the buffer. But you can do this in any
2228buffer you can edit; and when you write code or documentation (such as
2229this book), this feature is very useful.
2230
2231
2232File: eintr, Node: Getting Buffers, Next: Switching Buffers, Prev: Buffer Names, Up: Practicing Evaluation
2233
22342.2 Getting Buffers
2235===================
2236
2237The `buffer-name' function returns the _name_ of the buffer; to get the
2238buffer _itself_, a different function is needed: the `current-buffer'
2239function. If you use this function in code, what you get is the buffer
2240itself.
2241
2242A name and the object or entity to which the name refers are different
2243from each other. You are not your name. You are a person to whom
2244others refer by name. If you ask to speak to George and someone hands
2245you a card with the letters `G', `e', `o', `r', `g', and `e' written on
2246it, you might be amused, but you would not be satisfied. You do not
2247want to speak to the name, but to the person to whom the name refers.
2248A buffer is similar: the name of the scratch buffer is `*scratch*', but
2249the name is not the buffer. To get a buffer itself, you need to use a
2250function such as `current-buffer'.
2251
2252However, there is a slight complication: if you evaluate
2253`current-buffer' in an expression on its own, as we will do here, what
2254you see is a printed representation of the name of the buffer without
2255the contents of the buffer. Emacs works this way for two reasons: the
2256buffer may be thousands of lines long--too long to be conveniently
2257displayed; and, another buffer may have the same contents but a
2258different name, and it is important to distinguish between them.
2259
2260Here is an expression containing the function:
2261
2262 (current-buffer)
2263
2264If you evaluate this expression in Info in Emacs in the usual way,
2265`#<buffer *info*>' will appear in the echo area. The special format
2266indicates that the buffer itself is being returned, rather than just
2267its name.
2268
2269Incidentally, while you can type a number or symbol into a program, you
2270cannot do that with the printed representation of a buffer: the only way
2271to get a buffer itself is with a function such as `current-buffer'.
2272
2273A related function is `other-buffer'. This returns the most recently
2274selected buffer other than the one you are in currently, not a printed
2275representation of its name. If you have recently switched back and
2276forth from the `*scratch*' buffer, `other-buffer' will return that
2277buffer.
2278
2279You can see this by evaluating the expression:
2280
2281 (other-buffer)
2282
2283You should see `#<buffer *scratch*>' appear in the echo area, or the
2284name of whatever other buffer you switched back from most recently(1).
2285
2286---------- Footnotes ----------
2287
2288(1) Actually, by default, if the buffer from which you just switched is
2289visible to you in another window, `other-buffer' will choose the most
2290recent buffer that you cannot see; this is a subtlety that I often
2291forget.
2292
2293
2294File: eintr, Node: Switching Buffers, Next: Buffer Size & Locations, Prev: Getting Buffers, Up: Practicing Evaluation
2295
22962.3 Switching Buffers
2297=====================
2298
2299The `other-buffer' function actually provides a buffer when it is used
2300as an argument to a function that requires one. We can see this by
2301using `other-buffer' and `switch-to-buffer' to switch to a different
2302buffer.
2303
2304But first, a brief introduction to the `switch-to-buffer' function.
2305When you switched back and forth from Info to the `*scratch*' buffer to
2306evaluate `(buffer-name)', you most likely typed `C-x b' and then typed
2307`*scratch*'(1) when prompted in the minibuffer for the name of the
2308buffer to which you wanted to switch. The keystrokes, `C-x b', cause
2309the Lisp interpreter to evaluate the interactive function
2310`switch-to-buffer'. As we said before, this is how Emacs works:
2311different keystrokes call or run different functions. For example,
2312`C-f' calls `forward-char', `M-e' calls `forward-sentence', and so on.
2313
2314By writing `switch-to-buffer' in an expression, and giving it a buffer
2315to switch to, we can switch buffers just the way `C-x b' does.
2316
2317Here is the Lisp expression:
2318
2319 (switch-to-buffer (other-buffer))
2320
2321The symbol `switch-to-buffer' is the first element of the list, so the
2322Lisp interpreter will treat it as a function and carry out the
2323instructions that are attached to it. But before doing that, the
2324interpreter will note that `other-buffer' is inside parentheses and
2325work on that symbol first. `other-buffer' is the first (and in this
2326case, the only) element of this list, so the Lisp interpreter calls or
2327runs the function. It returns another buffer. Next, the interpreter
2328runs `switch-to-buffer', passing to it, as an argument, the other
2329buffer, which is what Emacs will switch to. If you are reading this in
2330Info, try this now. Evaluate the expression. (To get back, type `C-x
2331b <RET>'.)(2)
2332
2333In the programming examples in later sections of this document, you will
2334see the function `set-buffer' more often than `switch-to-buffer'. This
2335is because of a difference between computer programs and humans: humans
2336have eyes and expect to see the buffer on which they are working on
2337their computer terminals. This is so obvious, it almost goes without
2338saying. However, programs do not have eyes. When a computer program
2339works on a buffer, that buffer does not need to be visible on the
2340screen.
2341
2342`switch-to-buffer' is designed for humans and does two different
2343things: it switches the buffer to which Emacs' attention is directed;
2344and it switches the buffer displayed in the window to the new buffer.
2345`set-buffer', on the other hand, does only one thing: it switches the
2346attention of the computer program to a different buffer. The buffer on
2347the screen remains unchanged (of course, normally nothing happens there
2348until the command finishes running).
2349
2350Also, we have just introduced another jargon term, the word "call".
2351When you evaluate a list in which the first symbol is a function, you
2352are calling that function. The use of the term comes from the notion of
2353the function as an entity that can do something for you if you `call'
2354it--just as a plumber is an entity who can fix a leak if you call him
2355or her.
2356
2357---------- Footnotes ----------
2358
2359(1) Or rather, to save typing, you probably only typed `RET' if the
2360default buffer was `*scratch*', or if it was different, then you typed
2361just part of the name, such as `*sc', pressed your `TAB' key to cause
2362it to expand to the full name, and then typed your `RET' key.
2363
2364(2) Remember, this expression will move you to your most recent other
2365buffer that you cannot see. If you really want to go to your most
2366recently selected buffer, even if you can still see it, you need to
2367evaluate the following more complex expression:
2368
2369 (switch-to-buffer (other-buffer (current-buffer) t))
2370
2371In this case, the first argument to `other-buffer' tells it which
2372buffer to skip--the current one--and the second argument tells
2373`other-buffer' it is OK to switch to a visible buffer. In regular use,
2374`switch-to-buffer' takes you to an invisible window since you would
2375most likely use `C-x o' (`other-window') to go to another visible
2376buffer.
2377
2378
2379File: eintr, Node: Buffer Size & Locations, Next: Evaluation Exercise, Prev: Switching Buffers, Up: Practicing Evaluation
2380
23812.4 Buffer Size and the Location of Point
2382=========================================
2383
2384Finally, let's look at several rather simple functions, `buffer-size',
2385`point', `point-min', and `point-max'. These give information about
2386the size of a buffer and the location of point within it.
2387
2388The function `buffer-size' tells you the size of the current buffer;
2389that is, the function returns a count of the number of characters in
2390the buffer.
2391
2392 (buffer-size)
2393
2394You can evaluate this in the usual way, by positioning the cursor after
2395the expression and typing `C-x C-e'.
2396
2397In Emacs, the current position of the cursor is called "point". The
2398expression `(point)' returns a number that tells you where the cursor
2399is located as a count of the number of characters from the beginning of
2400the buffer up to point.
2401
2402You can see the character count for point in this buffer by evaluating
2403the following expression in the usual way:
2404
2405 (point)
2406
2407As I write this, the value of `point' is 65724. The `point' function
2408is frequently used in some of the examples later in this book.
2409
2410The value of point depends, of course, on its location within the
2411buffer. If you evaluate point in this spot, the number will be larger:
2412
2413 (point)
2414
2415For me, the value of point in this location is 66043, which means that
2416there are 319 characters (including spaces) between the two expressions.
2417
2418The function `point-min' is somewhat similar to `point', but it returns
2419the value of the minimum permissible value of point in the current
2420buffer. This is the number 1 unless "narrowing" is in effect.
2421(Narrowing is a mechanism whereby you can restrict yourself, or a
2422program, to operations on just a part of a buffer. *Note Narrowing and
2423Widening: Narrowing & Widening.) Likewise, the function `point-max'
2424returns the value of the maximum permissible value of point in the
2425current buffer.
2426
2427
2428File: eintr, Node: Evaluation Exercise, Prev: Buffer Size & Locations, Up: Practicing Evaluation
2429
24302.5 Exercise
2431============
2432
2433Find a file with which you are working and move towards its middle.
2434Find its buffer name, file name, length, and your position in the file.
2435
2436
2437File: eintr, Node: Writing Defuns, Next: Buffer Walk Through, Prev: Practicing Evaluation, Up: Top
2438
24393 How To Write Function Definitions
2440***********************************
2441
2442When the Lisp interpreter evaluates a list, it looks to see whether the
2443first symbol on the list has a function definition attached to it; or,
2444put another way, whether the symbol points to a function definition. If
2445it does, the computer carries out the instructions in the definition. A
2446symbol that has a function definition is called, simply, a function
2447(although, properly speaking, the definition is the function and the
2448symbol refers to it.)
2449
2450* Menu:
2451
2452* Primitive Functions::
2453* defun::
2454* Install::
2455* Interactive::
2456* Interactive Options::
2457* Permanent Installation::
2458* let::
2459* if::
2460* else::
2461* Truth & Falsehood::
2462* save-excursion::
2463* Review::
2464* defun Exercises::
2465
2466
2467File: eintr, Node: Primitive Functions, Next: defun, Prev: Writing Defuns, Up: Writing Defuns
2468
2469An Aside about Primitive Functions
2470==================================
2471
2472All functions are defined in terms of other functions, except for a few
2473"primitive" functions that are written in the C programming language.
2474When you write functions' definitions, you will write them in Emacs
2475Lisp and use other functions as your building blocks. Some of the
2476functions you will use will themselves be written in Emacs Lisp (perhaps
2477by you) and some will be primitives written in C. The primitive
2478functions are used exactly like those written in Emacs Lisp and behave
2479like them. They are written in C so we can easily run GNU Emacs on any
2480computer that has sufficient power and can run C.
2481
2482Let me re-emphasize this: when you write code in Emacs Lisp, you do not
2483distinguish between the use of functions written in C and the use of
2484functions written in Emacs Lisp. The difference is irrelevant. I
2485mention the distinction only because it is interesting to know. Indeed,
2486unless you investigate, you won't know whether an already-written
2487function is written in Emacs Lisp or C.
2488
2489
2490File: eintr, Node: defun, Next: Install, Prev: Primitive Functions, Up: Writing Defuns
2491
24923.1 The `defun' Special Form
2493============================
2494
2495In Lisp, a symbol such as `mark-whole-buffer' has code attached to it
2496that tells the computer what to do when the function is called. This
2497code is called the "function definition" and is created by evaluating a
2498Lisp expression that starts with the symbol `defun' (which is an
2499abbreviation for _define function_). Because `defun' does not evaluate
2500its arguments in the usual way, it is called a "special form".
2501
2502In subsequent sections, we will look at function definitions from the
2503Emacs source code, such as `mark-whole-buffer'. In this section, we
2504will describe a simple function definition so you can see how it looks.
2505This function definition uses arithmetic because it makes for a simple
2506example. Some people dislike examples using arithmetic; however, if
2507you are such a person, do not despair. Hardly any of the code we will
2508study in the remainder of this introduction involves arithmetic or
2509mathematics. The examples mostly involve text in one way or another.
2510
2511A function definition has up to five parts following the word `defun':
2512
2513 1. The name of the symbol to which the function definition should be
2514 attached.
2515
2516 2. A list of the arguments that will be passed to the function. If no
2517 arguments will be passed to the function, this is an empty list,
2518 `()'.
2519
2520 3. Documentation describing the function. (Technically optional, but
2521 strongly recommended.)
2522
2523 4. Optionally, an expression to make the function interactive so you
2524 can use it by typing `M-x' and then the name of the function; or by
2525 typing an appropriate key or keychord.
2526
2527 5. The code that instructs the computer what to do: the "body" of the
2528 function definition.
2529
2530It is helpful to think of the five parts of a function definition as
2531being organized in a template, with slots for each part:
2532
2533 (defun FUNCTION-NAME (ARGUMENTS...)
2534 "OPTIONAL-DOCUMENTATION..."
2535 (interactive ARGUMENT-PASSING-INFO) ; optional
2536 BODY...)
2537
2538As an example, here is the code for a function that multiplies its
2539argument by 7. (This example is not interactive. *Note Making a
2540Function Interactive: Interactive, for that information.)
2541
2542 (defun multiply-by-seven (number)
2543 "Multiply NUMBER by seven."
2544 (* 7 number))
2545
2546This definition begins with a parenthesis and the symbol `defun',
2547followed by the name of the function.
2548
2549The name of the function is followed by a list that contains the
2550arguments that will be passed to the function. This list is called the
2551"argument list". In this example, the list has only one element, the
2552symbol, `number'. When the function is used, the symbol will be bound
2553to the value that is used as the argument to the function.
2554
2555Instead of choosing the word `number' for the name of the argument, I
2556could have picked any other name. For example, I could have chosen the
2557word `multiplicand'. I picked the word `number' because it tells what
2558kind of value is intended for this slot; but I could just as well have
2559chosen the word `multiplicand' to indicate the role that the value
2560placed in this slot will play in the workings of the function. I could
2561have called it `foogle', but that would have been a bad choice because
2562it would not tell humans what it means. The choice of name is up to
2563the programmer and should be chosen to make the meaning of the function
2564clear.
2565
2566Indeed, you can choose any name you wish for a symbol in an argument
2567list, even the name of a symbol used in some other function: the name
2568you use in an argument list is private to that particular definition.
2569In that definition, the name refers to a different entity than any use
2570of the same name outside the function definition. Suppose you have a
2571nick-name `Shorty' in your family; when your family members refer to
2572`Shorty', they mean you. But outside your family, in a movie, for
2573example, the name `Shorty' refers to someone else. Because a name in an
2574argument list is private to the function definition, you can change the
2575value of such a symbol inside the body of a function without changing
2576its value outside the function. The effect is similar to that produced
2577by a `let' expression. (*Note `let': let.)
2578
2579The argument list is followed by the documentation string that
2580describes the function. This is what you see when you type `C-h f' and
2581the name of a function. Incidentally, when you write a documentation
2582string like this, you should make the first line a complete sentence
2583since some commands, such as `apropos', print only the first line of a
2584multi-line documentation string. Also, you should not indent the
2585second line of a documentation string, if you have one, because that
2586looks odd when you use `C-h f' (`describe-function'). The
2587documentation string is optional, but it is so useful, it should be
2588included in almost every function you write.
2589
2590The third line of the example consists of the body of the function
2591definition. (Most functions' definitions, of course, are longer than
2592this.) In this function, the body is the list, `(* 7 number)', which
2593says to multiply the value of NUMBER by 7. (In Emacs Lisp, `*' is the
2594function for multiplication, just as `+' is the function for addition.)
2595
2596When you use the `multiply-by-seven' function, the argument `number'
2597evaluates to the actual number you want used. Here is an example that
2598shows how `multiply-by-seven' is used; but don't try to evaluate this
2599yet!
2600
2601 (multiply-by-seven 3)
2602
2603The symbol `number', specified in the function definition in the next
2604section, is given or "bound to" the value 3 in the actual use of the
2605function. Note that although `number' was inside parentheses in the
2606function definition, the argument passed to the `multiply-by-seven'
2607function is not in parentheses. The parentheses are written in the
2608function definition so the computer can figure out where the argument
2609list ends and the rest of the function definition begins.
2610
2611If you evaluate this example, you are likely to get an error message.
2612(Go ahead, try it!) This is because we have written the function
2613definition, but not yet told the computer about the definition--we have
2614not yet installed (or `loaded') the function definition in Emacs.
2615Installing a function is the process that tells the Lisp interpreter the
2616definition of the function. Installation is described in the next
2617section.
2618
2619
2620File: eintr, Node: Install, Next: Interactive, Prev: defun, Up: Writing Defuns
2621
26223.2 Install a Function Definition
2623=================================
2624
2625If you are reading this inside of Info in Emacs, you can try out the
2626`multiply-by-seven' function by first evaluating the function
2627definition and then evaluating `(multiply-by-seven 3)'. A copy of the
2628function definition follows. Place the cursor after the last
2629parenthesis of the function definition and type `C-x C-e'. When you do
2630this, `multiply-by-seven' will appear in the echo area. (What this
2631means is that when a function definition is evaluated, the value it
2632returns is the name of the defined function.) At the same time, this
2633action installs the function definition.
2634
2635 (defun multiply-by-seven (number)
2636 "Multiply NUMBER by seven."
2637 (* 7 number))
2638
2639By evaluating this `defun', you have just installed `multiply-by-seven'
2640in Emacs. The function is now just as much a part of Emacs as
2641`forward-word' or any other editing function you use.
2642(`multiply-by-seven' will stay installed until you quit Emacs. To
2643reload code automatically whenever you start Emacs, see *Note
2644Installing Code Permanently: Permanent Installation.)
2645
2646* Menu:
2647
2648* Effect of installation::
2649* Change a defun::
2650
2651
2652File: eintr, Node: Effect of installation, Next: Change a defun, Prev: Install, Up: Install
2653
2654The effect of installation
2655--------------------------
2656
2657You can see the effect of installing `multiply-by-seven' by evaluating
2658the following sample. Place the cursor after the following expression
2659and type `C-x C-e'. The number 21 will appear in the echo area.
2660
2661 (multiply-by-seven 3)
2662
2663If you wish, you can read the documentation for the function by typing
2664`C-h f' (`describe-function') and then the name of the function,
2665`multiply-by-seven'. When you do this, a `*Help*' window will appear
2666on your screen that says:
2667
2668 multiply-by-seven is a Lisp function.
2669 (multiply-by-seven NUMBER)
2670
2671 Multiply NUMBER by seven.
2672
2673(To return to a single window on your screen, type `C-x 1'.)
2674
2675
2676File: eintr, Node: Change a defun, Prev: Effect of installation, Up: Install
2677
26783.2.1 Change a Function Definition
2679----------------------------------
2680
2681If you want to change the code in `multiply-by-seven', just rewrite it.
2682To install the new version in place of the old one, evaluate the
2683function definition again. This is how you modify code in Emacs. It is
2684very simple.
2685
2686As an example, you can change the `multiply-by-seven' function to add
2687the number to itself seven times instead of multiplying the number by
2688seven. It produces the same answer, but by a different path. At the
2689same time, we will add a comment to the code; a comment is text that
2690the Lisp interpreter ignores, but that a human reader may find useful
2691or enlightening. The comment is that this is the "second version".
2692
2693 (defun multiply-by-seven (number) ; Second version.
2694 "Multiply NUMBER by seven."
2695 (+ number number number number number number number))
2696
2697The comment follows a semicolon, `;'. In Lisp, everything on a line
2698that follows a semicolon is a comment. The end of the line is the end
2699of the comment. To stretch a comment over two or more lines, begin
2700each line with a semicolon.
2701
2702*Note Beginning a `.emacs' File: Beginning a .emacs File, and *Note
2703Comments: (elisp)Comments, for more about comments.
2704
2705You can install this version of the `multiply-by-seven' function by
2706evaluating it in the same way you evaluated the first function: place
2707the cursor after the last parenthesis and type `C-x C-e'.
2708
2709In summary, this is how you write code in Emacs Lisp: you write a
2710function; install it; test it; and then make fixes or enhancements and
2711install it again.
2712
2713
2714File: eintr, Node: Interactive, Next: Interactive Options, Prev: Install, Up: Writing Defuns
2715
27163.3 Make a Function Interactive
2717===============================
2718
2719You make a function interactive by placing a list that begins with the
2720special form `interactive' immediately after the documentation. A user
2721can invoke an interactive function by typing `M-x' and then the name of
2722the function; or by typing the keys to which it is bound, for example,
2723by typing `C-n' for `next-line' or `C-x h' for `mark-whole-buffer'.
2724
2725Interestingly, when you call an interactive function interactively, the
2726value returned is not automatically displayed in the echo area. This
2727is because you often call an interactive function for its side effects,
2728such as moving forward by a word or line, and not for the value
2729returned. If the returned value were displayed in the echo area each
2730time you typed a key, it would be very distracting.
2731
2732* Menu:
2733
2734* Interactive multiply-by-seven::
2735* multiply-by-seven in detail::
2736
2737
2738File: eintr, Node: Interactive multiply-by-seven, Next: multiply-by-seven in detail, Prev: Interactive, Up: Interactive
2739
2740An Interactive `multiply-by-seven', An Overview
2741-----------------------------------------------
2742
2743Both the use of the special form `interactive' and one way to display a
2744value in the echo area can be illustrated by creating an interactive
2745version of `multiply-by-seven'.
2746
2747Here is the code:
2748
2749 (defun multiply-by-seven (number) ; Interactive version.
2750 "Multiply NUMBER by seven."
2751 (interactive "p")
2752 (message "The result is %d" (* 7 number)))
2753
2754You can install this code by placing your cursor after it and typing
2755`C-x C-e'. The name of the function will appear in your echo area.
2756Then, you can use this code by typing `C-u' and a number and then
2757typing `M-x multiply-by-seven' and pressing <RET>. The phrase `The
2758result is ...' followed by the product will appear in the echo area.
2759
2760Speaking more generally, you invoke a function like this in either of
2761two ways:
2762
2763 1. By typing a prefix argument that contains the number to be passed,
2764 and then typing `M-x' and the name of the function, as with `C-u 3
2765 M-x forward-sentence'; or,
2766
2767 2. By typing whatever key or keychord the function is bound to, as
2768 with `C-u 3 M-e'.
2769
2770Both the examples just mentioned work identically to move point forward
2771three sentences. (Since `multiply-by-seven' is not bound to a key, it
2772could not be used as an example of key binding.)
2773
2774(*Note Some Keybindings: Keybindings, to learn how to bind a command to
2775a key.)
2776
2777A prefix argument is passed to an interactive function by typing the
2778<META> key followed by a number, for example, `M-3 M-e', or by typing
2779`C-u' and then a number, for example, `C-u 3 M-e' (if you type `C-u'
2780without a number, it defaults to 4).
2781
2782
2783File: eintr, Node: multiply-by-seven in detail, Prev: Interactive multiply-by-seven, Up: Interactive
2784
27853.3.1 An Interactive `multiply-by-seven'
2786----------------------------------------
2787
2788Let's look at the use of the special form `interactive' and then at the
2789function `message' in the interactive version of `multiply-by-seven'.
2790You will recall that the function definition looks like this:
2791
2792 (defun multiply-by-seven (number) ; Interactive version.
2793 "Multiply NUMBER by seven."
2794 (interactive "p")
2795 (message "The result is %d" (* 7 number)))
2796
2797In this function, the expression, `(interactive "p")', is a list of two
2798elements. The `"p"' tells Emacs to pass the prefix argument to the
2799function and use its value for the argument of the function.
2800
2801The argument will be a number. This means that the symbol `number'
2802will be bound to a number in the line:
2803
2804 (message "The result is %d" (* 7 number))
2805
2806For example, if your prefix argument is 5, the Lisp interpreter will
2807evaluate the line as if it were:
2808
2809 (message "The result is %d" (* 7 5))
2810
2811(If you are reading this in GNU Emacs, you can evaluate this expression
2812yourself.) First, the interpreter will evaluate the inner list, which
2813is `(* 7 5)'. This returns a value of 35. Next, it will evaluate the
2814outer list, passing the values of the second and subsequent elements of
2815the list to the function `message'.
2816
2817As we have seen, `message' is an Emacs Lisp function especially
2818designed for sending a one line message to a user. (*Note The
2819`message' function: message.) In summary, the `message' function
2820prints its first argument in the echo area as is, except for
2821occurrences of `%d' or `%s' (and various other %-sequences which we
2822have not mentioned). When it sees a control sequence, the function
2823looks to the second or subsequent arguments and prints the value of the
2824argument in the location in the string where the control sequence is
2825located.
2826
2827In the interactive `multiply-by-seven' function, the control string is
2828`%d', which requires a number, and the value returned by evaluating `(*
28297 5)' is the number 35. Consequently, the number 35 is printed in
2830place of the `%d' and the message is `The result is 35'.
2831
2832(Note that when you call the function `multiply-by-seven', the message
2833is printed without quotes, but when you call `message', the text is
2834printed in double quotes. This is because the value returned by
2835`message' is what appears in the echo area when you evaluate an
2836expression whose first element is `message'; but when embedded in a
2837function, `message' prints the text as a side effect without quotes.)
2838
2839
2840File: eintr, Node: Interactive Options, Next: Permanent Installation, Prev: Interactive, Up: Writing Defuns
2841
28423.4 Different Options for `interactive'
2843=======================================
2844
2845In the example, `multiply-by-seven' used `"p"' as the argument to
2846`interactive'. This argument told Emacs to interpret your typing
2847either `C-u' followed by a number or <META> followed by a number as a
2848command to pass that number to the function as its argument. Emacs has
2849more than twenty characters predefined for use with `interactive'. In
2850almost every case, one of these options will enable you to pass the
2851right information interactively to a function. (*Note Code Characters
2852for `interactive': (elisp)Interactive Codes.)
2853
2854Consider the function `zap-to-char'. Its interactive expression is
2855
2856 (interactive "p\ncZap to char: ")
2857
2858The first part of the argument to `interactive' is `p', with which you
2859are already familiar. This argument tells Emacs to interpret a
2860`prefix', as a number to be passed to the function. You can specify a
2861prefix either by typing `C-u' followed by a number or by typing <META>
2862followed by a number. The prefix is the number of specified
2863characters. Thus, if your prefix is three and the specified character
2864is `x', then you will delete all the text up to and including the third
2865next `x'. If you do not set a prefix, then you delete all the text up
2866to and including the specified character, but no more.
2867
2868The `c' tells the function the name of the character to which to delete.
2869
2870More formally, a function with two or more arguments can have
2871information passed to each argument by adding parts to the string that
2872follows `interactive'. When you do this, the information is passed to
2873each argument in the same order it is specified in the `interactive'
2874list. In the string, each part is separated from the next part by a
2875`\n', which is a newline. For example, you can follow `p' with a `\n'
2876and an `cZap to char: '. This causes Emacs to pass the value of the
2877prefix argument (if there is one) and the character.
2878
2879In this case, the function definition looks like the following, where
2880`arg' and `char' are the symbols to which `interactive' binds the
2881prefix argument and the specified character:
2882
2883 (defun NAME-OF-FUNCTION (arg char)
2884 "DOCUMENTATION..."
2885 (interactive "p\ncZap to char: ")
2886 BODY-OF-FUNCTION...)
2887
2888(The space after the colon in the prompt makes it look better when you
2889are prompted. *Note The Definition of `copy-to-buffer':
2890copy-to-buffer, for an example.)
2891
2892When a function does not take arguments, `interactive' does not require
2893any. Such a function contains the simple expression `(interactive)'.
2894The `mark-whole-buffer' function is like this.
2895
2896Alternatively, if the special letter-codes are not right for your
2897application, you can pass your own arguments to `interactive' as a list.
2898
2899*Note The Definition of `append-to-buffer': append-to-buffer, for an
2900example. *Note Using `Interactive': (elisp)Using Interactive, for a
2901more complete explanation about this technique.
2902
2903
2904File: eintr, Node: Permanent Installation, Next: let, Prev: Interactive Options, Up: Writing Defuns
2905
29063.5 Install Code Permanently
2907============================
2908
2909When you install a function definition by evaluating it, it will stay
2910installed until you quit Emacs. The next time you start a new session
2911of Emacs, the function will not be installed unless you evaluate the
2912function definition again.
2913
2914At some point, you may want to have code installed automatically
2915whenever you start a new session of Emacs. There are several ways of
2916doing this:
2917
2918 * If you have code that is just for yourself, you can put the code
2919 for the function definition in your `.emacs' initialization file.
2920 When you start Emacs, your `.emacs' file is automatically
2921 evaluated and all the function definitions within it are installed.
2922 *Note Your `.emacs' File: Emacs Initialization.
2923
2924 * Alternatively, you can put the function definitions that you want
2925 installed in one or more files of their own and use the `load'
2926 function to cause Emacs to evaluate and thereby install each of the
2927 functions in the files. *Note Loading Files: Loading Files.
2928
2929 * Thirdly, if you have code that your whole site will use, it is
2930 usual to put it in a file called `site-init.el' that is loaded when
2931 Emacs is built. This makes the code available to everyone who uses
2932 your machine. (See the `INSTALL' file that is part of the Emacs
2933 distribution.)
2934
2935Finally, if you have code that everyone who uses Emacs may want, you
2936can post it on a computer network or send a copy to the Free Software
2937Foundation. (When you do this, please license the code and its
2938documentation under a license that permits other people to run, copy,
2939study, modify, and redistribute the code and which protects you from
2940having your work taken from you.) If you send a copy of your code to
2941the Free Software Foundation, and properly protect yourself and others,
2942it may be included in the next release of Emacs. In large part, this
2943is how Emacs has grown over the past years, by donations.
2944
2945
2946File: eintr, Node: let, Next: if, Prev: Permanent Installation, Up: Writing Defuns
2947
29483.6 `let'
2949=========
2950
2951The `let' expression is a special form in Lisp that you will need to
2952use in most function definitions.
2953
2954`let' is used to attach or bind a symbol to a value in such a way that
2955the Lisp interpreter will not confuse the variable with a variable of
2956the same name that is not part of the function.
2957
2958To understand why the `let' special form is necessary, consider the
2959situation in which you own a home that you generally refer to as `the
2960house', as in the sentence, "The house needs painting." If you are
2961visiting a friend and your host refers to `the house', he is likely to
2962be referring to _his_ house, not yours, that is, to a different house.
2963
2964If your friend is referring to his house and you think he is referring
2965to your house, you may be in for some confusion. The same thing could
2966happen in Lisp if a variable that is used inside of one function has
2967the same name as a variable that is used inside of another function,
2968and the two are not intended to refer to the same value. The `let'
2969special form prevents this kind of confusion.
2970
2971* Menu:
2972
2973* Prevent confusion::
2974* Parts of let Expression::
2975* Sample let Expression::
2976* Uninitialized let Variables::
2977
2978
2979File: eintr, Node: Prevent confusion, Next: Parts of let Expression, Prev: let, Up: let
2980
2981`let' Prevents Confusion
2982------------------------
2983
2984The `let' special form prevents confusion. `let' creates a name for a
2985"local variable" that overshadows any use of the same name outside the
2986`let' expression. This is like understanding that whenever your host
2987refers to `the house', he means his house, not yours. (Symbols used in
2988argument lists work the same way. *Note The `defun' Special Form:
2989defun.)
2990
2991Local variables created by a `let' expression retain their value _only_
2992within the `let' expression itself (and within expressions called
2993within the `let' expression); the local variables have no effect
2994outside the `let' expression.
2995
2996Another way to think about `let' is that it is like a `setq' that is
2997temporary and local. The values set by `let' are automatically undone
2998when the `let' is finished. The setting only affects expressions that
2999are inside the bounds of the `let' expression. In computer science
3000jargon, we would say "the binding of a symbol is visible only in
3001functions called in the `let' form; in Emacs Lisp, scoping is dynamic,
3002not lexical."
3003
3004`let' can create more than one variable at once. Also, `let' gives
3005each variable it creates an initial value, either a value specified by
3006you, or `nil'. (In the jargon, this is called `binding the variable to
3007the value'.) After `let' has created and bound the variables, it
3008executes the code in the body of the `let', and returns the value of
3009the last expression in the body, as the value of the whole `let'
3010expression. (`Execute' is a jargon term that means to evaluate a list;
3011it comes from the use of the word meaning `to give practical effect to'
3012(`Oxford English Dictionary'). Since you evaluate an expression to
3013perform an action, `execute' has evolved as a synonym to `evaluate'.)
3014
3015
3016File: eintr, Node: Parts of let Expression, Next: Sample let Expression, Prev: Prevent confusion, Up: let
3017
30183.6.1 The Parts of a `let' Expression
3019-------------------------------------
3020
3021A `let' expression is a list of three parts. The first part is the
3022symbol `let'. The second part is a list, called a "varlist", each
3023element of which is either a symbol by itself or a two-element list,
3024the first element of which is a symbol. The third part of the `let'
3025expression is the body of the `let'. The body usually consists of one
3026or more lists.
3027
3028A template for a `let' expression looks like this:
3029
3030 (let VARLIST BODY...)
3031
3032The symbols in the varlist are the variables that are given initial
3033values by the `let' special form. Symbols by themselves are given the
3034initial value of `nil'; and each symbol that is the first element of a
3035two-element list is bound to the value that is returned when the Lisp
3036interpreter evaluates the second element.
3037
3038Thus, a varlist might look like this: `(thread (needles 3))'. In this
3039case, in a `let' expression, Emacs binds the symbol `thread' to an
3040initial value of `nil', and binds the symbol `needles' to an initial
3041value of 3.
3042
3043When you write a `let' expression, what you do is put the appropriate
3044expressions in the slots of the `let' expression template.
3045
3046If the varlist is composed of two-element lists, as is often the case,
3047the template for the `let' expression looks like this:
3048
3049 (let ((VARIABLE VALUE)
3050 (VARIABLE VALUE)
3051 ...)
3052 BODY...)
3053
3054
3055File: eintr, Node: Sample let Expression, Next: Uninitialized let Variables, Prev: Parts of let Expression, Up: let
3056
30573.6.2 Sample `let' Expression
3058-----------------------------
3059
3060The following expression creates and gives initial values to the two
3061variables `zebra' and `tiger'. The body of the `let' expression is a
3062list which calls the `message' function.
3063
3064 (let ((zebra 'stripes)
3065 (tiger 'fierce))
3066 (message "One kind of animal has %s and another is %s."
3067 zebra tiger))
3068
3069Here, the varlist is `((zebra 'stripes) (tiger 'fierce))'.
3070
3071The two variables are `zebra' and `tiger'. Each variable is the first
3072element of a two-element list and each value is the second element of
3073its two-element list. In the varlist, Emacs binds the variable `zebra'
3074to the value `stripes'(1), and binds the variable `tiger' to the value
3075`fierce'. In this example, both values are symbols preceded by a
3076quote. The values could just as well have been another list or a
3077string. The body of the `let' follows after the list holding the
3078variables. In this example, the body is a list that uses the `message'
3079function to print a string in the echo area.
3080
3081You may evaluate the example in the usual fashion, by placing the
3082cursor after the last parenthesis and typing `C-x C-e'. When you do
3083this, the following will appear in the echo area:
3084
3085 "One kind of animal has stripes and another is fierce."
3086
3087As we have seen before, the `message' function prints its first
3088argument, except for `%s'. In this example, the value of the variable
3089`zebra' is printed at the location of the first `%s' and the value of
3090the variable `tiger' is printed at the location of the second `%s'.
3091
3092---------- Footnotes ----------
3093
3094(1) According to Jared Diamond in `Guns, Germs, and Steel', "... zebras
3095become impossibly dangerous as they grow older" but the claim here is
3096that they do not become fierce like a tiger. (1997, W. W. Norton and
3097Co., ISBN 0-393-03894-2, page 171)
3098
3099
3100File: eintr, Node: Uninitialized let Variables, Prev: Sample let Expression, Up: let
3101
31023.6.3 Uninitialized Variables in a `let' Statement
3103--------------------------------------------------
3104
3105If you do not bind the variables in a `let' statement to specific
3106initial values, they will automatically be bound to an initial value of
3107`nil', as in the following expression:
3108
3109 (let ((birch 3)
3110 pine
3111 fir
3112 (oak 'some))
3113 (message
3114 "Here are %d variables with %s, %s, and %s value."
3115 birch pine fir oak))
3116
3117Here, the varlist is `((birch 3) pine fir (oak 'some))'.
3118
3119If you evaluate this expression in the usual way, the following will
3120appear in your echo area:
3121
3122 "Here are 3 variables with nil, nil, and some value."
3123
3124In this example, Emacs binds the symbol `birch' to the number 3, binds
3125the symbols `pine' and `fir' to `nil', and binds the symbol `oak' to
3126the value `some'.
3127
3128Note that in the first part of the `let', the variables `pine' and
3129`fir' stand alone as atoms that are not surrounded by parentheses; this
3130is because they are being bound to `nil', the empty list. But `oak' is
3131bound to `some' and so is a part of the list `(oak 'some)'. Similarly,
3132`birch' is bound to the number 3 and so is in a list with that number.
3133(Since a number evaluates to itself, the number does not need to be
3134quoted. Also, the number is printed in the message using a `%d' rather
3135than a `%s'.) The four variables as a group are put into a list to
3136delimit them from the body of the `let'.
3137
3138
3139File: eintr, Node: if, Next: else, Prev: let, Up: Writing Defuns
3140
31413.7 The `if' Special Form
3142=========================
3143
3144A third special form, in addition to `defun' and `let', is the
3145conditional `if'. This form is used to instruct the computer to make
3146decisions. You can write function definitions without using `if', but
3147it is used often enough, and is important enough, to be included here.
3148It is used, for example, in the code for the function
3149`beginning-of-buffer'.
3150
3151The basic idea behind an `if', is that "_if_ a test is true, _then_ an
3152expression is evaluated." If the test is not true, the expression is
3153not evaluated. For example, you might make a decision such as, "if it
3154is warm and sunny, then go to the beach!"
3155
3156* Menu:
3157
3158* if in more detail::
3159* type-of-animal in detail::
3160
3161
3162File: eintr, Node: if in more detail, Next: type-of-animal in detail, Prev: if, Up: if
3163
3164`if' in more detail
3165-------------------
3166
3167An `if' expression written in Lisp does not use the word `then'; the
3168test and the action are the second and third elements of the list whose
3169first element is `if'. Nonetheless, the test part of an `if'
3170expression is often called the "if-part" and the second argument is
3171often called the "then-part".
3172
3173Also, when an `if' expression is written, the true-or-false-test is
3174usually written on the same line as the symbol `if', but the action to
3175carry out if the test is true, the "then-part", is written on the
3176second and subsequent lines. This makes the `if' expression easier to
3177read.
3178
3179 (if TRUE-OR-FALSE-TEST
3180 ACTION-TO-CARRY-OUT-IF-TEST-IS-TRUE)
3181
3182The true-or-false-test will be an expression that is evaluated by the
3183Lisp interpreter.
3184
3185Here is an example that you can evaluate in the usual manner. The test
3186is whether the number 5 is greater than the number 4. Since it is, the
3187message `5 is greater than 4!' will be printed.
3188
3189 (if (> 5 4) ; if-part
3190 (message "5 is greater than 4!")) ; then-part
3191
3192(The function `>' tests whether its first argument is greater than its
3193second argument and returns true if it is.)
3194
3195Of course, in actual use, the test in an `if' expression will not be
3196fixed for all time as it is by the expression `(> 5 4)'. Instead, at
3197least one of the variables used in the test will be bound to a value
3198that is not known ahead of time. (If the value were known ahead of
3199time, we would not need to run the test!)
3200
3201For example, the value may be bound to an argument of a function
3202definition. In the following function definition, the character of the
3203animal is a value that is passed to the function. If the value bound to
3204`characteristic' is `fierce', then the message, `It's a tiger!' will be
3205printed; otherwise, `nil' will be returned.
3206
3207 (defun type-of-animal (characteristic)
3208 "Print message in echo area depending on CHARACTERISTIC.
3209 If the CHARACTERISTIC is the symbol `fierce',
3210 then warn of a tiger."
3211 (if (equal characteristic 'fierce)
3212 (message "It's a tiger!")))
3213
3214If you are reading this inside of GNU Emacs, you can evaluate the
3215function definition in the usual way to install it in Emacs, and then
3216you can evaluate the following two expressions to see the results:
3217
3218 (type-of-animal 'fierce)
3219
3220 (type-of-animal 'zebra)
3221
3222When you evaluate `(type-of-animal 'fierce)', you will see the
3223following message printed in the echo area: `"It's a tiger!"'; and when
3224you evaluate `(type-of-animal 'zebra)' you will see `nil' printed in
3225the echo area.
3226
3227
3228File: eintr, Node: type-of-animal in detail, Prev: if in more detail, Up: if
3229
32303.7.1 The `type-of-animal' Function in Detail
3231---------------------------------------------
3232
3233Let's look at the `type-of-animal' function in detail.
3234
3235The function definition for `type-of-animal' was written by filling the
3236slots of two templates, one for a function definition as a whole, and a
3237second for an `if' expression.
3238
3239The template for every function that is not interactive is:
3240
3241 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
3242 "DOCUMENTATION..."
3243 BODY...)
3244
3245The parts of the function that match this template look like this:
3246
3247 (defun type-of-animal (characteristic)
3248 "Print message in echo area depending on CHARACTERISTIC.
3249 If the CHARACTERISTIC is the symbol `fierce',
3250 then warn of a tiger."
3251 BODY: THE `if' EXPRESSION)
3252
3253The name of function is `type-of-animal'; it is passed the value of one
3254argument. The argument list is followed by a multi-line documentation
3255string. The documentation string is included in the example because it
3256is a good habit to write documentation string for every function
3257definition. The body of the function definition consists of the `if'
3258expression.
3259
3260The template for an `if' expression looks like this:
3261
3262 (if TRUE-OR-FALSE-TEST
3263 ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-TRUE)
3264
3265In the `type-of-animal' function, the code for the `if' looks like this:
3266
3267 (if (equal characteristic 'fierce)
3268 (message "It's a tiger!")))
3269
3270Here, the true-or-false-test is the expression:
3271
3272 (equal characteristic 'fierce)
3273
3274In Lisp, `equal' is a function that determines whether its first
3275argument is equal to its second argument. The second argument is the
3276quoted symbol `'fierce' and the first argument is the value of the
3277symbol `characteristic'--in other words, the argument passed to this
3278function.
3279
3280In the first exercise of `type-of-animal', the argument `fierce' is
3281passed to `type-of-animal'. Since `fierce' is equal to `fierce', the
3282expression, `(equal characteristic 'fierce)', returns a value of true.
3283When this happens, the `if' evaluates the second argument or then-part
3284of the `if': `(message "It's tiger!")'.
3285
3286On the other hand, in the second exercise of `type-of-animal', the
3287argument `zebra' is passed to `type-of-animal'. `zebra' is not equal
3288to `fierce', so the then-part is not evaluated and `nil' is returned by
3289the `if' expression.
3290
3291
3292File: eintr, Node: else, Next: Truth & Falsehood, Prev: if, Up: Writing Defuns
3293
32943.8 If-then-else Expressions
3295============================
3296
3297An `if' expression may have an optional third argument, called the
3298"else-part", for the case when the true-or-false-test returns false.
3299When this happens, the second argument or then-part of the overall `if'
3300expression is _not_ evaluated, but the third or else-part _is_
3301evaluated. You might think of this as the cloudy day alternative for
3302the decision "if it is warm and sunny, then go to the beach, else read
3303a book!".
3304
3305The word "else" is not written in the Lisp code; the else-part of an
3306`if' expression comes after the then-part. In the written Lisp, the
3307else-part is usually written to start on a line of its own and is
3308indented less than the then-part:
3309
3310 (if TRUE-OR-FALSE-TEST
3311 ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-TRUE
3312 ACTION-TO-CARRY-OUT-IF-THE-TEST-RETURNS-FALSE)
3313
3314For example, the following `if' expression prints the message `4 is not
3315greater than 5!' when you evaluate it in the usual way:
3316
3317 (if (> 4 5) ; if-part
3318 (message "5 is greater than 4!") ; then-part
3319 (message "4 is not greater than 5!")) ; else-part
3320
3321Note that the different levels of indentation make it easy to
3322distinguish the then-part from the else-part. (GNU Emacs has several
3323commands that automatically indent `if' expressions correctly. *Note
3324GNU Emacs Helps You Type Lists: Typing Lists.)
3325
3326We can extend the `type-of-animal' function to include an else-part by
3327simply incorporating an additional part to the `if' expression.
3328
3329You can see the consequences of doing this if you evaluate the following
3330version of the `type-of-animal' function definition to install it and
3331then evaluate the two subsequent expressions to pass different
3332arguments to the function.
3333
3334 (defun type-of-animal (characteristic) ; Second version.
3335 "Print message in echo area depending on CHARACTERISTIC.
3336 If the CHARACTERISTIC is the symbol `fierce',
3337 then warn of a tiger;
3338 else say it's not fierce."
3339 (if (equal characteristic 'fierce)
3340 (message "It's a tiger!")
3341 (message "It's not fierce!")))
3342
3343
3344 (type-of-animal 'fierce)
3345
3346 (type-of-animal 'zebra)
3347
3348When you evaluate `(type-of-animal 'fierce)', you will see the
3349following message printed in the echo area: `"It's a tiger!"'; but when
3350you evaluate `(type-of-animal 'zebra)', you will see `"It's not
3351fierce!"'.
3352
3353(Of course, if the CHARACTERISTIC were `ferocious', the message `"It's
3354not fierce!"' would be printed; and it would be misleading! When you
3355write code, you need to take into account the possibility that some
3356such argument will be tested by the `if' and write your program
3357accordingly.)
3358
3359
3360File: eintr, Node: Truth & Falsehood, Next: save-excursion, Prev: else, Up: Writing Defuns
3361
33623.9 Truth and Falsehood in Emacs Lisp
3363=====================================
3364
3365There is an important aspect to the truth test in an `if' expression.
3366So far, we have spoken of `true' and `false' as values of predicates as
3367if they were new kinds of Emacs Lisp objects. In fact, `false' is just
3368our old friend `nil'. Anything else--anything at all--is `true'.
3369
3370The expression that tests for truth is interpreted as "true" if the
3371result of evaluating it is a value that is not `nil'. In other words,
3372the result of the test is considered true if the value returned is a
3373number such as 47, a string such as `"hello"', or a symbol (other than
3374`nil') such as `flowers', or a list (so long as it is not empty), or
3375even a buffer!
3376
3377* Menu:
3378
3379* nil explained::
3380
3381
3382File: eintr, Node: nil explained, Prev: Truth & Falsehood, Up: Truth & Falsehood
3383
3384An explanation of `nil'
3385-----------------------
3386
3387Before illustrating a test for truth, we need an explanation of `nil'.
3388
3389In Emacs Lisp, the symbol `nil' has two meanings. First, it means the
3390empty list. Second, it means false and is the value returned when a
3391true-or-false-test tests false. `nil' can be written as an empty list,
3392`()', or as `nil'. As far as the Lisp interpreter is concerned, `()'
3393and `nil' are the same. Humans, however, tend to use `nil' for false
3394and `()' for the empty list.
3395
3396In Emacs Lisp, any value that is not `nil'--is not the empty list--is
3397considered true. This means that if an evaluation returns something
3398that is not an empty list, an `if' expression will test true. For
3399example, if a number is put in the slot for the test, it will be
3400evaluated and will return itself, since that is what numbers do when
3401evaluated. In this conditional, the `if' expression will test true.
3402The expression tests false only when `nil', an empty list, is returned
3403by evaluating the expression.
3404
3405You can see this by evaluating the two expressions in the following
3406examples.
3407
3408In the first example, the number 4 is evaluated as the test in the `if'
3409expression and returns itself; consequently, the then-part of the
3410expression is evaluated and returned: `true' appears in the echo area.
3411In the second example, the `nil' indicates false; consequently, the
3412else-part of the expression is evaluated and returned: `false' appears
3413in the echo area.
3414
3415 (if 4
3416 'true
3417 'false)
3418
3419 (if nil
3420 'true
3421 'false)
3422
3423Incidentally, if some other useful value is not available for a test
3424that returns true, then the Lisp interpreter will return the symbol `t'
3425for true. For example, the expression `(> 5 4)' returns `t' when
3426evaluated, as you can see by evaluating it in the usual way:
3427
3428 (> 5 4)
3429
3430On the other hand, this function returns `nil' if the test is false.
3431
3432 (> 4 5)
3433
3434
3435File: eintr, Node: save-excursion, Next: Review, Prev: Truth & Falsehood, Up: Writing Defuns
3436
34373.10 `save-excursion'
3438=====================
3439
3440The `save-excursion' function is the fourth and final special form that
3441we will discuss in this chapter.
3442
3443In Emacs Lisp programs used for editing, the `save-excursion' function
3444is very common. It saves the location of point and mark, executes the
3445body of the function, and then restores point and mark to their
3446previous positions if their locations were changed. Its primary
3447purpose is to keep the user from being surprised and disturbed by
3448unexpected movement of point or mark.
3449
3450* Menu:
3451
3452* Point and mark::
3453* Template for save-excursion::
3454
3455
3456File: eintr, Node: Point and mark, Next: Template for save-excursion, Prev: save-excursion, Up: save-excursion
3457
3458Point and Mark
3459--------------
3460
3461Before discussing `save-excursion', however, it may be useful first to
3462review what point and mark are in GNU Emacs. "Point" is the current
3463location of the cursor. Wherever the cursor is, that is point. More
3464precisely, on terminals where the cursor appears to be on top of a
3465character, point is immediately before the character. In Emacs Lisp,
3466point is an integer. The first character in a buffer is number one,
3467the second is number two, and so on. The function `point' returns the
3468current position of the cursor as a number. Each buffer has its own
3469value for point.
3470
3471The "mark" is another position in the buffer; its value can be set with
3472a command such as `C-<SPC>' (`set-mark-command'). If a mark has been
3473set, you can use the command `C-x C-x' (`exchange-point-and-mark') to
3474cause the cursor to jump to the mark and set the mark to be the
3475previous position of point. In addition, if you set another mark, the
3476position of the previous mark is saved in the mark ring. Many mark
3477positions can be saved this way. You can jump the cursor to a saved
3478mark by typing `C-u C-<SPC>' one or more times.
3479
3480The part of the buffer between point and mark is called "the region".
3481Numerous commands work on the region, including `center-region',
3482`count-lines-region', `kill-region', and `print-region'.
3483
3484The `save-excursion' special form saves the locations of point and mark
3485and restores those positions after the code within the body of the
3486special form is evaluated by the Lisp interpreter. Thus, if point were
3487in the beginning of a piece of text and some code moved point to the end
3488of the buffer, the `save-excursion' would put point back to where it
3489was before, after the expressions in the body of the function were
3490evaluated.
3491
3492In Emacs, a function frequently moves point as part of its internal
3493workings even though a user would not expect this. For example,
3494`count-lines-region' moves point. To prevent the user from being
3495bothered by jumps that are both unexpected and (from the user's point of
3496view) unnecessary, `save-excursion' is often used to keep point and
3497mark in the location expected by the user. The use of `save-excursion'
3498is good housekeeping.
3499
3500To make sure the house stays clean, `save-excursion' restores the
3501values of point and mark even if something goes wrong in the code inside
3502of it (or, to be more precise and to use the proper jargon, "in case of
3503abnormal exit"). This feature is very helpful.
3504
3505In addition to recording the values of point and mark, `save-excursion'
3506keeps track of the current buffer, and restores it, too. This means
3507you can write code that will change the buffer and have
3508`save-excursion' switch you back to the original buffer. This is how
3509`save-excursion' is used in `append-to-buffer'. (*Note The Definition
3510of `append-to-buffer': append-to-buffer.)
3511
3512
3513File: eintr, Node: Template for save-excursion, Prev: Point and mark, Up: save-excursion
3514
35153.10.1 Template for a `save-excursion' Expression
3516-------------------------------------------------
3517
3518The template for code using `save-excursion' is simple:
3519
3520 (save-excursion
3521 BODY...)
3522
3523The body of the function is one or more expressions that will be
3524evaluated in sequence by the Lisp interpreter. If there is more than
3525one expression in the body, the value of the last one will be returned
3526as the value of the `save-excursion' function. The other expressions
3527in the body are evaluated only for their side effects; and
3528`save-excursion' itself is used only for its side effect (which is
3529restoring the positions of point and mark).
3530
3531In more detail, the template for a `save-excursion' expression looks
3532like this:
3533
3534 (save-excursion
3535 FIRST-EXPRESSION-IN-BODY
3536 SECOND-EXPRESSION-IN-BODY
3537 THIRD-EXPRESSION-IN-BODY
3538 ...
3539 LAST-EXPRESSION-IN-BODY)
3540
3541An expression, of course, may be a symbol on its own or a list.
3542
3543In Emacs Lisp code, a `save-excursion' expression often occurs within
3544the body of a `let' expression. It looks like this:
3545
3546 (let VARLIST
3547 (save-excursion
3548 BODY...))
3549
3550
3551File: eintr, Node: Review, Next: defun Exercises, Prev: save-excursion, Up: Writing Defuns
3552
35533.11 Review
3554===========
3555
3556In the last few chapters we have introduced a fair number of functions
3557and special forms. Here they are described in brief, along with a few
3558similar functions that have not been mentioned yet.
3559
3560`eval-last-sexp'
3561 Evaluate the last symbolic expression before the current location
3562 of point. The value is printed in the echo area unless the
3563 function is invoked with an argument; in that case, the output is
3564 printed in the current buffer. This command is normally bound to
3565 `C-x C-e'.
3566
3567`defun'
3568 Define function. This special form has up to five parts: the name,
3569 a template for the arguments that will be passed to the function,
3570 documentation, an optional interactive declaration, and the body
3571 of the definition.
3572
3573 For example, in an early version of Emacs, the function definition
3574 was as follows. (It is slightly more complex now that it seeks
3575 the first non-whitespace character rather than the first visible
3576 character.)
3577
3578 (defun back-to-indentation ()
3579 "Move point to first visible character on line."
3580 (interactive)
3581 (beginning-of-line 1)
3582 (skip-chars-forward " \t"))
3583
3584`interactive'
3585 Declare to the interpreter that the function can be used
3586 interactively. This special form may be followed by a string with
3587 one or more parts that pass the information to the arguments of the
3588 function, in sequence. These parts may also tell the interpreter
3589 to prompt for information. Parts of the string are separated by
3590 newlines, `\n'.
3591
3592 Common code characters are:
3593
3594 `b'
3595 The name of an existing buffer.
3596
3597 `f'
3598 The name of an existing file.
3599
3600 `p'
3601 The numeric prefix argument. (Note that this `p' is lower
3602 case.)
3603
3604 `r'
3605 Point and the mark, as two numeric arguments, smallest first.
3606 This is the only code letter that specifies two successive
3607 arguments rather than one.
3608
3609 *Note Code Characters for `interactive': (elisp)Interactive Codes,
3610 for a complete list of code characters.
3611
3612`let'
3613 Declare that a list of variables is for use within the body of the
3614 `let' and give them an initial value, either `nil' or a specified
3615 value; then evaluate the rest of the expressions in the body of
3616 the `let' and return the value of the last one. Inside the body
3617 of the `let', the Lisp interpreter does not see the values of the
3618 variables of the same names that are bound outside of the `let'.
3619
3620 For example,
3621
3622 (let ((foo (buffer-name))
3623 (bar (buffer-size)))
3624 (message
3625 "This buffer is %s and has %d characters."
3626 foo bar))
3627
3628`save-excursion'
3629 Record the values of point and mark and the current buffer before
3630 evaluating the body of this special form. Restore the values of
3631 point and mark and buffer afterward.
3632
3633 For example,
3634
3635 (message "We are %d characters into this buffer."
3636 (- (point)
3637 (save-excursion
3638 (goto-char (point-min)) (point))))
3639
3640`if'
3641 Evaluate the first argument to the function; if it is true,
3642 evaluate the second argument; else evaluate the third argument, if
3643 there is one.
3644
3645 The `if' special form is called a "conditional". There are other
3646 conditionals in Emacs Lisp, but `if' is perhaps the most commonly
3647 used.
3648
3649 For example,
3650
3651 (if (string-equal
3652 (number-to-string 22)
3653 (substring (emacs-version) 10 12))
3654 (message "This is version 22 Emacs")
3655 (message "This is not version 22 Emacs"))
3656
3657`equal'
3658`eq'
3659 Test whether two objects are the same. `equal' uses one meaning
3660 of the word `same' and `eq' uses another: `equal' returns true if
3661 the two objects have a similar structure and contents, such as two
3662 copies of the same book. On the other hand, `eq', returns true if
3663 both arguments are actually the same object.
3664
3665`<'
3666`>'
3667`<='
3668`>='
3669 The `<' function tests whether its first argument is smaller than
3670 its second argument. A corresponding function, `>', tests whether
3671 the first argument is greater than the second. Likewise, `<='
3672 tests whether the first argument is less than or equal to the
3673 second and `>=' tests whether the first argument is greater than
3674 or equal to the second. In all cases, both arguments must be
3675 numbers or markers (markers indicate positions in buffers).
3676
3677`string<'
3678`string-lessp'
3679`string='
3680`string-equal'
3681 The `string-lessp' function tests whether its first argument is
3682 smaller than the second argument. A shorter, alternative name for
3683 the same function (a `defalias') is `string<'.
3684
3685 The arguments to `string-lessp' must be strings or symbols; the
3686 ordering is lexicographic, so case is significant. The print
3687 names of symbols are used instead of the symbols themselves.
3688
3689 An empty string, `""', a string with no characters in it, is
3690 smaller than any string of characters.
3691
3692 `string-equal' provides the corresponding test for equality. Its
3693 shorter, alternative name is `string='. There are no string test
3694 functions that correspond to >, `>=', or `<='.
3695
3696`message'
3697 Print a message in the echo area. The first argument is a string
3698 that can contain `%s', `%d', or `%c' to print the value of
3699 arguments that follow the string. The argument used by `%s' must
3700 be a string or a symbol; the argument used by `%d' must be a
3701 number. The argument used by `%c' must be an ASCII code number;
3702 it will be printed as the character with that ASCII code.
3703 (Various other %-sequences have not been mentioned.)
3704
3705`setq'
3706`set'
3707 The `setq' function sets the value of its first argument to the
3708 value of the second argument. The first argument is automatically
3709 quoted by `setq'. It does the same for succeeding pairs of
3710 arguments. Another function, `set', takes only two arguments and
3711 evaluates both of them before setting the value returned by its
3712 first argument to the value returned by its second argument.
3713
3714`buffer-name'
3715 Without an argument, return the name of the buffer, as a string.
3716
3717`buffer-file-name'
3718 Without an argument, return the name of the file the buffer is
3719 visiting.
3720
3721`current-buffer'
3722 Return the buffer in which Emacs is active; it may not be the
3723 buffer that is visible on the screen.
3724
3725`other-buffer'
3726 Return the most recently selected buffer (other than the buffer
3727 passed to `other-buffer' as an argument and other than the current
3728 buffer).
3729
3730`switch-to-buffer'
3731 Select a buffer for Emacs to be active in and display it in the
3732 current window so users can look at it. Usually bound to `C-x b'.
3733
3734`set-buffer'
3735 Switch Emacs' attention to a buffer on which programs will run.
3736 Don't alter what the window is showing.
3737
3738`buffer-size'
3739 Return the number of characters in the current buffer.
3740
3741`point'
3742 Return the value of the current position of the cursor, as an
3743 integer counting the number of characters from the beginning of the
3744 buffer.
3745
3746`point-min'
3747 Return the minimum permissible value of point in the current
3748 buffer. This is 1, unless narrowing is in effect.
3749
3750`point-max'
3751 Return the value of the maximum permissible value of point in the
3752 current buffer. This is the end of the buffer, unless narrowing
3753 is in effect.
3754
3755
3756File: eintr, Node: defun Exercises, Prev: Review, Up: Writing Defuns
3757
37583.12 Exercises
3759==============
3760
3761 * Write a non-interactive function that doubles the value of its
3762 argument, a number. Make that function interactive.
3763
3764 * Write a function that tests whether the current value of
3765 `fill-column' is greater than the argument passed to the function,
3766 and if so, prints an appropriate message.
3767
3768
3769File: eintr, Node: Buffer Walk Through, Next: More Complex, Prev: Writing Defuns, Up: Top
3770
37714 A Few Buffer-Related Functions
3772********************************
3773
3774In this chapter we study in detail several of the functions used in GNU
3775Emacs. This is called a "walk-through". These functions are used as
3776examples of Lisp code, but are not imaginary examples; with the
3777exception of the first, simplified function definition, these functions
3778show the actual code used in GNU Emacs. You can learn a great deal from
3779these definitions. The functions described here are all related to
3780buffers. Later, we will study other functions.
3781
3782* Menu:
3783
3784* Finding More::
3785* simplified-beginning-of-buffer::
3786* mark-whole-buffer::
3787* append-to-buffer::
3788* Buffer Related Review::
3789* Buffer Exercises::
3790
3791
3792File: eintr, Node: Finding More, Next: simplified-beginning-of-buffer, Prev: Buffer Walk Through, Up: Buffer Walk Through
3793
37944.1 Finding More Information
3795============================
3796
3797In this walk-through, I will describe each new function as we come to
3798it, sometimes in detail and sometimes briefly. If you are interested,
3799you can get the full documentation of any Emacs Lisp function at any
3800time by typing `C-h f' and then the name of the function (and then
3801<RET>). Similarly, you can get the full documentation for a variable
3802by typing `C-h v' and then the name of the variable (and then <RET>).
3803
3804When a function is written in Emacs Lisp, `describe-function' will also
3805tell you the location of the function definition.
3806
3807Put point into the name of the file that contains the function and
3808press the <RET> key. In this case, <RET> means `push-button' rather
3809than `return' or `enter'. Emacs will take you directly to the function
3810definition.
3811
3812More generally, if you want to see a function in its original source
3813file, you can use the `find-tags' function to jump to it. `find-tags'
3814works with a wide variety of languages, not just Lisp, and C, and it
3815works with non-programming text as well. For example, `find-tags' will
3816jump to the various nodes in the Texinfo source file of this document.
3817
3818The `find-tags' function depends on `tags tables' that record the
3819locations of the functions, variables, and other items to which
3820`find-tags' jumps.
3821
3822To use the `find-tags' command, type `M-.' (i.e., press the period key
3823while holding down the <META> key, or else type the <ESC> key and then
3824type the period key), and then, at the prompt, type in the name of the
3825function whose source code you want to see, such as
3826`mark-whole-buffer', and then type <RET>. Emacs will switch buffers
3827and display the source code for the function on your screen. To switch
3828back to your current buffer, type `C-x b <RET>'. (On some keyboards,
3829the <META> key is labelled <ALT>.)
3830
3831Depending on how the initial default values of your copy of Emacs are
3832set, you may also need to specify the location of your `tags table',
3833which is a file called `TAGS'. For example, if you are interested in
3834Emacs sources, the tags table you will most likely want, if it has
3835already been created for you, will be in a subdirectory of the
3836`/usr/local/share/emacs/' directory; thus you would use the `M-x
3837visit-tags-table' command and specify a pathname such as
3838`/usr/local/share/emacs/22.0.100/lisp/TAGS'. If the tags table has not
3839already been created, you will have to create it yourself. It will in
3840a file such as `/usr/local/src/emacs/src/TAGS'.
3841
3842To create a `TAGS' file in a specific directory, switch to that
3843directory in Emacs using `M-x cd' command, or list the directory with
3844`C-x d' (`dired'). Then run the compile command, with `etags *.el' as
3845the command to execute:
3846
3847 M-x compile RET etags *.el RET
3848
3849For more information, see *Note Create Your Own `TAGS' File: etags.
3850
3851After you become more familiar with Emacs Lisp, you will find that you
3852will frequently use `find-tags' to navigate your way around source code;
3853and you will create your own `TAGS' tables.
3854
3855Incidentally, the files that contain Lisp code are conventionally
3856called "libraries". The metaphor is derived from that of a specialized
3857library, such as a law library or an engineering library, rather than a
3858general library. Each library, or file, contains functions that relate
3859to a particular topic or activity, such as `abbrev.el' for handling
3860abbreviations and other typing shortcuts, and `help.el' for on-line
3861help. (Sometimes several libraries provide code for a single activity,
3862as the various `rmail...' files provide code for reading electronic
3863mail.) In `The GNU Emacs Manual', you will see sentences such as "The
3864`C-h p' command lets you search the standard Emacs Lisp libraries by
3865topic keywords."
3866
3867
3868File: eintr, Node: simplified-beginning-of-buffer, Next: mark-whole-buffer, Prev: Finding More, Up: Buffer Walk Through
3869
38704.2 A Simplified `beginning-of-buffer' Definition
3871=================================================
3872
3873The `beginning-of-buffer' command is a good function to start with
3874since you are likely to be familiar with it and it is easy to
3875understand. Used as an interactive command, `beginning-of-buffer'
3876moves the cursor to the beginning of the buffer, leaving the mark at the
3877previous position. It is generally bound to `M-<'.
3878
3879In this section, we will discuss a shortened version of the function
3880that shows how it is most frequently used. This shortened function
3881works as written, but it does not contain the code for a complex option.
3882In another section, we will describe the entire function. (*Note
3883Complete Definition of `beginning-of-buffer': beginning-of-buffer.)
3884
3885Before looking at the code, let's consider what the function definition
3886has to contain: it must include an expression that makes the function
3887interactive so it can be called by typing `M-x beginning-of-buffer' or
3888by typing a keychord such as `M-<'; it must include code to leave a
3889mark at the original position in the buffer; and it must include code
3890to move the cursor to the beginning of the buffer.
3891
3892Here is the complete text of the shortened version of the function:
3893
3894 (defun simplified-beginning-of-buffer ()
3895 "Move point to the beginning of the buffer;
3896 leave mark at previous position."
3897 (interactive)
3898 (push-mark)
3899 (goto-char (point-min)))
3900
3901Like all function definitions, this definition has five parts following
3902the special form `defun':
3903
3904 1. The name: in this example, `simplified-beginning-of-buffer'.
3905
3906 2. A list of the arguments: in this example, an empty list, `()',
3907
3908 3. The documentation string.
3909
3910 4. The interactive expression.
3911
3912 5. The body.
3913
3914In this function definition, the argument list is empty; this means that
3915this function does not require any arguments. (When we look at the
3916definition for the complete function, we will see that it may be passed
3917an optional argument.)
3918
3919The interactive expression tells Emacs that the function is intended to
3920be used interactively. In this example, `interactive' does not have an
3921argument because `simplified-beginning-of-buffer' does not require one.
3922
3923The body of the function consists of the two lines:
3924
3925 (push-mark)
3926 (goto-char (point-min))
3927
3928The first of these lines is the expression, `(push-mark)'. When this
3929expression is evaluated by the Lisp interpreter, it sets a mark at the
3930current position of the cursor, wherever that may be. The position of
3931this mark is saved in the mark ring.
3932
3933The next line is `(goto-char (point-min))'. This expression jumps the
3934cursor to the minimum point in the buffer, that is, to the beginning of
3935the buffer (or to the beginning of the accessible portion of the buffer
3936if it is narrowed. *Note Narrowing and Widening: Narrowing & Widening.)
3937
3938The `push-mark' command sets a mark at the place where the cursor was
3939located before it was moved to the beginning of the buffer by the
3940`(goto-char (point-min))' expression. Consequently, you can, if you
3941wish, go back to where you were originally by typing `C-x C-x'.
3942
3943That is all there is to the function definition!
3944
3945When you are reading code such as this and come upon an unfamiliar
3946function, such as `goto-char', you can find out what it does by using
3947the `describe-function' command. To use this command, type `C-h f' and
3948then type in the name of the function and press <RET>. The
3949`describe-function' command will print the function's documentation
3950string in a `*Help*' window. For example, the documentation for
3951`goto-char' is:
3952
3953 Set point to POSITION, a number or marker.
3954 Beginning of buffer is position (point-min), end is (point-max).
3955
3956The function's one argument is the desired position.
3957
3958(The prompt for `describe-function' will offer you the symbol under or
3959preceding the cursor, so you can save typing by positioning the cursor
3960right over or after the function and then typing `C-h f <RET>'.)
3961
3962The `end-of-buffer' function definition is written in the same way as
3963the `beginning-of-buffer' definition except that the body of the
3964function contains the expression `(goto-char (point-max))' in place of
3965`(goto-char (point-min))'.
3966
3967
3968File: eintr, Node: mark-whole-buffer, Next: append-to-buffer, Prev: simplified-beginning-of-buffer, Up: Buffer Walk Through
3969
39704.3 The Definition of `mark-whole-buffer'
3971=========================================
3972
3973The `mark-whole-buffer' function is no harder to understand than the
3974`simplified-beginning-of-buffer' function. In this case, however, we
3975will look at the complete function, not a shortened version.
3976
3977The `mark-whole-buffer' function is not as commonly used as the
3978`beginning-of-buffer' function, but is useful nonetheless: it marks a
3979whole buffer as a region by putting point at the beginning and a mark
3980at the end of the buffer. It is generally bound to `C-x h'.
3981
3982* Menu:
3983
3984* mark-whole-buffer overview::
3985* Body of mark-whole-buffer::
3986
3987
3988File: eintr, Node: mark-whole-buffer overview, Next: Body of mark-whole-buffer, Prev: mark-whole-buffer, Up: mark-whole-buffer
3989
3990An overview of `mark-whole-buffer'
3991----------------------------------
3992
3993In GNU Emacs 22, the code for the complete function looks like this:
3994
3995 (defun mark-whole-buffer ()
3996 "Put point at beginning and mark at end of buffer.
3997 You probably should not use this function in Lisp programs;
3998 it is usually a mistake for a Lisp function to use any subroutine
3999 that uses or sets the mark."
4000 (interactive)
4001 (push-mark (point))
4002 (push-mark (point-max) nil t)
4003 (goto-char (point-min)))
4004
4005Like all other functions, the `mark-whole-buffer' function fits into
4006the template for a function definition. The template looks like this:
4007
4008 (defun NAME-OF-FUNCTION (ARGUMENT-LIST)
4009 "DOCUMENTATION..."
4010 (INTERACTIVE-EXPRESSION...)
4011 BODY...)
4012
4013Here is how the function works: the name of the function is
4014`mark-whole-buffer'; it is followed by an empty argument list, `()',
4015which means that the function does not require arguments. The
4016documentation comes next.
4017
4018The next line is an `(interactive)' expression that tells Emacs that
4019the function will be used interactively. These details are similar to
4020the `simplified-beginning-of-buffer' function described in the previous
4021section.
4022
4023
4024File: eintr, Node: Body of mark-whole-buffer, Prev: mark-whole-buffer overview, Up: mark-whole-buffer
4025
40264.3.1 Body of `mark-whole-buffer'
4027---------------------------------
4028
4029The body of the `mark-whole-buffer' function consists of three lines of
4030code:
4031
4032 (push-mark (point))
4033 (push-mark (point-max) nil t)
4034 (goto-char (point-min))
4035
4036The first of these lines is the expression, `(push-mark (point))'.
4037
4038This line does exactly the same job as the first line of the body of
4039the `simplified-beginning-of-buffer' function, which is written
4040`(push-mark)'. In both cases, the Lisp interpreter sets a mark at the
4041current position of the cursor.
4042
4043I don't know why the expression in `mark-whole-buffer' is written
4044`(push-mark (point))' and the expression in `beginning-of-buffer' is
4045written `(push-mark)'. Perhaps whoever wrote the code did not know
4046that the arguments for `push-mark' are optional and that if `push-mark'
4047is not passed an argument, the function automatically sets mark at the
4048location of point by default. Or perhaps the expression was written so
4049as to parallel the structure of the next line. In any case, the line
4050causes Emacs to determine the position of point and set a mark there.
4051
4052In earlier versions of GNU Emacs, the next line of `mark-whole-buffer'
4053was `(push-mark (point-max))'. This expression sets a mark at the
4054point in the buffer that has the highest number. This will be the end
4055of the buffer (or, if the buffer is narrowed, the end of the accessible
4056portion of the buffer. *Note Narrowing and Widening: Narrowing &
4057Widening, for more about narrowing.) After this mark has been set, the
4058previous mark, the one set at point, is no longer set, but Emacs
4059remembers its position, just as all other recent marks are always
4060remembered. This means that you can, if you wish, go back to that
4061position by typing `C-u C-<SPC>' twice.
4062
4063In GNU Emacs 22, the `(point-max)' is slightly more complicated. The
4064line reads
4065
4066 (push-mark (point-max) nil t)
4067
4068The expression works nearly the same as before. It sets a mark at the
4069highest numbered place in the buffer that it can. However, in this
4070version, `push-mark' has two additional arguments. The second argument
4071to `push-mark' is `nil'. This tells the function it _should_ display a
4072message that says `Mark set' when it pushes the mark. The third
4073argument is `t'. This tells `push-mark' to activate the mark when
4074Transient Mark mode is turned on. Transient Mark mode highlights the
4075currently active region. It is often turned off.
4076
4077Finally, the last line of the function is `(goto-char (point-min)))'.
4078This is written exactly the same way as it is written in
4079`beginning-of-buffer'. The expression moves the cursor to the minimum
4080point in the buffer, that is, to the beginning of the buffer (or to the
4081beginning of the accessible portion of the buffer). As a result of
4082this, point is placed at the beginning of the buffer and mark is set at
4083the end of the buffer. The whole buffer is, therefore, the region.
4084
4085
4086File: eintr, Node: append-to-buffer, Next: Buffer Related Review, Prev: mark-whole-buffer, Up: Buffer Walk Through
4087
40884.4 The Definition of `append-to-buffer'
4089========================================
4090
4091The `append-to-buffer' command is more complex than the
4092`mark-whole-buffer' command. What it does is copy the region (that is,
4093the part of the buffer between point and mark) from the current buffer
4094to a specified buffer.
4095
4096* Menu:
4097
4098* append-to-buffer overview::
4099* append interactive::
4100* append-to-buffer body::
4101* append save-excursion::
4102
4103
4104File: eintr, Node: append-to-buffer overview, Next: append interactive, Prev: append-to-buffer, Up: append-to-buffer
4105
4106An Overview of `append-to-buffer'
4107---------------------------------
4108
4109The `append-to-buffer' command uses the `insert-buffer-substring'
4110function to copy the region. `insert-buffer-substring' is described by
4111its name: it takes a string of characters from part of a buffer, a
4112"substring", and inserts them into another buffer.
4113
4114Most of `append-to-buffer' is concerned with setting up the conditions
4115for `insert-buffer-substring' to work: the code must specify both the
4116buffer to which the text will go, the window it comes from and goes to,
4117and the region that will be copied.
4118
4119Here is the complete text of the function:
4120
4121 (defun append-to-buffer (buffer start end)
4122 "Append to specified buffer the text of the region.
4123 It is inserted into that buffer before its point.
4124
4125 When calling from a program, give three arguments:
4126 BUFFER (or buffer name), START and END.
4127 START and END specify the portion of the current buffer to be copied."
4128 (interactive
4129 (list (read-buffer "Append to buffer: " (other-buffer
4130 (current-buffer) t))
4131 (region-beginning) (region-end)))
4132 (let ((oldbuf (current-buffer)))
4133 (save-excursion
4134 (let* ((append-to (get-buffer-create buffer))
4135 (windows (get-buffer-window-list append-to t t))
4136 point)
4137 (set-buffer append-to)
4138 (setq point (point))
4139 (barf-if-buffer-read-only)
4140 (insert-buffer-substring oldbuf start end)
4141 (dolist (window windows)
4142 (when (= (window-point window) point)
4143 (set-window-point window (point))))))))
4144
4145The function can be understood by looking at it as a series of
4146filled-in templates.
4147
4148The outermost template is for the function definition. In this
4149function, it looks like this (with several slots filled in):
4150
4151 (defun append-to-buffer (buffer start end)
4152 "DOCUMENTATION..."
4153 (interactive ...)
4154 BODY...)
4155
4156The first line of the function includes its name and three arguments.
4157The arguments are the `buffer' to which the text will be copied, and
4158the `start' and `end' of the region in the current buffer that will be
4159copied.
4160
4161The next part of the function is the documentation, which is clear and
4162complete. As is conventional, the three arguments are written in upper
4163case so you will notice them easily. Even better, they are described
4164in the same order as in the argument list.
4165
4166Note that the documentation distinguishes between a buffer and its
4167name. (The function can handle either.)
4168
4169
4170File: eintr, Node: append interactive, Next: append-to-buffer body, Prev: append-to-buffer overview, Up: append-to-buffer
4171
41724.4.1 The `append-to-buffer' Interactive Expression
4173---------------------------------------------------
4174
4175Since the `append-to-buffer' function will be used interactively, the
4176function must have an `interactive' expression. (For a review of
4177`interactive', see *Note Making a Function Interactive: Interactive.)
4178The expression reads as follows:
4179
4180 (interactive
4181 (list (read-buffer
4182 "Append to buffer: "
4183 (other-buffer (current-buffer) t))
4184 (region-beginning)
4185 (region-end)))
4186
4187This expression is not one with letters standing for parts, as
4188described earlier. Instead, it starts a list with thee parts.
4189
4190The first part of the list is an expression to read the name of a
4191buffer and return it as a string. That is `read-buffer'. The function
4192requires a prompt as its first argument, `"Append to buffer: "'. Its
4193second argument tells the command what value to provide if you don't
4194specify anything.
4195
4196In this case that second argument is an expression containing the
4197function `other-buffer', an exception, and a `t', standing for true.
4198
4199The first argument to `other-buffer', the exception, is yet another
4200function, `current-buffer'. That is not going to be returned. The
4201second argument is the symbol for true, `t'. that tells `other-buffer'
4202that it may show visible buffers (except in this case, it will not show
4203the current buffer, which makes sense).
4204
4205The expression looks like this:
4206
4207 (other-buffer (current-buffer) t)
4208
4209The second and third arguments to the `list' expression are
4210`(region-beginning)' and `(region-end)'. These two functions specify
4211the beginning and end of the text to be appended.
4212
4213Originally, the command used the letters `B' and `r'. The whole
4214`interactive' expression looked like this:
4215
4216 (interactive "BAppend to buffer: \nr")
4217
4218But when that was done, the default value of the buffer switched to was
4219invisible. That was not wanted.
4220
4221(The prompt was separated from the second argument with a newline,
4222`\n'. It was followed by an `r' that told Emacs to bind the two
4223arguments that follow the symbol `buffer' in the function's argument
4224list (that is, `start' and `end') to the values of point and mark.
4225That argument worked fine.)
4226
4227
4228File: eintr, Node: append-to-buffer body, Next: append save-excursion, Prev: append interactive, Up: append-to-buffer
4229
42304.4.2 The Body of `append-to-buffer'
4231------------------------------------
4232
4233The body of the `append-to-buffer' function begins with `let'.
4234
4235As we have seen before (*note `let': let.), the purpose of a `let'
4236expression is to create and give initial values to one or more
4237variables that will only be used within the body of the `let'. This
4238means that such a variable will not be confused with any variable of
4239the same name outside the `let' expression.
4240
4241We can see how the `let' expression fits into the function as a whole
4242by showing a template for `append-to-buffer' with the `let' expression
4243in outline:
4244
4245 (defun append-to-buffer (buffer start end)
4246 "DOCUMENTATION..."
4247 (interactive ...)
4248 (let ((VARIABLE VALUE))
4249 BODY...)
4250
4251The `let' expression has three elements:
4252
4253 1. The symbol `let';
4254
4255 2. A varlist containing, in this case, a single two-element list,
4256 `(VARIABLE VALUE)';
4257
4258 3. The body of the `let' expression.
4259
4260In the `append-to-buffer' function, the varlist looks like this:
4261
4262 (oldbuf (current-buffer))
4263
4264In this part of the `let' expression, the one variable, `oldbuf', is
4265bound to the value returned by the `(current-buffer)' expression. The
4266variable, `oldbuf', is used to keep track of the buffer in which you
4267are working and from which you will copy.
4268
4269The element or elements of a varlist are surrounded by a set of
4270parentheses so the Lisp interpreter can distinguish the varlist from
4271the body of the `let'. As a consequence, the two-element list within
4272the varlist is surrounded by a circumscribing set of parentheses. The
4273line looks like this:
4274
4275 (let ((oldbuf (current-buffer)))
4276 ... )
4277
4278The two parentheses before `oldbuf' might surprise you if you did not
4279realize that the first parenthesis before `oldbuf' marks the boundary
4280of the varlist and the second parenthesis marks the beginning of the
4281two-element list, `(oldbuf (current-buffer))'.
4282
4283
4284File: eintr, Node: append save-excursion, Prev: append-to-buffer body, Up: append-to-buffer
4285
42864.4.3 `save-excursion' in `append-to-buffer'
4287--------------------------------------------
4288
4289The body of the `let' expression in `append-to-buffer' consists of a
4290`save-excursion' expression.
4291
4292The `save-excursion' function saves the locations of point and mark,
4293and restores them to those positions after the expressions in the body
4294of the `save-excursion' complete execution. In addition,
4295`save-excursion' keeps track of the original buffer, and restores it.
4296This is how `save-excursion' is used in `append-to-buffer'.
4297
4298Incidentally, it is worth noting here that a Lisp function is normally
4299formatted so that everything that is enclosed in a multi-line spread is
4300indented more to the right than the first symbol. In this function
4301definition, the `let' is indented more than the `defun', and the
4302`save-excursion' is indented more than the `let', like this:
4303
4304 (defun ...
4305 ...
4306 ...
4307 (let...
4308 (save-excursion
4309 ...
4310
4311This formatting convention makes it easy to see that the lines in the
4312body of the `save-excursion' are enclosed by the parentheses associated
4313with `save-excursion', just as the `save-excursion' itself is enclosed
4314by the parentheses associated with the `let':
4315
4316 (let ((oldbuf (current-buffer)))
4317 (save-excursion
4318 ...
4319 (set-buffer ...)
4320 (insert-buffer-substring oldbuf start end)
4321 ...))
4322
4323The use of the `save-excursion' function can be viewed as a process of
4324filling in the slots of a template:
4325
4326 (save-excursion
4327 FIRST-EXPRESSION-IN-BODY
4328 SECOND-EXPRESSION-IN-BODY
4329 ...
4330 LAST-EXPRESSION-IN-BODY)
4331
4332In this function, the body of the `save-excursion' contains only one
4333expression, the `let*' expression. You know about a `let' function.
4334The `let*' function is different. It has a `*' in its name. It
4335enables Emacs to set each variable in its varlist in sequence, one
4336after another.
4337
4338Its critical feature is that variables later in the varlist can make
4339use of the values to which Emacs set variables earlier in the varlist.
4340*Note The `let*' expression: fwd-para let.
4341
4342We will skip functions like `let*' and focus on two: the `set-buffer'
4343function and the `insert-buffer-substring' function.
4344
4345In the old days, the `set-buffer' expression was simply
4346
4347 (set-buffer (get-buffer-create buffer))
4348
4349but now it is
4350
4351 (set-buffer append-to)
4352
4353`append-to' is bound to `(get-buffer-create buffer)' earlier on in the
4354`let*' expression. That extra binding would not be necessary except
4355for that `append-to' is used later in the varlist as an argument to
4356`get-buffer-window-list'.
4357
4358The `append-to-buffer' function definition inserts text from the buffer
4359in which you are currently to a named buffer. It happens that
4360`insert-buffer-substring' copies text from another buffer to the
4361current buffer, just the reverse--that is why the `append-to-buffer'
4362definition starts out with a `let' that binds the local symbol `oldbuf'
4363to the value returned by `current-buffer'.
4364
4365The `insert-buffer-substring' expression looks like this:
4366
4367 (insert-buffer-substring oldbuf start end)
4368
4369The `insert-buffer-substring' function copies a string _from_ the
4370buffer specified as its first argument and inserts the string into the
4371present buffer. In this case, the argument to
4372`insert-buffer-substring' is the value of the variable created and
4373bound by the `let', namely the value of `oldbuf', which was the current
4374buffer when you gave the `append-to-buffer' command.
4375
4376After `insert-buffer-substring' has done its work, `save-excursion'
4377will restore the action to the original buffer and `append-to-buffer'
4378will have done its job.
4379
4380Written in skeletal form, the workings of the body look like this:
4381
4382 (let (BIND-`oldbuf'-TO-VALUE-OF-`current-buffer')
4383 (save-excursion ; Keep track of buffer.
4384 CHANGE-BUFFER
4385 INSERT-SUBSTRING-FROM-`oldbuf'-INTO-BUFFER)
4386
4387 CHANGE-BACK-TO-ORIGINAL-BUFFER-WHEN-FINISHED
4388 LET-THE-LOCAL-MEANING-OF-`oldbuf'-DISAPPEAR-WHEN-FINISHED
4389
4390In summary, `append-to-buffer' works as follows: it saves the value of
4391the current buffer in the variable called `oldbuf'. It gets the new
4392buffer (creating one if need be) and switches Emacs' attention to it.
4393Using the value of `oldbuf', it inserts the region of text from the old
4394buffer into the new buffer; and then using `save-excursion', it brings
4395you back to your original buffer.
4396
4397In looking at `append-to-buffer', you have explored a fairly complex
4398function. It shows how to use `let' and `save-excursion', and how to
4399change to and come back from another buffer. Many function definitions
4400use `let', `save-excursion', and `set-buffer' this way.
4401
4402
4403File: eintr, Node: Buffer Related Review, Next: Buffer Exercises, Prev: append-to-buffer, Up: Buffer Walk Through
4404
44054.5 Review
4406==========
4407
4408Here is a brief summary of the various functions discussed in this
4409chapter.
4410
4411`describe-function'
4412`describe-variable'
4413 Print the documentation for a function or variable.
4414 Conventionally bound to `C-h f' and `C-h v'.
4415
4416`find-tag'
4417 Find the file containing the source for a function or variable and
4418 switch buffers to it, positioning point at the beginning of the
4419 item. Conventionally bound to `M-.' (that's a period following the
4420 <META> key).
4421
4422`save-excursion'
4423 Save the location of point and mark and restore their values after
4424 the arguments to `save-excursion' have been evaluated. Also,
4425 remember the current buffer and return to it.
4426
4427`push-mark'
4428 Set mark at a location and record the value of the previous mark
4429 on the mark ring. The mark is a location in the buffer that will
4430 keep its relative position even if text is added to or removed
4431 from the buffer.
4432
4433`goto-char'
4434 Set point to the location specified by the value of the argument,
4435 which can be a number, a marker, or an expression that returns
4436 the number of a position, such as `(point-min)'.
4437
4438`insert-buffer-substring'
4439 Copy a region of text from a buffer that is passed to the function
4440 as an argument and insert the region into the current buffer.
4441
4442`mark-whole-buffer'
4443 Mark the whole buffer as a region. Normally bound to `C-x h'.
4444
4445`set-buffer'
4446 Switch the attention of Emacs to another buffer, but do not change
4447 the window being displayed. Used when the program rather than a
4448 human is to work on a different buffer.
4449
4450`get-buffer-create'
4451`get-buffer'
4452 Find a named buffer or create one if a buffer of that name does not
4453 exist. The `get-buffer' function returns `nil' if the named
4454 buffer does not exist.
4455
4456
4457File: eintr, Node: Buffer Exercises, Prev: Buffer Related Review, Up: Buffer Walk Through
4458
44594.6 Exercises
4460=============
4461
4462 * Write your own `simplified-end-of-buffer' function definition;
4463 then test it to see whether it works.
4464
4465 * Use `if' and `get-buffer' to write a function that prints a
4466 message telling you whether a buffer exists.
4467
4468 * Using `find-tag', find the source for the `copy-to-buffer'
4469 function.
4470
4471
4472File: eintr, Node: More Complex, Next: Narrowing & Widening, Prev: Buffer Walk Through, Up: Top
4473
44745 A Few More Complex Functions
4475******************************
4476
4477In this chapter, we build on what we have learned in previous chapters
4478by looking at more complex functions. The `copy-to-buffer' function
4479illustrates use of two `save-excursion' expressions in one definition,
4480while the `insert-buffer' function illustrates use of an asterisk in an
4481`interactive' expression, use of `or', and the important distinction
4482between a name and the object to which the name refers.
4483
4484* Menu:
4485
4486* copy-to-buffer::
4487* insert-buffer::
4488* beginning-of-buffer::
4489* Second Buffer Related Review::
4490* optional Exercise::
4491
4492
4493File: eintr, Node: copy-to-buffer, Next: insert-buffer, Prev: More Complex, Up: More Complex
4494
44955.1 The Definition of `copy-to-buffer'
4496======================================
4497
4498After understanding how `append-to-buffer' works, it is easy to
4499understand `copy-to-buffer'. This function copies text into a buffer,
4500but instead of adding to the second buffer, it replaces all the
4501previous text in the second buffer.
4502
4503The body of `copy-to-buffer' looks like this,
4504
4505 ...
4506 (interactive "BCopy to buffer: \nr")
4507 (let ((oldbuf (current-buffer)))
4508 (with-current-buffer (get-buffer-create buffer)
4509 (barf-if-buffer-read-only)
4510 (erase-buffer)
4511 (save-excursion
4512 (insert-buffer-substring oldbuf start end)))))
4513
4514The `copy-to-buffer' function has a simpler `interactive' expression
4515than `append-to-buffer'.
4516
4517The definition then says
4518
4519 (with-current-buffer (get-buffer-create buffer) ...
4520
4521First, look at the earliest inner expression; that is evaluated first.
4522That expression starts with `get-buffer-create buffer'. The function
4523tells the computer to use the buffer with the name specified as the one
4524to which you are copying, or if such a buffer does not exist, to create
4525it. Then, the `with-current-buffer' function evaluates its body with
4526that buffer temporarily current.
4527
4528(This demonstrates another way to shift the computer's attention but
4529not the user's. The `append-to-buffer' function showed how to do the
4530same with `save-excursion' and `set-buffer'. `with-current-buffer' is
4531a newer, and arguably easier, mechanism.)
4532
4533The `barf-if-buffer-read-only' function sends you an error message
4534saying the buffer is read-only if you cannot modify it.
4535
4536The next line has the `erase-buffer' function as its sole contents.
4537That function erases the buffer.
4538
4539Finally, the last two lines contain the `save-excursion' expression
4540with `insert-buffer-substring' as its body. The
4541`insert-buffer-substring' expression copies the text from the buffer
4542you are in (and you have not seen the computer shift its attention, so
4543you don't know that that buffer is now called `oldbuf').
4544
4545Incidentally, this is what is meant by `replacement'. To replace text,
4546Emacs erases the previous text and then inserts new text.
4547
4548In outline, the body of `copy-to-buffer' looks like this:
4549
4550 (let (BIND-`oldbuf'-TO-VALUE-OF-`current-buffer')
4551 (WITH-THE-BUFFER-YOU-ARE-COPYING-TO
4552 (BUT-DO-NOT-ERASE-OR-COPY-TO-A-READ-ONLY-BUFFER)
4553 (erase-buffer)
4554 (save-excursion
4555 INSERT-SUBSTRING-FROM-`oldbuf'-INTO-BUFFER)))
4556
4557
4558File: eintr, Node: insert-buffer, Next: beginning-of-buffer, Prev: copy-to-buffer, Up: More Complex
4559
45605.2 The Definition of `insert-buffer'
4561=====================================
4562
4563`insert-buffer' is yet another buffer-related function. This command
4564copies another buffer _into_ the current buffer. It is the reverse of
4565`append-to-buffer' or `copy-to-buffer', since they copy a region of
4566text _from_ the current buffer to another buffer.
4567
4568Here is a discussion based on the original code. The code was
4569simplified in 2003 and is harder to understand.
4570
4571*Note New Body for `insert-buffer': New insert-buffer, to see a
4572discussion of the new body.)
4573
4574In addition, this code illustrates the use of `interactive' with a
4575buffer that might be "read-only" and the important distinction between
4576the name of an object and the object actually referred to.
4577
4578* Menu:
4579
4580* insert-buffer code::
4581* insert-buffer interactive::
4582* insert-buffer body::
4583* if & or::
4584* Insert or::
4585* Insert let::
4586* New insert-buffer ::
4587
4588
4589File: eintr, Node: insert-buffer code, Next: insert-buffer interactive, Prev: insert-buffer, Up: insert-buffer
4590
4591The Code for `insert-buffer'
4592----------------------------
4593
4594Here is the earlier code:
4595
4596 (defun insert-buffer (buffer)
4597 "Insert after point the contents of BUFFER.
4598 Puts mark after the inserted text.
4599 BUFFER may be a buffer or a buffer name."
4600 (interactive "*bInsert buffer: ")
4601 (or (bufferp buffer)
4602 (setq buffer (get-buffer buffer)))
4603 (let (start end newmark)
4604 (save-excursion
4605 (save-excursion
4606 (set-buffer buffer)
4607 (setq start (point-min) end (point-max)))
4608 (insert-buffer-substring buffer start end)
4609 (setq newmark (point)))
4610 (push-mark newmark)))
4611
4612As with other function definitions, you can use a template to see an
4613outline of the function:
4614
4615 (defun insert-buffer (buffer)
4616 "DOCUMENTATION..."
4617 (interactive "*bInsert buffer: ")
4618 BODY...)
4619
4620
4621File: eintr, Node: insert-buffer interactive, Next: insert-buffer body, Prev: insert-buffer code, Up: insert-buffer
4622
46235.2.1 The Interactive Expression in `insert-buffer'
4624---------------------------------------------------
4625
4626In `insert-buffer', the argument to the `interactive' declaration has
4627two parts, an asterisk, `*', and `bInsert buffer: '.
4628
4629* Menu:
4630
4631* Read-only buffer::
4632* b for interactive::
4633
4634
4635File: eintr, Node: Read-only buffer, Next: b for interactive, Prev: insert-buffer interactive, Up: insert-buffer interactive
4636
4637A Read-only Buffer
4638..................
4639
4640The asterisk is for the situation when the current buffer is a
4641read-only buffer--a buffer that cannot be modified. If `insert-buffer'
4642is called when the current buffer is read-only, a message to this
4643effect is printed in the echo area and the terminal may beep or blink
4644at you; you will not be permitted to insert anything into current
4645buffer. The asterisk does not need to be followed by a newline to
4646separate it from the next argument.
4647
4648
4649File: eintr, Node: b for interactive, Prev: Read-only buffer, Up: insert-buffer interactive
4650
4651`b' in an Interactive Expression
4652................................
4653
4654The next argument in the interactive expression starts with a lower
4655case `b'. (This is different from the code for `append-to-buffer',
4656which uses an upper-case `B'. *Note The Definition of
4657`append-to-buffer': append-to-buffer.) The lower-case `b' tells the
4658Lisp interpreter that the argument for `insert-buffer' should be an
4659existing buffer or else its name. (The upper-case `B' option provides
4660for the possibility that the buffer does not exist.) Emacs will prompt
4661you for the name of the buffer, offering you a default buffer, with
4662name completion enabled. If the buffer does not exist, you receive a
4663message that says "No match"; your terminal may beep at you as well.
4664
4665The new and simplified code generates a list for `interactive'. It
4666uses the `barf-if-buffer-read-only' and `read-buffer' functions with
4667which we are already familiar and the `progn' special form with which
4668we are not. (It will be described later.)
4669
4670
4671File: eintr, Node: insert-buffer body, Next: if & or, Prev: insert-buffer interactive, Up: insert-buffer
4672
46735.2.2 The Body of the `insert-buffer' Function
4674----------------------------------------------
4675
4676The body of the `insert-buffer' function has two major parts: an `or'
4677expression and a `let' expression. The purpose of the `or' expression
4678is to ensure that the argument `buffer' is bound to a buffer and not
4679just the name of a buffer. The body of the `let' expression contains
4680the code which copies the other buffer into the current buffer.
4681
4682In outline, the two expressions fit into the `insert-buffer' function
4683like this:
4684
4685 (defun insert-buffer (buffer)
4686 "DOCUMENTATION..."
4687 (interactive "*bInsert buffer: ")
4688 (or ...
4689 ...
4690 (let (VARLIST)
4691 BODY-OF-`let'... )
4692
4693To understand how the `or' expression ensures that the argument
4694`buffer' is bound to a buffer and not to the name of a buffer, it is
4695first necessary to understand the `or' function.
4696
4697Before doing this, let me rewrite this part of the function using `if'
4698so that you can see what is done in a manner that will be familiar.
4699
4700
4701File: eintr, Node: if & or, Next: Insert or, Prev: insert-buffer body, Up: insert-buffer
4702
47035.2.3 `insert-buffer' With an `if' Instead of an `or'
4704-----------------------------------------------------
4705
4706The job to be done is to make sure the value of `buffer' is a buffer
4707itself and not the name of a buffer. If the value is the name, then
4708the buffer itself must be got.
4709
4710You can imagine yourself at a conference where an usher is wandering
4711around holding a list with your name on it and looking for you: the
4712usher is "bound" to your name, not to you; but when the usher finds you
4713and takes your arm, the usher becomes "bound" to you.
4714
4715In Lisp, you might describe this situation like this:
4716
4717 (if (not (holding-on-to-guest))
4718 (find-and-take-arm-of-guest))
4719
4720We want to do the same thing with a buffer--if we do not have the
4721buffer itself, we want to get it.
4722
4723Using a predicate called `bufferp' that tells us whether we have a
4724buffer (rather than its name), we can write the code like this:
4725
4726 (if (not (bufferp buffer)) ; if-part
4727 (setq buffer (get-buffer buffer))) ; then-part
4728
4729Here, the true-or-false-test of the `if' expression is
4730`(not (bufferp buffer))'; and the then-part is the expression
4731`(setq buffer (get-buffer buffer))'.
4732
4733In the test, the function `bufferp' returns true if its argument is a
4734buffer--but false if its argument is the name of the buffer. (The last
4735character of the function name `bufferp' is the character `p'; as we
4736saw earlier, such use of `p' is a convention that indicates that the
4737function is a predicate, which is a term that means that the function
4738will determine whether some property is true or false. *Note Using the
4739Wrong Type Object as an Argument: Wrong Type of Argument.)
4740
4741The function `not' precedes the expression `(bufferp buffer)', so the
4742true-or-false-test looks like this:
4743
4744 (not (bufferp buffer))
4745
4746`not' is a function that returns true if its argument is false and
4747false if its argument is true. So if `(bufferp buffer)' returns true,
4748the `not' expression returns false and vice-verse: what is "not true"
4749is false and what is "not false" is true.
4750
4751Using this test, the `if' expression works as follows: when the value
4752of the variable `buffer' is actually a buffer rather than its name, the
4753true-or-false-test returns false and the `if' expression does not
4754evaluate the then-part. This is fine, since we do not need to do
4755anything to the variable `buffer' if it really is a buffer.
4756
4757On the other hand, when the value of `buffer' is not a buffer itself,
4758but the name of a buffer, the true-or-false-test returns true and the
4759then-part of the expression is evaluated. In this case, the then-part
4760is `(setq buffer (get-buffer buffer))'. This expression uses the
4761`get-buffer' function to return an actual buffer itself, given its
4762name. The `setq' then sets the variable `buffer' to the value of the
4763buffer itself, replacing its previous value (which was the name of the
4764buffer).
4765
4766
4767File: eintr, Node: Insert or, Next: Insert let, Prev: if & or, Up: insert-buffer
4768
47695.2.4 The `or' in the Body
4770--------------------------
4771
4772The purpose of the `or' expression in the `insert-buffer' function is
4773to ensure that the argument `buffer' is bound to a buffer and not just
4774to the name of a buffer. The previous section shows how the job could
4775have been done using an `if' expression. However, the `insert-buffer'
4776function actually uses `or'. To understand this, it is necessary to
4777understand how `or' works.
4778
4779An `or' function can have any number of arguments. It evaluates each
4780argument in turn and returns the value of the first of its arguments
4781that is not `nil'. Also, and this is a crucial feature of `or', it
4782does not evaluate any subsequent arguments after returning the first
4783non-`nil' value.
4784
4785The `or' expression looks like this:
4786
4787 (or (bufferp buffer)
4788 (setq buffer (get-buffer buffer)))
4789
4790The first argument to `or' is the expression `(bufferp buffer)'. This
4791expression returns true (a non-`nil' value) if the buffer is actually a
4792buffer, and not just the name of a buffer. In the `or' expression, if
4793this is the case, the `or' expression returns this true value and does
4794not evaluate the next expression--and this is fine with us, since we do
4795not want to do anything to the value of `buffer' if it really is a
4796buffer.
4797
4798On the other hand, if the value of `(bufferp buffer)' is `nil', which
4799it will be if the value of `buffer' is the name of a buffer, the Lisp
4800interpreter evaluates the next element of the `or' expression. This is
4801the expression `(setq buffer (get-buffer buffer))'. This expression
4802returns a non-`nil' value, which is the value to which it sets the
4803variable `buffer'--and this value is a buffer itself, not the name of a
4804buffer.
4805
4806The result of all this is that the symbol `buffer' is always bound to a
4807buffer itself rather than to the name of a buffer. All this is
4808necessary because the `set-buffer' function in a following line only
4809works with a buffer itself, not with the name to a buffer.
4810
4811Incidentally, using `or', the situation with the usher would be written
4812like this:
4813
4814 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
4815
4816
4817File: eintr, Node: Insert let, Next: New insert-buffer, Prev: Insert or, Up: insert-buffer
4818
48195.2.5 The `let' Expression in `insert-buffer'
4820---------------------------------------------
4821
4822After ensuring that the variable `buffer' refers to a buffer itself and
4823not just to the name of a buffer, the `insert-buffer function'
4824continues with a `let' expression. This specifies three local
4825variables, `start', `end', and `newmark' and binds them to the initial
4826value `nil'. These variables are used inside the remainder of the
4827`let' and temporarily hide any other occurrence of variables of the
4828same name in Emacs until the end of the `let'.
4829
4830The body of the `let' contains two `save-excursion' expressions.
4831First, we will look at the inner `save-excursion' expression in detail.
4832The expression looks like this:
4833
4834 (save-excursion
4835 (set-buffer buffer)
4836 (setq start (point-min) end (point-max)))
4837
4838The expression `(set-buffer buffer)' changes Emacs' attention from the
4839current buffer to the one from which the text will copied. In that
4840buffer, the variables `start' and `end' are set to the beginning and
4841end of the buffer, using the commands `point-min' and `point-max'.
4842Note that we have here an illustration of how `setq' is able to set two
4843variables in the same expression. The first argument of `setq' is set
4844to the value of its second, and its third argument is set to the value
4845of its fourth.
4846
4847After the body of the inner `save-excursion' is evaluated, the
4848`save-excursion' restores the original buffer, but `start' and `end'
4849remain set to the values of the beginning and end of the buffer from
4850which the text will be copied.
4851
4852The outer `save-excursion' expression looks like this:
4853
4854 (save-excursion
4855 (INNER-`save-excursion'-EXPRESSION
4856 (GO-TO-NEW-BUFFER-AND-SET-`start'-AND-`end')
4857 (insert-buffer-substring buffer start end)
4858 (setq newmark (point)))
4859
4860The `insert-buffer-substring' function copies the text _into_ the
4861current buffer _from_ the region indicated by `start' and `end' in
4862`buffer'. Since the whole of the second buffer lies between `start'
4863and `end', the whole of the second buffer is copied into the buffer you
4864are editing. Next, the value of point, which will be at the end of the
4865inserted text, is recorded in the variable `newmark'.
4866
4867After the body of the outer `save-excursion' is evaluated, point and
4868mark are relocated to their original places.
4869
4870However, it is convenient to locate a mark at the end of the newly
4871inserted text and locate point at its beginning. The `newmark'
4872variable records the end of the inserted text. In the last line of the
4873`let' expression, the `(push-mark newmark)' expression function sets a
4874mark to this location. (The previous location of the mark is still
4875accessible; it is recorded on the mark ring and you can go back to it
4876with `C-u C-<SPC>'.) Meanwhile, point is located at the beginning of
4877the inserted text, which is where it was before you called the insert
4878function, the position of which was saved by the first `save-excursion'.
4879
4880The whole `let' expression looks like this:
4881
4882 (let (start end newmark)
4883 (save-excursion
4884 (save-excursion
4885 (set-buffer buffer)
4886 (setq start (point-min) end (point-max)))
4887 (insert-buffer-substring buffer start end)
4888 (setq newmark (point)))
4889 (push-mark newmark))
4890
4891Like the `append-to-buffer' function, the `insert-buffer' function uses
4892`let', `save-excursion', and `set-buffer'. In addition, the function
4893illustrates one way to use `or'. All these functions are building
4894blocks that we will find and use again and again.
4895
4896
4897File: eintr, Node: New insert-buffer, Prev: Insert let, Up: insert-buffer
4898
48995.2.6 New Body for `insert-buffer'
4900----------------------------------
4901
4902The body in the GNU Emacs 22 version is more confusing than the
4903original.
4904
4905It consists of two expressions,
4906
4907 (push-mark
4908 (save-excursion
4909 (insert-buffer-substring (get-buffer buffer))
4910 (point)))
4911
4912 nil
4913
4914except, and this is what confuses novices, very important work is done
4915inside the `push-mark' expression.
4916
4917The `get-buffer' function returns a buffer with the name provided. You
4918will note that the function is _not_ called `get-buffer-create'; it
4919does not create a buffer if one does not already exist. The buffer
4920returned by `get-buffer', an existing buffer, is passed to
4921`insert-buffer-substring', which inserts the whole of the buffer (since
4922you did not specify anything else).
4923
4924The location into which the buffer is inserted is recorded by
4925`push-mark'. Then the function returns `nil', the value of its last
4926command. Put another way, the `insert-buffer' function exists only to
4927produce a side effect, inserting another buffer, not to return any
4928value.
4929
4930
4931File: eintr, Node: beginning-of-buffer, Next: Second Buffer Related Review, Prev: insert-buffer, Up: More Complex
4932
49335.3 Complete Definition of `beginning-of-buffer'
4934================================================
4935
4936The basic structure of the `beginning-of-buffer' function has already
4937been discussed. (*Note A Simplified `beginning-of-buffer' Definition:
4938simplified-beginning-of-buffer.) This section describes the complex
4939part of the definition.
4940
4941As previously described, when invoked without an argument,
4942`beginning-of-buffer' moves the cursor to the beginning of the buffer
4943(in truth, the accessible portion of the buffer), leaving the mark at
4944the previous position. However, when the command is invoked with a
4945number between one and ten, the function considers that number to be a
4946fraction of the length of the buffer, measured in tenths, and Emacs
4947moves the cursor that fraction of the way from the beginning of the
4948buffer. Thus, you can either call this function with the key command
4949`M-<', which will move the cursor to the beginning of the buffer, or
4950with a key command such as `C-u 7 M-<' which will move the cursor to a
4951point 70% of the way through the buffer. If a number bigger than ten
4952is used for the argument, it moves to the end of the buffer.
4953
4954The `beginning-of-buffer' function can be called with or without an
4955argument. The use of the argument is optional.
4956
4957* Menu:
4958
4959* Optional Arguments::
4960* beginning-of-buffer opt arg::
4961* beginning-of-buffer complete::
4962
4963
4964File: eintr, Node: Optional Arguments, Next: beginning-of-buffer opt arg, Prev: beginning-of-buffer, Up: beginning-of-buffer
4965
49665.3.1 Optional Arguments
4967------------------------
4968
4969Unless told otherwise, Lisp expects that a function with an argument in
4970its function definition will be called with a value for that argument.
4971If that does not happen, you get an error and a message that says
4972`Wrong number of arguments'.
4973
4974However, optional arguments are a feature of Lisp: a particular
4975"keyword" is used to tell the Lisp interpreter that an argument is
4976optional. The keyword is `&optional'. (The `&' in front of `optional'
4977is part of the keyword.) In a function definition, if an argument
4978follows the keyword `&optional', no value need be passed to that
4979argument when the function is called.
4980
4981The first line of the function definition of `beginning-of-buffer'
4982therefore looks like this:
4983
4984 (defun beginning-of-buffer (&optional arg)
4985
4986In outline, the whole function looks like this:
4987
4988 (defun beginning-of-buffer (&optional arg)
4989 "DOCUMENTATION..."
4990 (interactive "P")
4991 (or (IS-THE-ARGUMENT-A-CONS-CELL arg)
4992 (and ARE-BOTH-TRANSIENT-MARK-MODE-AND-MARK-ACTIVE-TRUE)
4993 (push-mark))
4994 (let (DETERMINE-SIZE-AND-SET-IT)
4995 (goto-char
4996 (IF-THERE-IS-AN-ARGUMENT
4997 FIGURE-OUT-WHERE-TO-GO
4998 ELSE-GO-TO
4999 (point-min))))
5000 DO-NICETY
5001
5002The function is similar to the `simplified-beginning-of-buffer'
5003function except that the `interactive' expression has `"P"' as an
5004argument and the `goto-char' function is followed by an if-then-else
5005expression that figures out where to put the cursor if there is an
5006argument that is not a cons cell.
5007
5008(Since I do not explain a cons cell for many more chapters, please
5009consider ignoring the function `consp'. *Note How Lists are
5010Implemented: List Implementation, and *Note Cons Cell and List Types:
5011(elisp)Cons Cell Type.)
5012
5013The `"P"' in the `interactive' expression tells Emacs to pass a prefix
5014argument, if there is one, to the function in raw form. A prefix
5015argument is made by typing the <META> key followed by a number, or by
5016typing `C-u' and then a number. (If you don't type a number, `C-u'
5017defaults to a cons cell with a 4. A lowercase `"p"' in the
5018`interactive' expression causes the function to convert a prefix arg to
5019a number.)
5020
5021The true-or-false-test of the `if' expression looks complex, but it is
5022not: it checks whether `arg' has a value that is not `nil' and whether
5023it is a cons cell. (That is what `consp' does; it checks whether its
5024argument is a cons cell.) If `arg' has a value that is not `nil' (and
5025is not a cons cell), which will be the case if `beginning-of-buffer' is
5026called with a numeric argument, then this true-or-false-test will
5027return true and the then-part of the `if' expression will be evaluated.
5028On the other hand, if `beginning-of-buffer' is not called with an
5029argument, the value of `arg' will be `nil' and the else-part of the
5030`if' expression will be evaluated. The else-part is simply
5031`point-min', and when this is the outcome, the whole `goto-char'
5032expression is `(goto-char (point-min))', which is how we saw the
5033`beginning-of-buffer' function in its simplified form.
5034
5035
5036File: eintr, Node: beginning-of-buffer opt arg, Next: beginning-of-buffer complete, Prev: Optional Arguments, Up: beginning-of-buffer
5037
50385.3.2 `beginning-of-buffer' with an Argument
5039--------------------------------------------
5040
5041When `beginning-of-buffer' is called with an argument, an expression is
5042evaluated which calculates what value to pass to `goto-char'. This
5043expression is rather complicated at first sight. It includes an inner
5044`if' expression and much arithmetic. It looks like this:
5045
5046 (if (> (buffer-size) 10000)
5047 ;; Avoid overflow for large buffer sizes!
5048 (* (prefix-numeric-value arg)
5049 (/ size 10))
5050 (/
5051 (+ 10
5052 (*
5053 size (prefix-numeric-value arg))) 10)))
5054
5055* Menu:
5056
5057* Disentangle beginning-of-buffer::
5058* Large buffer case::
5059* Small buffer case::
5060
5061
5062File: eintr, Node: Disentangle beginning-of-buffer, Next: Large buffer case, Prev: beginning-of-buffer opt arg, Up: beginning-of-buffer opt arg
5063
5064Disentangle `beginning-of-buffer'
5065.................................
5066
5067Like other complex-looking expressions, the conditional expression
5068within `beginning-of-buffer' can be disentangled by looking at it as
5069parts of a template, in this case, the template for an if-then-else
5070expression. In skeletal form, the expression looks like this:
5071
5072 (if (BUFFER-IS-LARGE
5073 DIVIDE-BUFFER-SIZE-BY-10-AND-MULTIPLY-BY-ARG
5074 ELSE-USE-ALTERNATE-CALCULATION
5075
5076The true-or-false-test of this inner `if' expression checks the size of
5077the buffer. The reason for this is that the old Version 18 Emacs used
5078numbers that are no bigger than eight million or so and in the
5079computation that followed, the programmer feared that Emacs might try
5080to use over-large numbers if the buffer were large. The term
5081`overflow', mentioned in the comment, means numbers that are over
5082large. Version 21 Emacs uses larger numbers, but this code has not
5083been touched, if only because people now look at buffers that are far,
5084far larger than ever before.
5085
5086There are two cases: if the buffer is large and if it is not.
5087
5088
5089File: eintr, Node: Large buffer case, Next: Small buffer case, Prev: Disentangle beginning-of-buffer, Up: beginning-of-buffer opt arg
5090
5091What happens in a large buffer
5092..............................
5093
5094In `beginning-of-buffer', the inner `if' expression tests whether the
5095size of the buffer is greater than 10,000 characters. To do this, it
5096uses the `>' function and the computation of `size' that comes from the
5097let expression.
5098
5099In the old days, the function `buffer-size' was used. Not only was
5100that function called several times, it gave the size of the whole
5101buffer, not the accessible part. The computation makes much more sense
5102when it handles just the accessible part. (*Note Narrowing and
5103Widening: Narrowing & Widening, for more information on focusing
5104attention to an `accessible' part.)
5105
5106The line looks like this:
5107
5108 (if (> size 10000)
5109
5110When the buffer is large, the then-part of the `if' expression is
5111evaluated. It reads like this (after formatting for easy reading):
5112
5113 (*
5114 (prefix-numeric-value arg)
5115 (/ size 10))
5116
5117This expression is a multiplication, with two arguments to the function
5118`*'.
5119
5120The first argument is `(prefix-numeric-value arg)'. When `"P"' is used
5121as the argument for `interactive', the value passed to the function as
5122its argument is passed a "raw prefix argument", and not a number. (It
5123is a number in a list.) To perform the arithmetic, a conversion is
5124necessary, and `prefix-numeric-value' does the job.
5125
5126The second argument is `(/ size 10)'. This expression divides the
5127numeric value by ten -- the numeric value of the size of the accessible
5128portion of the buffer. This produces a number that tells how many
5129characters make up one tenth of the buffer size. (In Lisp, `/' is used
5130for division, just as `*' is used for multiplication.)
5131
5132In the multiplication expression as a whole, this amount is multiplied
5133by the value of the prefix argument--the multiplication looks like this:
5134
5135 (* NUMERIC-VALUE-OF-PREFIX-ARG
5136 NUMBER-OF-CHARACTERS-IN-ONE-TENTH-OF-THE-ACCESSIBLE-BUFFER)
5137
5138If, for example, the prefix argument is `7', the one-tenth value will
5139be multiplied by 7 to give a position 70% of the way through.
5140
5141The result of all this is that if the accessible portion of the buffer
5142is large, the `goto-char' expression reads like this:
5143
5144 (goto-char (* (prefix-numeric-value arg)
5145 (/ size 10)))
5146
5147This puts the cursor where we want it.
5148
5149
5150File: eintr, Node: Small buffer case, Prev: Large buffer case, Up: beginning-of-buffer opt arg
5151
5152What happens in a small buffer
5153..............................
5154
5155If the buffer contains fewer than 10,000 characters, a slightly
5156different computation is performed. You might think this is not
5157necessary, since the first computation could do the job. However, in a
5158small buffer, the first method may not put the cursor on exactly the
5159desired line; the second method does a better job.
5160
5161The code looks like this:
5162
5163 (/ (+ 10 (* size (prefix-numeric-value arg))) 10))
5164
5165This is code in which you figure out what happens by discovering how the
5166functions are embedded in parentheses. It is easier to read if you
5167reformat it with each expression indented more deeply than its
5168enclosing expression:
5169
5170 (/
5171 (+ 10
5172 (*
5173 size
5174 (prefix-numeric-value arg)))
5175 10))
5176
5177Looking at parentheses, we see that the innermost operation is
5178`(prefix-numeric-value arg)', which converts the raw argument to a
5179number. In the following expression, this number is multiplied by the
5180size of the accessible portion of the buffer:
5181
5182 (* size (prefix-numeric-value arg))
5183
5184This multiplication creates a number that may be larger than the size of
5185the buffer--seven times larger if the argument is 7, for example. Ten
5186is then added to this number and finally the large number is divided by
5187ten to provide a value that is one character larger than the percentage
5188position in the buffer.
5189
5190The number that results from all this is passed to `goto-char' and the
5191cursor is moved to that point.
5192
5193
5194File: eintr, Node: beginning-of-buffer complete, Prev: beginning-of-buffer opt arg, Up: beginning-of-buffer
5195
51965.3.3 The Complete `beginning-of-buffer'
5197----------------------------------------
5198
5199Here is the complete text of the `beginning-of-buffer' function:
5200
5201 (defun beginning-of-buffer (&optional arg)
5202 "Move point to the beginning of the buffer;
5203 leave mark at previous position.
5204 With \\[universal-argument] prefix,
5205 do not set mark at previous position.
5206 With numeric arg N,
5207 put point N/10 of the way from the beginning.
5208
5209 If the buffer is narrowed,
5210 this command uses the beginning and size
5211 of the accessible part of the buffer.
5212
5213 Don't use this command in Lisp programs!
5214 \(goto-char (point-min)) is faster
5215 and avoids clobbering the mark."
5216 (interactive "P")
5217 (or (consp arg)
5218 (and transient-mark-mode mark-active)
5219 (push-mark))
5220 (let ((size (- (point-max) (point-min))))
5221 (goto-char (if (and arg (not (consp arg)))
5222 (+ (point-min)
5223 (if (> size 10000)
5224 ;; Avoid overflow for large buffer sizes!
5225 (* (prefix-numeric-value arg)
5226 (/ size 10))
5227 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
5228 (point-min))))
5229 (if arg (forward-line 1)))
5230
5231Except for two small points, the previous discussion shows how this
5232function works. The first point deals with a detail in the
5233documentation string, and the second point concerns the last line of
5234the function.
5235
5236In the documentation string, there is reference to an expression:
5237
5238 \\[universal-argument]
5239
5240A `\\' is used before the first square bracket of this expression.
5241This `\\' tells the Lisp interpreter to substitute whatever key is
5242currently bound to the `[...]'. In the case of `universal-argument',
5243that is usually `C-u', but it might be different. (*Note Tips for
5244Documentation Strings: (elisp)Documentation Tips, for more information.)
5245
5246Finally, the last line of the `beginning-of-buffer' command says to
5247move point to the beginning of the next line if the command is invoked
5248with an argument:
5249
5250 (if arg (forward-line 1)))
5251
5252This puts the cursor at the beginning of the first line after the
5253appropriate tenths position in the buffer. This is a flourish that
5254means that the cursor is always located _at least_ the requested tenths
5255of the way through the buffer, which is a nicety that is, perhaps, not
5256necessary, but which, if it did not occur, would be sure to draw
5257complaints.
5258
5259On the other hand, it also means that if you specify the command with a
5260`C-u', but without a number, that is to say, if the `raw prefix
5261argument' is simply a cons cell, then the command puts you at the
5262beginning of the second line ... I don't know whether this is intended
5263or whether no one has dealt with the code to avoid this happening.
5264
5265
5266File: eintr, Node: Second Buffer Related Review, Next: optional Exercise, Prev: beginning-of-buffer, Up: More Complex
5267
52685.4 Review
5269==========
5270
5271Here is a brief summary of some of the topics covered in this chapter.
5272
5273`or'
5274 Evaluate each argument in sequence, and return the value of the
5275 first argument that is not `nil'; if none return a value that is
5276 not `nil', return `nil'. In brief, return the first true value of
5277 the arguments; return a true value if one _or_ any of the others
5278 are true.
5279
5280`and'
5281 Evaluate each argument in sequence, and if any are `nil', return
5282 `nil'; if none are `nil', return the value of the last argument.
5283 In brief, return a true value only if all the arguments are true;
5284 return a true value if one _and_ each of the others is true.
5285
5286`&optional'
5287 A keyword used to indicate that an argument to a function
5288 definition is optional; this means that the function can be
5289 evaluated without the argument, if desired.
5290
5291`prefix-numeric-value'
5292 Convert the `raw prefix argument' produced by `(interactive "P")'
5293 to a numeric value.
5294
5295`forward-line'
5296 Move point forward to the beginning of the next line, or if the
5297 argument is greater than one, forward that many lines. If it
5298 can't move as far forward as it is supposed to, `forward-line'
5299 goes forward as far as it can and then returns a count of the
5300 number of additional lines it was supposed to move but couldn't.
5301
5302`erase-buffer'
5303 Delete the entire contents of the current buffer.
5304
5305`bufferp'
5306 Return `t' if its argument is a buffer; otherwise return `nil'.
5307
5308
5309File: eintr, Node: optional Exercise, Prev: Second Buffer Related Review, Up: More Complex
5310
53115.5 `optional' Argument Exercise
5312================================
5313
5314Write an interactive function with an optional argument that tests
5315whether its argument, a number, is greater than or equal to, or else,
5316less than the value of `fill-column', and tells you which, in a
5317message. However, if you do not pass an argument to the function, use
531856 as a default value.
5319
5320
5321File: eintr, Node: Narrowing & Widening, Next: car cdr & cons, Prev: More Complex, Up: Top
5322
53236 Narrowing and Widening
5324************************
5325
5326Narrowing is a feature of Emacs that makes it possible for you to focus
5327on a specific part of a buffer, and work without accidentally changing
5328other parts. Narrowing is normally disabled since it can confuse
5329novices.
5330
5331* Menu:
5332
5333* Narrowing advantages::
5334* save-restriction::
5335* what-line::
5336* narrow Exercise::
5337
5338
5339File: eintr, Node: Narrowing advantages, Next: save-restriction, Prev: Narrowing & Widening, Up: Narrowing & Widening
5340
5341The Advantages of Narrowing
5342===========================
5343
5344With narrowing, the rest of a buffer is made invisible, as if it weren't
5345there. This is an advantage if, for example, you want to replace a word
5346in one part of a buffer but not in another: you narrow to the part you
5347want and the replacement is carried out only in that section, not in
5348the rest of the buffer. Searches will only work within a narrowed
5349region, not outside of one, so if you are fixing a part of a document,
5350you can keep yourself from accidentally finding parts you do not need
5351to fix by narrowing just to the region you want. (The key binding for
5352`narrow-to-region' is `C-x n n'.)
5353
5354However, narrowing does make the rest of the buffer invisible, which
5355can scare people who inadvertently invoke narrowing and think they have
5356deleted a part of their file. Moreover, the `undo' command (which is
5357usually bound to `C-x u') does not turn off narrowing (nor should it),
5358so people can become quite desperate if they do not know that they can
5359return the rest of a buffer to visibility with the `widen' command.
5360(The key binding for `widen' is `C-x n w'.)
5361
5362Narrowing is just as useful to the Lisp interpreter as to a human.
5363Often, an Emacs Lisp function is designed to work on just part of a
5364buffer; or conversely, an Emacs Lisp function needs to work on all of a
5365buffer that has been narrowed. The `what-line' function, for example,
5366removes the narrowing from a buffer, if it has any narrowing and when
5367it has finished its job, restores the narrowing to what it was. On the
5368other hand, the `count-lines' function, which is called by `what-line',
5369uses narrowing to restrict itself to just that portion of the buffer in
5370which it is interested and then restores the previous situation.
5371
5372
5373File: eintr, Node: save-restriction, Next: what-line, Prev: Narrowing advantages, Up: Narrowing & Widening
5374
53756.1 The `save-restriction' Special Form
5376=======================================
5377
5378In Emacs Lisp, you can use the `save-restriction' special form to keep
5379track of whatever narrowing is in effect, if any. When the Lisp
5380interpreter meets with `save-restriction', it executes the code in the
5381body of the `save-restriction' expression, and then undoes any changes
5382to narrowing that the code caused. If, for example, the buffer is
5383narrowed and the code that follows `save-restriction' gets rid of the
5384narrowing, `save-restriction' returns the buffer to its narrowed region
5385afterwards. In the `what-line' command, any narrowing the buffer may
5386have is undone by the `widen' command that immediately follows the
5387`save-restriction' command. Any original narrowing is restored just
5388before the completion of the function.
5389
5390The template for a `save-restriction' expression is simple:
5391
5392 (save-restriction
5393 BODY... )
5394
5395The body of the `save-restriction' is one or more expressions that will
5396be evaluated in sequence by the Lisp interpreter.
5397
5398Finally, a point to note: when you use both `save-excursion' and
5399`save-restriction', one right after the other, you should use
5400`save-excursion' outermost. If you write them in reverse order, you
5401may fail to record narrowing in the buffer to which Emacs switches
5402after calling `save-excursion'. Thus, when written together,
5403`save-excursion' and `save-restriction' should be written like this:
5404
5405 (save-excursion
5406 (save-restriction
5407 BODY...))
5408
5409In other circumstances, when not written together, the `save-excursion'
5410and `save-restriction' special forms must be written in the order
5411appropriate to the function.
5412
5413For example,
5414
5415 (save-restriction
5416 (widen)
5417 (save-excursion
5418 BODY...))
5419
5420
5421File: eintr, Node: what-line, Next: narrow Exercise, Prev: save-restriction, Up: Narrowing & Widening
5422
54236.2 `what-line'
5424===============
5425
5426The `what-line' command tells you the number of the line in which the
5427cursor is located. The function illustrates the use of the
5428`save-restriction' and `save-excursion' commands. Here is the original
5429text of the function:
5430
5431 (defun what-line ()
5432 "Print the current line number (in the buffer) of point."
5433 (interactive)
5434 (save-restriction
5435 (widen)
5436 (save-excursion
5437 (beginning-of-line)
5438 (message "Line %d"
5439 (1+ (count-lines 1 (point)))))))
5440
5441(In recent versions of GNU Emacs, the `what-line' function has been
5442expanded to tell you your line number in a narrowed buffer as well as
5443your line number in a widened buffer. The recent version is more
5444complex than the version shown here. If you feel adventurous, you
5445might want to look at it after figuring out how this version works.
5446You will probably need to use `C-h f' (`describe-function'). The newer
5447version uses a conditional to determine whether the buffer has been
5448narrowed.
5449
5450(Also, it uses `line-number-at-pos', which among other simple
5451expressions, such as `(goto-char (point-min))', moves point to the
5452beginning of the current line with `(forward-line 0)' rather than
5453`beginning-of-line'.)
5454
5455The `what-line' function as shown here has a documentation line and is
5456interactive, as you would expect. The next two lines use the functions
5457`save-restriction' and `widen'.
5458
5459The `save-restriction' special form notes whatever narrowing is in
5460effect, if any, in the current buffer and restores that narrowing after
5461the code in the body of the `save-restriction' has been evaluated.
5462
5463The `save-restriction' special form is followed by `widen'. This
5464function undoes any narrowing the current buffer may have had when
5465`what-line' was called. (The narrowing that was there is the narrowing
5466that `save-restriction' remembers.) This widening makes it possible
5467for the line counting commands to count from the beginning of the
5468buffer. Otherwise, they would have been limited to counting within the
5469accessible region. Any original narrowing is restored just before the
5470completion of the function by the `save-restriction' special form.
5471
5472The call to `widen' is followed by `save-excursion', which saves the
5473location of the cursor (i.e., of point) and of the mark, and restores
5474them after the code in the body of the `save-excursion' uses the
5475`beginning-of-line' function to move point.
5476
5477(Note that the `(widen)' expression comes between the
5478`save-restriction' and `save-excursion' special forms. When you write
5479the two `save- ...' expressions in sequence, write `save-excursion'
5480outermost.)
5481
5482The last two lines of the `what-line' function are functions to count
5483the number of lines in the buffer and then print the number in the echo
5484area.
5485
5486 (message "Line %d"
5487 (1+ (count-lines 1 (point)))))))
5488
5489The `message' function prints a one-line message at the bottom of the
5490Emacs screen. The first argument is inside of quotation marks and is
5491printed as a string of characters. However, it may contain a `%d'
5492expression to print a following argument. `%d' prints the argument as
5493a decimal, so the message will say something such as `Line 243'.
5494
5495The number that is printed in place of the `%d' is computed by the last
5496line of the function:
5497
5498 (1+ (count-lines 1 (point)))
5499
5500What this does is count the lines from the first position of the
5501buffer, indicated by the `1', up to `(point)', and then add one to that
5502number. (The `1+' function adds one to its argument.) We add one to
5503it because line 2 has only one line before it, and `count-lines' counts
5504only the lines _before_ the current line.
5505
5506After `count-lines' has done its job, and the message has been printed
5507in the echo area, the `save-excursion' restores point and mark to their
5508original positions; and `save-restriction' restores the original
5509narrowing, if any.
5510
5511
5512File: eintr, Node: narrow Exercise, Prev: what-line, Up: Narrowing & Widening
5513
55146.3 Exercise with Narrowing
5515===========================
5516
5517Write a function that will display the first 60 characters of the
5518current buffer, even if you have narrowed the buffer to its latter half
5519so that the first line is inaccessible. Restore point, mark, and
5520narrowing. For this exercise, you need to use a whole potpourri of
5521functions, including `save-restriction', `widen', `goto-char',
5522`point-min', `message', and `buffer-substring'.
5523
5524(`buffer-substring' is a previously unmentioned function you will have
5525to investigate yourself; or perhaps you will have to use
5526`buffer-substring-no-properties' or `filter-buffer-substring' ..., yet
5527other functions. Text properties are a feature otherwise not discussed
5528here. *Note Text Properties: (elisp)Text Properties.
5529
5530Additionally, do you really need `goto-char' or `point-min'? Or can
5531you write the function without them?)
5532
5533
5534File: eintr, Node: car cdr & cons, Next: Cutting & Storing Text, Prev: Narrowing & Widening, Up: Top
5535
55367 `car', `cdr', `cons': Fundamental Functions
5537*********************************************
5538
5539In Lisp, `car', `cdr', and `cons' are fundamental functions. The
5540`cons' function is used to construct lists, and the `car' and `cdr'
5541functions are used to take them apart.
5542
5543In the walk through of the `copy-region-as-kill' function, we will see
5544`cons' as well as two variants on `cdr', namely, `setcdr' and `nthcdr'.
5545(*Note copy-region-as-kill::.)
5546
5547* Menu:
5548
5549* Strange Names::
5550* car & cdr::
5551* cons::
5552* nthcdr::
5553* nth::
5554* setcar::
5555* setcdr::
5556* cons Exercise::
5557
5558
5559File: eintr, Node: Strange Names, Next: car & cdr, Prev: car cdr & cons, Up: car cdr & cons
5560
5561Strange Names
5562=============
5563
5564The name of the `cons' function is not unreasonable: it is an
5565abbreviation of the word `construct'. The origins of the names for
5566`car' and `cdr', on the other hand, are esoteric: `car' is an acronym
5567from the phrase `Contents of the Address part of the Register'; and
5568`cdr' (pronounced `could-er') is an acronym from the phrase `Contents
5569of the Decrement part of the Register'. These phrases refer to
5570specific pieces of hardware on the very early computer on which the
5571original Lisp was developed. Besides being obsolete, the phrases have
5572been completely irrelevant for more than 25 years to anyone thinking
5573about Lisp. Nonetheless, although a few brave scholars have begun to
5574use more reasonable names for these functions, the old terms are still
5575in use. In particular, since the terms are used in the Emacs Lisp
5576source code, we will use them in this introduction.
5577
5578
5579File: eintr, Node: car & cdr, Next: cons, Prev: Strange Names, Up: car cdr & cons
5580
55817.1 `car' and `cdr'
5582===================
5583
5584The CAR of a list is, quite simply, the first item in the list. Thus
5585the CAR of the list `(rose violet daisy buttercup)' is `rose'.
5586
5587If you are reading this in Info in GNU Emacs, you can see this by
5588evaluating the following:
5589
5590 (car '(rose violet daisy buttercup))
5591
5592After evaluating the expression, `rose' will appear in the echo area.
5593
5594Clearly, a more reasonable name for the `car' function would be `first'
5595and this is often suggested.
5596
5597`car' does not remove the first item from the list; it only reports
5598what it is. After `car' has been applied to a list, the list is still
5599the same as it was. In the jargon, `car' is `non-destructive'. This
5600feature turns out to be important.
5601
5602The CDR of a list is the rest of the list, that is, the `cdr' function
5603returns the part of the list that follows the first item. Thus, while
5604the CAR of the list `'(rose violet daisy buttercup)' is `rose', the
5605rest of the list, the value returned by the `cdr' function, is `(violet
5606daisy buttercup)'.
5607
5608You can see this by evaluating the following in the usual way:
5609
5610 (cdr '(rose violet daisy buttercup))
5611
5612When you evaluate this, `(violet daisy buttercup)' will appear in the
5613echo area.
5614
5615Like `car', `cdr' does not remove any elements from the list--it just
5616returns a report of what the second and subsequent elements are.
5617
5618Incidentally, in the example, the list of flowers is quoted. If it were
5619not, the Lisp interpreter would try to evaluate the list by calling
5620`rose' as a function. In this example, we do not want to do that.
5621
5622Clearly, a more reasonable name for `cdr' would be `rest'.
5623
5624(There is a lesson here: when you name new functions, consider very
5625carefully what you are doing, since you may be stuck with the names for
5626far longer than you expect. The reason this document perpetuates these
5627names is that the Emacs Lisp source code uses them, and if I did not
5628use them, you would have a hard time reading the code; but do, please,
5629try to avoid using these terms yourself. The people who come after you
5630will be grateful to you.)
5631
5632When `car' and `cdr' are applied to a list made up of symbols, such as
5633the list `(pine fir oak maple)', the element of the list returned by
5634the function `car' is the symbol `pine' without any parentheses around
5635it. `pine' is the first element in the list. However, the CDR of the
5636list is a list itself, `(fir oak maple)', as you can see by evaluating
5637the following expressions in the usual way:
5638
5639 (car '(pine fir oak maple))
5640
5641 (cdr '(pine fir oak maple))
5642
5643On the other hand, in a list of lists, the first element is itself a
5644list. `car' returns this first element as a list. For example, the
5645following list contains three sub-lists, a list of carnivores, a list
5646of herbivores and a list of sea mammals:
5647
5648 (car '((lion tiger cheetah)
5649 (gazelle antelope zebra)
5650 (whale dolphin seal)))
5651
5652In this example, the first element or CAR of the list is the list of
5653carnivores, `(lion tiger cheetah)', and the rest of the list is
5654`((gazelle antelope zebra) (whale dolphin seal))'.
5655
5656 (cdr '((lion tiger cheetah)
5657 (gazelle antelope zebra)
5658 (whale dolphin seal)))
5659
5660It is worth saying again that `car' and `cdr' are non-destructive--that
5661is, they do not modify or change lists to which they are applied. This
5662is very important for how they are used.
5663
5664Also, in the first chapter, in the discussion about atoms, I said that
5665in Lisp, "certain kinds of atom, such as an array, can be separated
5666into parts; but the mechanism for doing this is different from the
5667mechanism for splitting a list. As far as Lisp is concerned, the atoms
5668of a list are unsplittable." (*Note Lisp Atoms::.) The `car' and
5669`cdr' functions are used for splitting lists and are considered
5670fundamental to Lisp. Since they cannot split or gain access to the
5671parts of an array, an array is considered an atom. Conversely, the
5672other fundamental function, `cons', can put together or construct a
5673list, but not an array. (Arrays are handled by array-specific
5674functions. *Note Arrays: (elisp)Arrays.)
5675
5676
5677File: eintr, Node: cons, Next: nthcdr, Prev: car & cdr, Up: car cdr & cons
5678
56797.2 `cons'
5680==========
5681
5682The `cons' function constructs lists; it is the inverse of `car' and
5683`cdr'. For example, `cons' can be used to make a four element list
5684from the three element list, `(fir oak maple)':
5685
5686 (cons 'pine '(fir oak maple))
5687
5688After evaluating this list, you will see
5689
5690 (pine fir oak maple)
5691
5692appear in the echo area. `cons' causes the creation of a new list in
5693which the element is followed by the elements of the original list.
5694
5695We often say that ``cons' puts a new element at the beginning of a
5696list; it attaches or pushes elements onto the list', but this phrasing
5697can be misleading, since `cons' does not change an existing list, but
5698creates a new one.
5699
5700Like `car' and `cdr', `cons' is non-destructive.
5701
5702* Menu:
5703
5704* Build a list::
5705* length::
5706
5707
5708File: eintr, Node: Build a list, Next: length, Prev: cons, Up: cons
5709
5710Build a list
5711------------
5712
5713`cons' must have a list to attach to.(1) You cannot start from
5714absolutely nothing. If you are building a list, you need to provide at
5715least an empty list at the beginning. Here is a series of `cons'
5716expressions that build up a list of flowers. If you are reading this
5717in Info in GNU Emacs, you can evaluate each of the expressions in the
5718usual way; the value is printed in this text after `=>', which you may
5719read as `evaluates to'.
5720
5721 (cons 'buttercup ())
5722 => (buttercup)
5723
5724 (cons 'daisy '(buttercup))
5725 => (daisy buttercup)
5726
5727 (cons 'violet '(daisy buttercup))
5728 => (violet daisy buttercup)
5729
5730 (cons 'rose '(violet daisy buttercup))
5731 => (rose violet daisy buttercup)
5732
5733In the first example, the empty list is shown as `()' and a list made
5734up of `buttercup' followed by the empty list is constructed. As you
5735can see, the empty list is not shown in the list that was constructed.
5736All that you see is `(buttercup)'. The empty list is not counted as an
5737element of a list because there is nothing in an empty list. Generally
5738speaking, an empty list is invisible.
5739
5740The second example, `(cons 'daisy '(buttercup))' constructs a new, two
5741element list by putting `daisy' in front of `buttercup'; and the third
5742example constructs a three element list by putting `violet' in front of
5743`daisy' and `buttercup'.
5744
5745---------- Footnotes ----------
5746
5747(1) Actually, you can `cons' an element to an atom to produce a dotted
5748pair. Dotted pairs are not discussed here; see *Note Dotted Pair
5749Notation: (elisp)Dotted Pair Notation.
5750
5751
5752File: eintr, Node: length, Prev: Build a list, Up: cons
5753
57547.2.1 Find the Length of a List: `length'
5755-----------------------------------------
5756
5757You can find out how many elements there are in a list by using the Lisp
5758function `length', as in the following examples:
5759
5760 (length '(buttercup))
5761 => 1
5762
5763 (length '(daisy buttercup))
5764 => 2
5765
5766 (length (cons 'violet '(daisy buttercup)))
5767 => 3
5768
5769In the third example, the `cons' function is used to construct a three
5770element list which is then passed to the `length' function as its
5771argument.
5772
5773We can also use `length' to count the number of elements in an empty
5774list:
5775
5776 (length ())
5777 => 0
5778
5779As you would expect, the number of elements in an empty list is zero.
5780
5781An interesting experiment is to find out what happens if you try to find
5782the length of no list at all; that is, if you try to call `length'
5783without giving it an argument, not even an empty list:
5784
5785 (length )
5786
5787What you see, if you evaluate this, is the error message
5788
5789 Lisp error: (wrong-number-of-arguments length 0)
5790
5791This means that the function receives the wrong number of arguments,
5792zero, when it expects some other number of arguments. In this case,
5793one argument is expected, the argument being a list whose length the
5794function is measuring. (Note that _one_ list is _one_ argument, even
5795if the list has many elements inside it.)
5796
5797The part of the error message that says `length' is the name of the
5798function.
5799
5800
5801File: eintr, Node: nthcdr, Next: nth, Prev: cons, Up: car cdr & cons
5802
58037.3 `nthcdr'
5804============
5805
5806The `nthcdr' function is associated with the `cdr' function. What it
5807does is take the CDR of a list repeatedly.
5808
5809If you take the CDR of the list `(pine fir oak maple)', you will be
5810returned the list `(fir oak maple)'. If you repeat this on what was
5811returned, you will be returned the list `(oak maple)'. (Of course,
5812repeated CDRing on the original list will just give you the original
5813CDR since the function does not change the list. You need to evaluate
5814the CDR of the CDR and so on.) If you continue this, eventually you
5815will be returned an empty list, which in this case, instead of being
5816shown as `()' is shown as `nil'.
5817
5818For review, here is a series of repeated CDRs, the text following the
5819`=>' shows what is returned.
5820
5821 (cdr '(pine fir oak maple))
5822 =>(fir oak maple)
5823
5824 (cdr '(fir oak maple))
5825 => (oak maple)
5826
5827 (cdr '(oak maple))
5828 =>(maple)
5829
5830 (cdr '(maple))
5831 => nil
5832
5833 (cdr 'nil)
5834 => nil
5835
5836 (cdr ())
5837 => nil
5838
5839You can also do several CDRs without printing the values in between,
5840like this:
5841
5842 (cdr (cdr '(pine fir oak maple)))
5843 => (oak maple)
5844
5845In this example, the Lisp interpreter evaluates the innermost list
5846first. The innermost list is quoted, so it just passes the list as it
5847is to the innermost `cdr'. This `cdr' passes a list made up of the
5848second and subsequent elements of the list to the outermost `cdr',
5849which produces a list composed of the third and subsequent elements of
5850the original list. In this example, the `cdr' function is repeated and
5851returns a list that consists of the original list without its first two
5852elements.
5853
5854The `nthcdr' function does the same as repeating the call to `cdr'. In
5855the following example, the argument 2 is passed to the function
5856`nthcdr', along with the list, and the value returned is the list
5857without its first two items, which is exactly the same as repeating
5858`cdr' twice on the list:
5859
5860 (nthcdr 2 '(pine fir oak maple))
5861 => (oak maple)
5862
5863Using the original four element list, we can see what happens when
5864various numeric arguments are passed to `nthcdr', including 0, 1, and 5:
5865
5866 ;; Leave the list as it was.
5867 (nthcdr 0 '(pine fir oak maple))
5868 => (pine fir oak maple)
5869
5870 ;; Return a copy without the first element.
5871 (nthcdr 1 '(pine fir oak maple))
5872 => (fir oak maple)
5873
5874 ;; Return a copy of the list without three elements.
5875 (nthcdr 3 '(pine fir oak maple))
5876 => (maple)
5877
5878 ;; Return a copy lacking all four elements.
5879 (nthcdr 4 '(pine fir oak maple))
5880 => nil
5881
5882 ;; Return a copy lacking all elements.
5883 (nthcdr 5 '(pine fir oak maple))
5884 => nil
5885
5886
5887File: eintr, Node: nth, Next: setcar, Prev: nthcdr, Up: car cdr & cons
5888
58897.4 `nth'
5890=========
5891
5892The `nthcdr' function takes the CDR of a list repeatedly. The `nth'
5893function takes the CAR of the result returned by `nthcdr'. It returns
5894the Nth element of the list.
5895
5896Thus, if it were not defined in C for speed, the definition of `nth'
5897would be:
5898
5899 (defun nth (n list)
5900 "Returns the Nth element of LIST.
5901 N counts from zero. If LIST is not that long, nil is returned."
5902 (car (nthcdr n list)))
5903
5904(Originally, `nth' was defined in Emacs Lisp in `subr.el', but its
5905definition was redone in C in the 1980s.)
5906
5907The `nth' function returns a single element of a list. This can be
5908very convenient.
5909
5910Note that the elements are numbered from zero, not one. That is to
5911say, the first element of a list, its CAR is the zeroth element. This
5912is called `zero-based' counting and often bothers people who are
5913accustomed to the first element in a list being number one, which is
5914`one-based'.
5915
5916For example:
5917
5918 (nth 0 '("one" "two" "three"))
5919 => "one"
5920
5921 (nth 1 '("one" "two" "three"))
5922 => "two"
5923
5924It is worth mentioning that `nth', like `nthcdr' and `cdr', does not
5925change the original list--the function is non-destructive. This is in
5926sharp contrast to the `setcar' and `setcdr' functions.
5927
5928
5929File: eintr, Node: setcar, Next: setcdr, Prev: nth, Up: car cdr & cons
5930
59317.5 `setcar'
5932============
5933
5934As you might guess from their names, the `setcar' and `setcdr'
5935functions set the CAR or the CDR of a list to a new value. They
5936actually change the original list, unlike `car' and `cdr' which leave
5937the original list as it was. One way to find out how this works is to
5938experiment. We will start with the `setcar' function.
5939
5940First, we can make a list and then set the value of a variable to the
5941list, using the `setq' function. Here is a list of animals:
5942
5943 (setq animals '(antelope giraffe lion tiger))
5944
5945If you are reading this in Info inside of GNU Emacs, you can evaluate
5946this expression in the usual fashion, by positioning the cursor after
5947the expression and typing `C-x C-e'. (I'm doing this right here as I
5948write this. This is one of the advantages of having the interpreter
5949built into the computing environment. Incidentally, when there is
5950nothing on the line after the final parentheses, such as a comment,
5951point can be on the next line. Thus, if your cursor is in the first
5952column of the next line, you do not need to move it. Indeed, Emacs
5953permits any amount of white space after the final parenthesis.)
5954
5955When we evaluate the variable `animals', we see that it is bound to the
5956list `(antelope giraffe lion tiger)':
5957
5958 animals
5959 => (antelope giraffe lion tiger)
5960
5961Put another way, the variable `animals' points to the list `(antelope
5962giraffe lion tiger)'.
5963
5964Next, evaluate the function `setcar' while passing it two arguments,
5965the variable `animals' and the quoted symbol `hippopotamus'; this is
5966done by writing the three element list `(setcar animals 'hippopotamus)'
5967and then evaluating it in the usual fashion:
5968
5969 (setcar animals 'hippopotamus)
5970
5971After evaluating this expression, evaluate the variable `animals'
5972again. You will see that the list of animals has changed:
5973
5974 animals
5975 => (hippopotamus giraffe lion tiger)
5976
5977The first element on the list, `antelope' is replaced by `hippopotamus'.
5978
5979So we can see that `setcar' did not add a new element to the list as
5980`cons' would have; it replaced `antelope' with `hippopotamus'; it
5981_changed_ the list.
5982
5983
5984File: eintr, Node: setcdr, Next: cons Exercise, Prev: setcar, Up: car cdr & cons
5985
59867.6 `setcdr'
5987============
5988
5989The `setcdr' function is similar to the `setcar' function, except that
5990the function replaces the second and subsequent elements of a list
5991rather than the first element.
5992
5993(To see how to change the last element of a list, look ahead to *Note
5994The `kill-new' function: kill-new function, which uses the `nthcdr' and
5995`setcdr' functions.)
5996
5997To see how this works, set the value of the variable to a list of
5998domesticated animals by evaluating the following expression:
5999
6000 (setq domesticated-animals '(horse cow sheep goat))
6001
6002If you now evaluate the list, you will be returned the list `(horse cow
6003sheep goat)':
6004
6005 domesticated-animals
6006 => (horse cow sheep goat)
6007
6008Next, evaluate `setcdr' with two arguments, the name of the variable
6009which has a list as its value, and the list to which the CDR of the
6010first list will be set;
6011
6012 (setcdr domesticated-animals '(cat dog))
6013
6014If you evaluate this expression, the list `(cat dog)' will appear in
6015the echo area. This is the value returned by the function. The result
6016we are interested in is the "side effect", which we can see by
6017evaluating the variable `domesticated-animals':
6018
6019 domesticated-animals
6020 => (horse cat dog)
6021
6022Indeed, the list is changed from `(horse cow sheep goat)' to `(horse
6023cat dog)'. The CDR of the list is changed from `(cow sheep goat)' to
6024`(cat dog)'.
6025
6026
6027File: eintr, Node: cons Exercise, Prev: setcdr, Up: car cdr & cons
6028
60297.7 Exercise
6030============
6031
6032Construct a list of four birds by evaluating several expressions with
6033`cons'. Find out what happens when you `cons' a list onto itself.
6034Replace the first element of the list of four birds with a fish.
6035Replace the rest of that list with a list of other fish.
6036
6037
6038File: eintr, Node: Cutting & Storing Text, Next: List Implementation, Prev: car cdr & cons, Up: Top
6039
60408 Cutting and Storing Text
6041**************************
6042
6043Whenever you cut or clip text out of a buffer with a `kill' command in
6044GNU Emacs, it is stored in a list and you can bring it back with a
6045`yank' command.
6046
6047(The use of the word `kill' in Emacs for processes which specifically
6048_do not_ destroy the values of the entities is an unfortunate
6049historical accident. A much more appropriate word would be `clip' since
6050that is what the kill commands do; they clip text out of a buffer and
6051put it into storage from which it can be brought back. I have often
6052been tempted to replace globally all occurrences of `kill' in the Emacs
6053sources with `clip' and all occurrences of `killed' with `clipped'.)
6054
6055* Menu:
6056
6057* Storing Text::
6058* zap-to-char::
6059* kill-region::
6060* copy-region-as-kill::
6061* Digression into C::
6062* defvar::
6063* cons & search-fwd Review::
6064* search Exercises::
6065
6066
6067File: eintr, Node: Storing Text, Next: zap-to-char, Prev: Cutting & Storing Text, Up: Cutting & Storing Text
6068
6069Storing Text in a List
6070======================
6071
6072When text is cut out of a buffer, it is stored on a list. Successive
6073pieces of text are stored on the list successively, so the list might
6074look like this:
6075
6076 ("a piece of text" "previous piece")
6077
6078The function `cons' can be used to create a new list from a piece of
6079text (an `atom', to use the jargon) and an existing list, like this:
6080
6081 (cons "another piece"
6082 '("a piece of text" "previous piece"))
6083
6084If you evaluate this expression, a list of three elements will appear in
6085the echo area:
6086
6087 ("another piece" "a piece of text" "previous piece")
6088
6089With the `car' and `nthcdr' functions, you can retrieve whichever piece
6090of text you want. For example, in the following code, `nthcdr 1 ...'
6091returns the list with the first item removed; and the `car' returns the
6092first element of that remainder--the second element of the original
6093list:
6094
6095 (car (nthcdr 1 '("another piece"
6096 "a piece of text"
6097 "previous piece")))
6098 => "a piece of text"
6099
6100The actual functions in Emacs are more complex than this, of course.
6101The code for cutting and retrieving text has to be written so that
6102Emacs can figure out which element in the list you want--the first,
6103second, third, or whatever. In addition, when you get to the end of
6104the list, Emacs should give you the first element of the list, rather
6105than nothing at all.
6106
6107The list that holds the pieces of text is called the "kill ring". This
6108chapter leads up to a description of the kill ring and how it is used
6109by first tracing how the `zap-to-char' function works. This function
6110uses (or `calls') a function that invokes a function that manipulates
6111the kill ring. Thus, before reaching the mountains, we climb the
6112foothills.
6113
6114A subsequent chapter describes how text that is cut from the buffer is
6115retrieved. *Note Yanking Text Back: Yanking.
6116
6117
6118File: eintr, Node: zap-to-char, Next: kill-region, Prev: Storing Text, Up: Cutting & Storing Text
6119
61208.1 `zap-to-char'
6121=================
6122
6123The `zap-to-char' function changed a little between GNU Emacs version
612419 and GNU Emacs version 22. However, `zap-to-char' calls another
6125function, `kill-region', which enjoyed a major rewrite.
6126
6127The `kill-region' function in Emacs 19 is complex, but does not use
6128code that is important at this time. We will skip it.
6129
6130The `kill-region' function in Emacs 22 is easier to read than the same
6131function in Emacs 19 and introduces a very important concept, that of
6132error handling. We will walk through the function.
6133
6134But first, let us look at the interactive `zap-to-char' function.
6135
6136* Menu:
6137
6138* Complete zap-to-char::
6139* zap-to-char interactive::
6140* zap-to-char body::
6141* search-forward::
6142* progn::
6143* Summing up zap-to-char::
6144
6145
6146File: eintr, Node: Complete zap-to-char, Next: zap-to-char interactive, Prev: zap-to-char, Up: zap-to-char
6147
6148The Complete `zap-to-char' Implementation
6149-----------------------------------------
6150
6151The GNU Emacs version 19 and version 21 implementations of the
6152`zap-to-char' function are nearly identical in form, and they work
6153alike. The function removes the text in the region between the
6154location of the cursor (i.e., of point) up to and including the next
6155occurrence of a specified character. The text that `zap-to-char'
6156removes is put in the kill ring; and it can be retrieved from the kill
6157ring by typing `C-y' (`yank'). If the command is given an argument, it
6158removes text through that number of occurrences. Thus, if the cursor
6159were at the beginning of this sentence and the character were `s',
6160`Thus' would be removed. If the argument were two, `Thus, if the curs'
6161would be removed, up to and including the `s' in `cursor'.
6162
6163If the specified character is not found, `zap-to-char' will say "Search
6164failed", tell you the character you typed, and not remove any text.
6165
6166In order to determine how much text to remove, `zap-to-char' uses a
6167search function. Searches are used extensively in code that
6168manipulates text, and we will focus attention on them as well as on the
6169deletion command.
6170
6171Here is the complete text of the version 22 implementation of the
6172function:
6173
6174 (defun zap-to-char (arg char)
6175 "Kill up to and including ARG'th occurrence of CHAR.
6176 Case is ignored if `case-fold-search' is non-nil in the current buffer.
6177 Goes backward if ARG is negative; error if CHAR not found."
6178 (interactive "p\ncZap to char: ")
6179 (if (char-table-p translation-table-for-input)
6180 (setq char (or (aref translation-table-for-input char) char)))
6181 (kill-region (point) (progn
6182 (search-forward (char-to-string char) nil nil arg)
6183 (point))))
6184
6185
6186File: eintr, Node: zap-to-char interactive, Next: zap-to-char body, Prev: Complete zap-to-char, Up: zap-to-char
6187
61888.1.1 The `interactive' Expression
6189----------------------------------
6190
6191The interactive expression in the `zap-to-char' command looks like this:
6192
6193 (interactive "p\ncZap to char: ")
6194
6195The part within quotation marks, `"p\ncZap to char: "', specifies two
6196different things. First, and most simply, is the `p'. This part is
6197separated from the next part by a newline, `\n'. The `p' means that
6198the first argument to the function will be passed the value of a
6199`processed prefix'. The prefix argument is passed by typing `C-u' and
6200a number, or `M-' and a number. If the function is called
6201interactively without a prefix, 1 is passed to this argument.
6202
6203The second part of `"p\ncZap to char: "' is `cZap to char: '. In this
6204part, the lower case `c' indicates that `interactive' expects a prompt
6205and that the argument will be a character. The prompt follows the `c'
6206and is the string `Zap to char: ' (with a space after the colon to make
6207it look good).
6208
6209What all this does is prepare the arguments to `zap-to-char' so they
6210are of the right type, and give the user a prompt.
6211
6212In a read-only buffer, the `zap-to-char' function copies the text to
6213the kill ring, but does not remove it. The echo area displays a
6214message saying that the buffer is read-only. Also, the terminal may
6215beep or blink at you.
6216
6217Let us continue with the interactive specification.
6218
6219
6220File: eintr, Node: zap-to-char body, Next: search-forward, Prev: zap-to-char interactive, Up: zap-to-char
6221
62228.1.2 The Body of `zap-to-char'
6223-------------------------------
6224
6225The body of the `zap-to-char' function contains the code that kills
6226(that is, removes) the text in the region from the current position of
6227the cursor up to and including the specified character.
6228
6229The documentation is thorough. You do need to know the jargon meaning
6230of the word `kill'.
6231
6232The first part of the code looks like this:
6233
6234 (if (char-table-p translation-table-for-input)
6235 (setq char (or (aref translation-table-for-input char) char)))
6236 (kill-region (point) (progn
6237 (search-forward (char-to-string char) nil nil arg)
6238 (point)))
6239
6240`char-table-p' is an hitherto unseen function. It determines whether
6241its argument is a character table. When it is, it sets the character
6242passed to `zap-to-char' to one of them, if that character exists, or to
6243the character itself. (This becomes important for certain characters
6244in non-European languages. The `aref' function extracts an element
6245from an array. It is an array-specific function that is not described
6246in this document. *Note Arrays: (elisp)Arrays.)
6247
6248`(point)' is the current position of the cursor.
6249
6250The next part of the code is an expression using `progn'. The body of
6251the `progn' consists of calls to `search-forward' and `point'.
6252
6253It is easier to understand how `progn' works after learning about
6254`search-forward', so we will look at `search-forward' and then at
6255`progn'.
6256
6257
6258File: eintr, Node: search-forward, Next: progn, Prev: zap-to-char body, Up: zap-to-char
6259
62608.1.3 The `search-forward' Function
6261-----------------------------------
6262
6263The `search-forward' function is used to locate the
6264zapped-for-character in `zap-to-char'. If the search is successful,
6265`search-forward' leaves point immediately after the last character in
6266the target string. (In `zap-to-char', the target string is just one
6267character long. `zap-to-char' uses the function `char-to-string' to
6268ensure that the computer treats that character as a string.) If the
6269search is backwards, `search-forward' leaves point just before the
6270first character in the target. Also, `search-forward' returns `t' for
6271true. (Moving point is therefore a `side effect'.)
6272
6273In `zap-to-char', the `search-forward' function looks like this:
6274
6275 (search-forward (char-to-string char) nil nil arg)
6276
6277The `search-forward' function takes four arguments:
6278
6279 1. The first argument is the target, what is searched for. This must
6280 be a string, such as `"z"'.
6281
6282 As it happens, the argument passed to `zap-to-char' is a single
6283 character. Because of the way computers are built, the Lisp
6284 interpreter may treat a single character as being different from a
6285 string of characters. Inside the computer, a single character has
6286 a different electronic format than a string of one character. (A
6287 single character can often be recorded in the computer using
6288 exactly one byte; but a string may be longer, and the computer
6289 needs to be ready for this.) Since the `search-forward' function
6290 searches for a string, the character that the `zap-to-char'
6291 function receives as its argument must be converted inside the
6292 computer from one format to the other; otherwise the
6293 `search-forward' function will fail. The `char-to-string'
6294 function is used to make this conversion.
6295
6296 2. The second argument bounds the search; it is specified as a
6297 position in the buffer. In this case, the search can go to the
6298 end of the buffer, so no bound is set and the second argument is
6299 `nil'.
6300
6301 3. The third argument tells the function what it should do if the
6302 search fails--it can signal an error (and print a message) or it
6303 can return `nil'. A `nil' as the third argument causes the
6304 function to signal an error when the search fails.
6305
6306 4. The fourth argument to `search-forward' is the repeat count--how
6307 many occurrences of the string to look for. This argument is
6308 optional and if the function is called without a repeat count,
6309 this argument is passed the value 1. If this argument is
6310 negative, the search goes backwards.
6311
6312In template form, a `search-forward' expression looks like this:
6313
6314 (search-forward "TARGET-STRING"
6315 LIMIT-OF-SEARCH
6316 WHAT-TO-DO-IF-SEARCH-FAILS
6317 REPEAT-COUNT)
6318
6319We will look at `progn' next.
6320
6321
6322File: eintr, Node: progn, Next: Summing up zap-to-char, Prev: search-forward, Up: zap-to-char
6323
63248.1.4 The `progn' Special Form
6325------------------------------
6326
6327`progn' is a special form that causes each of its arguments to be
6328evaluated in sequence and then returns the value of the last one. The
6329preceding expressions are evaluated only for the side effects they
6330perform. The values produced by them are discarded.
6331
6332The template for a `progn' expression is very simple:
6333
6334 (progn
6335 BODY...)
6336
6337In `zap-to-char', the `progn' expression has to do two things: put
6338point in exactly the right position; and return the location of point
6339so that `kill-region' will know how far to kill to.
6340
6341The first argument to the `progn' is `search-forward'. When
6342`search-forward' finds the string, the function leaves point
6343immediately after the last character in the target string. (In this
6344case the target string is just one character long.) If the search is
6345backwards, `search-forward' leaves point just before the first
6346character in the target. The movement of point is a side effect.
6347
6348The second and last argument to `progn' is the expression `(point)'.
6349This expression returns the value of point, which in this case will be
6350the location to which it has been moved by `search-forward'. (In the
6351source, a line that tells the function to go to the previous character,
6352if it is going forward, was commented out in 1999; I don't remember
6353whether that feature or mis-feature was ever a part of the distributed
6354source.) The value of `point' is returned by the `progn' expression
6355and is passed to `kill-region' as `kill-region''s second argument.
6356
6357
6358File: eintr, Node: Summing up zap-to-char, Prev: progn, Up: zap-to-char
6359
63608.1.5 Summing up `zap-to-char'
6361------------------------------
6362
6363Now that we have seen how `search-forward' and `progn' work, we can see
6364how the `zap-to-char' function works as a whole.
6365
6366The first argument to `kill-region' is the position of the cursor when
6367the `zap-to-char' command is given--the value of point at that time.
6368Within the `progn', the search function then moves point to just after
6369the zapped-to-character and `point' returns the value of this location.
6370The `kill-region' function puts together these two values of point,
6371the first one as the beginning of the region and the second one as the
6372end of the region, and removes the region.
6373
6374The `progn' special form is necessary because the `kill-region' command
6375takes two arguments; and it would fail if `search-forward' and `point'
6376expressions were written in sequence as two additional arguments. The
6377`progn' expression is a single argument to `kill-region' and returns
6378the one value that `kill-region' needs for its second argument.
6379
6380
6381File: eintr, Node: kill-region, Next: copy-region-as-kill, Prev: zap-to-char, Up: Cutting & Storing Text
6382
63838.2 `kill-region'
6384=================
6385
6386The `zap-to-char' function uses the `kill-region' function. This
6387function clips text from a region and copies that text to the kill
6388ring, from which it may be retrieved.
6389
6390The Emacs 22 version of that function uses `condition-case' and
6391`copy-region-as-kill', both of which we will explain. `condition-case'
6392is an important special form.
6393
6394In essence, the `kill-region' function calls `condition-case', which
6395takes three arguments. In this function, the first argument does
6396nothing. The second argument contains the code that does the work when
6397all goes well. The third argument contains the code that is called in
6398the event of an error.
6399
6400* Menu:
6401
6402* Complete kill-region::
6403* condition-case::
6404* Lisp macro::
6405
6406
6407File: eintr, Node: Complete kill-region, Next: condition-case, Prev: kill-region, Up: kill-region
6408
6409The Complete `kill-region' Definition
6410-------------------------------------
6411
6412We will go through the `condition-case' code in a moment. First, let
6413us look at the definition of `kill-region', with comments added:
6414
6415 (defun kill-region (beg end)
6416 "Kill (\"cut\") text between point and mark.
6417 This deletes the text from the buffer and saves it in the kill ring.
6418 The command \\[yank] can retrieve it from there. ... "
6419
6420 ;; * Since order matters, pass point first.
6421 (interactive (list (point) (mark)))
6422 ;; * And tell us if we cannot cut the text.
6423 (unless (and beg end)
6424 (error "The mark is not set now, so there is no region"))
6425
6426 ;; * `condition-case' takes three arguments.
6427 ;; If the first argument is nil, as it is here,
6428 ;; information about the error signal is not
6429 ;; stored for use by another function.
6430 (condition-case nil
6431
6432 ;; * The second argument to `condition-case' tells the
6433 ;; Lisp interpreter what to do when all goes well.
6434
6435 ;; It starts with a `let' function that extracts the string
6436 ;; and tests whether it exists. If so (that is what the
6437 ;; `when' checks), it calls an `if' function that determines
6438 ;; whether the previous command was another call to
6439 ;; `kill-region'; if it was, then the new text is appended to
6440 ;; the previous text; if not, then a different function,
6441 ;; `kill-new', is called.
6442
6443 ;; The `kill-append' function concatenates the new string and
6444 ;; the old. The `kill-new' function inserts text into a new
6445 ;; item in the kill ring.
6446
6447 ;; `when' is an `if' without an else-part. The second `when'
6448 ;; again checks whether the current string exists; in
6449 ;; addition, it checks whether the previous command was
6450 ;; another call to `kill-region'. If one or the other
6451 ;; condition is true, then it sets the current command to
6452 ;; be `kill-region'.
6453 (let ((string (filter-buffer-substring beg end t)))
6454 (when string ;STRING is nil if BEG = END
6455 ;; Add that string to the kill ring, one way or another.
6456 (if (eq last-command 'kill-region)
6457 ;; - `yank-handler' is an optional argument to
6458 ;; `kill-region' that tells the `kill-append' and
6459 ;; `kill-new' functions how deal with properties
6460 ;; added to the text, such as `bold' or `italics'.
6461 (kill-append string (< end beg) yank-handler)
6462 (kill-new string nil yank-handler)))
6463 (when (or string (eq last-command 'kill-region))
6464 (setq this-command 'kill-region))
6465 nil)
6466
6467 ;; * The third argument to `condition-case' tells the interpreter
6468 ;; what to do with an error.
6469 ;; The third argument has a conditions part and a body part.
6470 ;; If the conditions are met (in this case,
6471 ;; if text or buffer are read-only)
6472 ;; then the body is executed.
6473 ;; The first part of the third argument is the following:
6474 ((buffer-read-only text-read-only) ;; the if-part
6475 ;; ... the then-part
6476 (copy-region-as-kill beg end)
6477 ;; Next, also as part of the then-part, set this-command, so
6478 ;; it will be set in an error
6479 (setq this-command 'kill-region)
6480 ;; Finally, in the then-part, send a message if you may copy
6481 ;; the text to the kill ring without signally an error, but
6482 ;; don't if you may not.
6483 (if kill-read-only-ok
6484 (progn (message "Read only text copied to kill ring") nil)
6485 (barf-if-buffer-read-only)
6486 ;; If the buffer isn't read-only, the text is.
6487 (signal 'text-read-only (list (current-buffer)))))
6488
6489
6490File: eintr, Node: condition-case, Next: Lisp macro, Prev: Complete kill-region, Up: kill-region
6491
64928.2.1 `condition-case'
6493----------------------
6494
6495As we have seen earlier (*note Generate an Error Message: Making
6496Errors.), when the Emacs Lisp interpreter has trouble evaluating an
6497expression, it provides you with help; in the jargon, this is called
6498"signaling an error". Usually, the computer stops the program and
6499shows you a message.
6500
6501However, some programs undertake complicated actions. They should not
6502simply stop on an error. In the `kill-region' function, the most
6503likely error is that you will try to kill text that is read-only and
6504cannot be removed. So the `kill-region' function contains code to
6505handle this circumstance. This code, which makes up the body of the
6506`kill-region' function, is inside of a `condition-case' special form.
6507
6508The template for `condition-case' looks like this:
6509
6510 (condition-case
6511 VAR
6512 BODYFORM
6513 ERROR-HANDLER...)
6514
6515The second argument, BODYFORM, is straightforward. The
6516`condition-case' special form causes the Lisp interpreter to evaluate
6517the code in BODYFORM. If no error occurs, the special form returns the
6518code's value and produces the side-effects, if any.
6519
6520In short, the BODYFORM part of a `condition-case' expression determines
6521what should happen when everything works correctly.
6522
6523However, if an error occurs, among its other actions, the function
6524generating the error signal will define one or more error condition
6525names.
6526
6527An error handler is the third argument to `condition case'. An error
6528handler has two parts, a CONDITION-NAME and a BODY. If the
6529CONDITION-NAME part of an error handler matches a condition name
6530generated by an error, then the BODY part of the error handler is run.
6531
6532As you will expect, the CONDITION-NAME part of an error handler may be
6533either a single condition name or a list of condition names.
6534
6535Also, a complete `condition-case' expression may contain more than one
6536error handler. When an error occurs, the first applicable handler is
6537run.
6538
6539Lastly, the first argument to the `condition-case' expression, the VAR
6540argument, is sometimes bound to a variable that contains information
6541about the error. However, if that argument is nil, as is the case in
6542`kill-region', that information is discarded.
6543
6544In brief, in the `kill-region' function, the code `condition-case'
6545works like this:
6546
6547 IF NO ERRORS, RUN ONLY THIS CODE
6548 BUT, IF ERRORS, RUN THIS OTHER CODE.
6549
6550
6551File: eintr, Node: Lisp macro, Prev: condition-case, Up: kill-region
6552
65538.2.2 Lisp macro
6554----------------
6555
6556The part of the `condition-case' expression that is evaluated in the
6557expectation that all goes well has a `when'. The code uses `when' to
6558determine whether the `string' variable points to text that exists.
6559
6560A `when' expression is simply a programmers' convenience. It is an
6561`if' without the possibility of an else clause. In your mind, you can
6562replace `when' with `if' and understand what goes on. That is what the
6563Lisp interpreter does.
6564
6565Technically speaking, `when' is a Lisp macro. A Lisp "macro" enables
6566you to define new control constructs and other language features. It
6567tells the interpreter how to compute another Lisp expression which will
6568in turn compute the value. In this case, the `other expression' is an
6569`if' expression. For more about Lisp macros, see *Note Macros:
6570(elisp)Macros. The C programming language also provides macros. These
6571are different, but also useful.
6572
6573If the string has content, then another conditional expression is
6574executed. This is an `if' with both a then-part and an else-part.
6575
6576 (if (eq last-command 'kill-region)
6577 (kill-append string (< end beg) yank-handler)
6578 (kill-new string nil yank-handler))
6579
6580The then-part is evaluated if the previous command was another call to
6581`kill-region'; if not, the else-part is evaluated.
6582
6583`yank-handler' is an optional argument to `kill-region' that tells the
6584`kill-append' and `kill-new' functions how deal with properties added
6585to the text, such as `bold' or `italics'.
6586
6587`last-command' is a variable that comes with Emacs that we have not
6588seen before. Normally, whenever a function is executed, Emacs sets the
6589value of `last-command' to the previous command.
6590
6591In this segment of the definition, the `if' expression checks whether
6592the previous command was `kill-region'. If it was,
6593
6594 (kill-append string (< end beg) yank-handler)
6595
6596concatenates a copy of the newly clipped text to the just previously
6597clipped text in the kill ring.
6598
6599
6600File: eintr, Node: copy-region-as-kill, Next: Digression into C, Prev: kill-region, Up: Cutting & Storing Text
6601
66028.3 `copy-region-as-kill'
6603=========================
6604
6605The `copy-region-as-kill' function copies a region of text from a
6606buffer and (via either `kill-append' or `kill-new') saves it in the
6607`kill-ring'.
6608
6609If you call `copy-region-as-kill' immediately after a `kill-region'
6610command, Emacs appends the newly copied text to the previously copied
6611text. This means that if you yank back the text, you get it all, from
6612both this and the previous operation. On the other hand, if some other
6613command precedes the `copy-region-as-kill', the function copies the
6614text into a separate entry in the kill ring.
6615
6616* Menu:
6617
6618* Complete copy-region-as-kill::
6619* copy-region-as-kill body::
6620
6621
6622File: eintr, Node: Complete copy-region-as-kill, Next: copy-region-as-kill body, Prev: copy-region-as-kill, Up: copy-region-as-kill
6623
6624The complete `copy-region-as-kill' function definition
6625------------------------------------------------------
6626
6627Here is the complete text of the version 22 `copy-region-as-kill'
6628function:
6629
6630 (defun copy-region-as-kill (beg end)
6631 "Save the region as if killed, but don't kill it.
6632 In Transient Mark mode, deactivate the mark.
6633 If `interprogram-cut-function' is non-nil, also save the text for a window
6634 system cut and paste."
6635 (interactive "r")
6636 (if (eq last-command 'kill-region)
6637 (kill-append (filter-buffer-substring beg end) (< end beg))
6638 (kill-new (filter-buffer-substring beg end)))
6639 (if transient-mark-mode
6640 (setq deactivate-mark t))
6641 nil)
6642
6643As usual, this function can be divided into its component parts:
6644
6645 (defun copy-region-as-kill (ARGUMENT-LIST)
6646 "DOCUMENTATION..."
6647 (interactive "r")
6648 BODY...)
6649
6650The arguments are `beg' and `end' and the function is interactive with
6651`"r"', so the two arguments must refer to the beginning and end of the
6652region. If you have been reading though this document from the
6653beginning, understanding these parts of a function is almost becoming
6654routine.
6655
6656The documentation is somewhat confusing unless you remember that the
6657word `kill' has a meaning different from usual. The `Transient Mark'
6658and `interprogram-cut-function' comments explain certain side-effects.
6659
6660After you once set a mark, a buffer always contains a region. If you
6661wish, you can use Transient Mark mode to highlight the region
6662temporarily. (No one wants to highlight the region all the time, so
6663Transient Mark mode highlights it only at appropriate times. Many
6664people turn off Transient Mark mode, so the region is never
6665highlighted.)
6666
6667Also, a windowing system allows you to copy, cut, and paste among
6668different programs. In the X windowing system, for example, the
6669`interprogram-cut-function' function is `x-select-text', which works
6670with the windowing system's equivalent of the Emacs kill ring.
6671
6672The body of the `copy-region-as-kill' function starts with an `if'
6673clause. What this clause does is distinguish between two different
6674situations: whether or not this command is executed immediately after a
6675previous `kill-region' command. In the first case, the new region is
6676appended to the previously copied text. Otherwise, it is inserted into
6677the beginning of the kill ring as a separate piece of text from the
6678previous piece.
6679
6680The last two lines of the function prevent the region from lighting up
6681if Transient Mark mode is turned on.
6682
6683The body of `copy-region-as-kill' merits discussion in detail.
6684
6685
6686File: eintr, Node: copy-region-as-kill body, Prev: Complete copy-region-as-kill, Up: copy-region-as-kill
6687
66888.3.1 The Body of `copy-region-as-kill'
6689---------------------------------------
6690
6691The `copy-region-as-kill' function works in much the same way as the
6692`kill-region' function. Both are written so that two or more kills in
6693a row combine their text into a single entry. If you yank back the
6694text from the kill ring, you get it all in one piece. Moreover, kills
6695that kill forward from the current position of the cursor are added to
6696the end of the previously copied text and commands that copy text
6697backwards add it to the beginning of the previously copied text. This
6698way, the words in the text stay in the proper order.
6699
6700Like `kill-region', the `copy-region-as-kill' function makes use of the
6701`last-command' variable that keeps track of the previous Emacs command.
6702
6703* Menu:
6704
6705* last-command & this-command::
6706* kill-append function::
6707* kill-new function::
6708
6709
6710File: eintr, Node: last-command & this-command, Next: kill-append function, Prev: copy-region-as-kill body, Up: copy-region-as-kill body
6711
6712`last-command' and `this-command'
6713.................................
6714
6715Normally, whenever a function is executed, Emacs sets the value of
6716`this-command' to the function being executed (which in this case would
6717be `copy-region-as-kill'). At the same time, Emacs sets the value of
6718`last-command' to the previous value of `this-command'.
6719
6720In the first part of the body of the `copy-region-as-kill' function, an
6721`if' expression determines whether the value of `last-command' is
6722`kill-region'. If so, the then-part of the `if' expression is
6723evaluated; it uses the `kill-append' function to concatenate the text
6724copied at this call to the function with the text already in the first
6725element (the CAR) of the kill ring. On the other hand, if the value of
6726`last-command' is not `kill-region', then the `copy-region-as-kill'
6727function attaches a new element to the kill ring using the `kill-new'
6728function.
6729
6730The `if' expression reads as follows; it uses `eq', which is a function
6731we have not yet seen:
6732
6733 (if (eq last-command 'kill-region)
6734 ;; then-part
6735 (kill-append (filter-buffer-substring beg end) (< end beg))
6736 ;; else-part
6737 (kill-new (filter-buffer-substring beg end)))
6738
6739(The `filter-buffer-substring' function returns a filtered substring of
6740the buffer, if any. Optionally--the arguments are not here, so neither
6741is done--the function may delete the initial text or return the text
6742without its properties; this function is a replacement for the older
6743`buffer-substring' function, which came before text properties were
6744implemented.)
6745
6746The `eq' function tests whether its first argument is the same Lisp
6747object as its second argument. The `eq' function is similar to the
6748`equal' function in that it is used to test for equality, but differs
6749in that it determines whether two representations are actually the same
6750object inside the computer, but with different names. `equal'
6751determines whether the structure and contents of two expressions are
6752the same.
6753
6754If the previous command was `kill-region', then the Emacs Lisp
6755interpreter calls the `kill-append' function
6756
6757
6758File: eintr, Node: kill-append function, Next: kill-new function, Prev: last-command & this-command, Up: copy-region-as-kill body
6759
6760The `kill-append' function
6761..........................
6762
6763The `kill-append' function looks like this:
6764
6765 (defun kill-append (string before-p &optional yank-handler)
6766 "Append STRING to the end of the latest kill in the kill ring.
6767 If BEFORE-P is non-nil, prepend STRING to the kill.
6768 ... "
6769 (let* ((cur (car kill-ring)))
6770 (kill-new (if before-p (concat string cur) (concat cur string))
6771 (or (= (length cur) 0)
6772 (equal yank-handler (get-text-property 0 'yank-handler cur)))
6773 yank-handler)))
6774
6775The `kill-append' function is fairly straightforward. It uses the
6776`kill-new' function, which we will discuss in more detail in a moment.
6777
6778(Also, the function provides an optional argument called
6779`yank-handler'; when invoked, this argument tells the function how to
6780deal with properties added to the text, such as `bold' or `italics'.)
6781
6782It has a `let*' function to set the value of the first element of the
6783kill ring to `cur'. (I do not know why the function does not use `let'
6784instead; only one value is set in the expression. Perhaps this is a
6785bug that produces no problems?)
6786
6787Consider the conditional that is one of the two arguments to
6788`kill-new'. It uses `concat' to concatenate the new text to the CAR of
6789the kill ring. Whether it prepends or appends the text depends on the
6790results of an `if' expression:
6791
6792 (if before-p ; if-part
6793 (concat string cur) ; then-part
6794 (concat cur string)) ; else-part
6795
6796If the region being killed is before the region that was killed in the
6797last command, then it should be prepended before the material that was
6798saved in the previous kill; and conversely, if the killed text follows
6799what was just killed, it should be appended after the previous text.
6800The `if' expression depends on the predicate `before-p' to decide
6801whether the newly saved text should be put before or after the
6802previously saved text.
6803
6804The symbol `before-p' is the name of one of the arguments to
6805`kill-append'. When the `kill-append' function is evaluated, it is
6806bound to the value returned by evaluating the actual argument. In this
6807case, this is the expression `(< end beg)'. This expression does not
6808directly determine whether the killed text in this command is located
6809before or after the kill text of the last command; what it does is
6810determine whether the value of the variable `end' is less than the
6811value of the variable `beg'. If it is, it means that the user is most
6812likely heading towards the beginning of the buffer. Also, the result
6813of evaluating the predicate expression, `(< end beg)', will be true and
6814the text will be prepended before the previous text. On the other
6815hand, if the value of the variable `end' is greater than the value of
6816the variable `beg', the text will be appended after the previous text.
6817
6818When the newly saved text will be prepended, then the string with the
6819new text will be concatenated before the old text:
6820
6821 (concat string cur)
6822
6823But if the text will be appended, it will be concatenated after the old
6824text:
6825
6826 (concat cur string))
6827
6828To understand how this works, we first need to review the `concat'
6829function. The `concat' function links together or unites two strings
6830of text. The result is a string. For example:
6831
6832 (concat "abc" "def")
6833 => "abcdef"
6834
6835 (concat "new "
6836 (car '("first element" "second element")))
6837 => "new first element"
6838
6839 (concat (car
6840 '("first element" "second element")) " modified")
6841 => "first element modified"
6842
6843We can now make sense of `kill-append': it modifies the contents of the
6844kill ring. The kill ring is a list, each element of which is saved
6845text. The `kill-append' function uses the `kill-new' function which in
6846turn uses the `setcar' function.
6847
6848
6849File: eintr, Node: kill-new function, Prev: kill-append function, Up: copy-region-as-kill body
6850
6851The `kill-new' function
6852.......................
6853
6854The `kill-new' function looks like this:
6855
6856 (defun kill-new (string &optional replace yank-handler)
6857 "Make STRING the latest kill in the kill ring.
6858 Set `kill-ring-yank-pointer' to point to it.
6859
6860 If `interprogram-cut-function' is non-nil, apply it to STRING.
6861 Optional second argument REPLACE non-nil means that STRING will replace
6862 the front of the kill ring, rather than being added to the list.
6863 ..."
6864 (if (> (length string) 0)
6865 (if yank-handler
6866 (put-text-property 0 (length string)
6867 'yank-handler yank-handler string))
6868 (if yank-handler
6869 (signal 'args-out-of-range
6870 (list string "yank-handler specified for empty string"))))
6871 (if (fboundp 'menu-bar-update-yank-menu)
6872 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
6873 (if (and replace kill-ring)
6874 (setcar kill-ring string)
6875 (push string kill-ring)
6876 (if (> (length kill-ring) kill-ring-max)
6877 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
6878 (setq kill-ring-yank-pointer kill-ring)
6879 (if interprogram-cut-function
6880 (funcall interprogram-cut-function string (not replace))))
6881
6882(Notice that the function is not interactive.)
6883
6884As usual, we can look at this function in parts.
6885
6886The function definition has an optional `yank-handler' argument, which
6887when invoked tells the function how to deal with properties added to
6888the text, such as `bold' or `italics'. We will skip that.
6889
6890The first line of the documentation makes sense:
6891
6892 Make STRING the latest kill in the kill ring.
6893
6894Let's skip over the rest of the documentation for the moment.
6895
6896Also, let's skip over the initial `if' expression and those lines of
6897code involving `menu-bar-update-yank-menu'. We will explain them below.
6898
6899The critical lines are these:
6900
6901 (if (and replace kill-ring)
6902 ;; then
6903 (setcar kill-ring string)
6904 ;; else
6905 (push string kill-ring)
6906 (setq kill-ring (cons string kill-ring))
6907 (if (> (length kill-ring) kill-ring-max)
6908 ;; avoid overly long kill ring
6909 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
6910 (setq kill-ring-yank-pointer kill-ring)
6911 (if interprogram-cut-function
6912 (funcall interprogram-cut-function string (not replace))))
6913
6914The conditional test is `(and replace kill-ring)'. This will be true
6915when two conditions are met: the kill ring has something in it, and
6916the `replace' variable is true.
6917
6918When the `kill-append' function sets `replace' to be true and when the
6919kill ring has at least one item in it, the `setcar' expression is
6920executed:
6921
6922 (setcar kill-ring string)
6923
6924The `setcar' function actually changes the first element of the
6925`kill-ring' list to the value of `string'. It replaces the first
6926element.
6927
6928On the other hand, if the kill ring is empty, or replace is false, the
6929else-part of the condition is executed:
6930
6931 (push string kill-ring)
6932
6933`push' puts its first argument onto the second. It is the same as the
6934older
6935
6936 (setq kill-ring (cons string kill-ring))
6937
6938or the newer
6939
6940 (add-to-list kill-ring string)
6941
6942When it is false, the expression first constructs a new version of the
6943kill ring by prepending `string' to the existing kill ring as a new
6944element (that is what the `push' does). Then it executes a second `if'
6945clause. This second `if' clause keeps the kill ring from growing too
6946long.
6947
6948Let's look at these two expressions in order.
6949
6950The `push' line of the else-part sets the new value of the kill ring to
6951what results from adding the string being killed to the old kill ring.
6952
6953We can see how this works with an example.
6954
6955First,
6956
6957 (setq example-list '("here is a clause" "another clause"))
6958
6959After evaluating this expression with `C-x C-e', you can evaluate
6960`example-list' and see what it returns:
6961
6962 example-list
6963 => ("here is a clause" "another clause")
6964
6965Now, we can add a new element on to this list by evaluating the
6966following expression:
6967
6968 (push "a third clause" example-list)
6969
6970When we evaluate `example-list', we find its value is:
6971
6972 example-list
6973 => ("a third clause" "here is a clause" "another clause")
6974
6975Thus, the third clause is added to the list by `push'.
6976
6977Now for the second part of the `if' clause. This expression keeps the
6978kill ring from growing too long. It looks like this:
6979
6980 (if (> (length kill-ring) kill-ring-max)
6981 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
6982
6983The code checks whether the length of the kill ring is greater than the
6984maximum permitted length. This is the value of `kill-ring-max' (which
6985is 60, by default). If the length of the kill ring is too long, then
6986this code sets the last element of the kill ring to `nil'. It does
6987this by using two functions, `nthcdr' and `setcdr'.
6988
6989We looked at `setcdr' earlier (*note `setcdr': setcdr.). It sets the
6990CDR of a list, just as `setcar' sets the CAR of a list. In this case,
6991however, `setcdr' will not be setting the CDR of the whole kill ring;
6992the `nthcdr' function is used to cause it to set the CDR of the next to
6993last element of the kill ring--this means that since the CDR of the
6994next to last element is the last element of the kill ring, it will set
6995the last element of the kill ring.
6996
6997The `nthcdr' function works by repeatedly taking the CDR of a list--it
6998takes the CDR of the CDR of the CDR ... It does this N times and
6999returns the results. (*Note `nthcdr': nthcdr.)
7000
7001Thus, if we had a four element list that was supposed to be three
7002elements long, we could set the CDR of the next to last element to
7003`nil', and thereby shorten the list. (If you sent the last element to
7004some other value than `nil', which you could do, then you would not
7005have shortened the list. *Note `setcdr': setcdr.)
7006
7007You can see shortening by evaluating the following three expressions in
7008turn. First set the value of `trees' to `(maple oak pine birch)', then
7009set the CDR of its second CDR to `nil' and then find the value of
7010`trees':
7011
7012 (setq trees '(maple oak pine birch))
7013 => (maple oak pine birch)
7014
7015 (setcdr (nthcdr 2 trees) nil)
7016 => nil
7017
7018 trees
7019 => (maple oak pine)
7020
7021(The value returned by the `setcdr' expression is `nil' since that is
7022what the CDR is set to.)
7023
7024To repeat, in `kill-new', the `nthcdr' function takes the CDR a number
7025of times that is one less than the maximum permitted size of the kill
7026ring and `setcdr' sets the CDR of that element (which will be the rest
7027of the elements in the kill ring) to `nil'. This prevents the kill
7028ring from growing too long.
7029
7030The next to last expression in the `kill-new' function is
7031
7032 (setq kill-ring-yank-pointer kill-ring)
7033
7034The `kill-ring-yank-pointer' is a global variable that is set to be the
7035`kill-ring'.
7036
7037Even though the `kill-ring-yank-pointer' is called a `pointer', it is a
7038variable just like the kill ring. However, the name has been chosen to
7039help humans understand how the variable is used. The variable is used
7040in functions such as `yank' and `yank-pop' (*note Yanking Text Back:
7041Yanking.).
7042
7043Now, to return to an early expression in the body of the function:
7044
7045 (if (fboundp 'menu-bar-update-yank-menu)
7046 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
7047
7048It starts with an `if' expression
7049
7050In this case, the expression tests first to see whether
7051`menu-bar-update-yank-menu' exists as a function, and if so, calls it.
7052The `fboundp' function returns true if the symbol it is testing has a
7053function definition that `is not void'. If the symbol's function
7054definition were void, we would receive an error message, as we did when
7055we created errors intentionally (*note Generate an Error Message:
7056Making Errors.).
7057
7058The then-part contains an expression whose first element is the
7059function `and'.
7060
7061The `and' special form evaluates each of its arguments until one of the
7062arguments returns a value of `nil', in which case the `and' expression
7063returns `nil'; however, if none of the arguments returns a value of
7064`nil', the value resulting from evaluating the last argument is
7065returned. (Since such a value is not `nil', it is considered true in
7066Emacs Lisp.) In other words, an `and' expression returns a true value
7067only if all its arguments are true. (*Note Second Buffer Related
7068Review::.)
7069
7070The expression determines whether the second argument to
7071`menu-bar-update-yank-menu' is true or not.
7072
7073`menu-bar-update-yank-menu' is one of the functions that make it
7074possible to use the `Select and Paste' menu in the Edit item of a menu
7075bar; using a mouse, you can look at the various pieces of text you have
7076saved and select one piece to paste.
7077
7078The last expression in the `kill-new' function adds the newly copied
7079string to whatever facility exists for copying and pasting among
7080different programs running in a windowing system. In the X Windowing
7081system, for example, the `x-select-text' function takes the string and
7082stores it in memory operated by X. You can paste the string in another
7083program, such as an Xterm.
7084
7085The expression looks like this:
7086
7087 (if interprogram-cut-function
7088 (funcall interprogram-cut-function string (not replace))))
7089
7090If an `interprogram-cut-function' exists, then Emacs executes
7091`funcall', which in turn calls its first argument as a function and
7092passes the remaining arguments to it. (Incidentally, as far as I can
7093see, this `if' expression could be replaced by an `and' expression
7094similar to the one in the first part of the function.)
7095
7096We are not going to discuss windowing systems and other programs
7097further, but merely note that this is a mechanism that enables GNU
7098Emacs to work easily and well with other programs.
7099
7100This code for placing text in the kill ring, either concatenated with
7101an existing element or as a new element, leads us to the code for
7102bringing back text that has been cut out of the buffer--the yank
7103commands. However, before discussing the yank commands, it is better
7104to learn how lists are implemented in a computer. This will make clear
7105such mysteries as the use of the term `pointer'.
7106
7107
7108File: eintr, Node: Digression into C, Next: defvar, Prev: copy-region-as-kill, Up: Cutting & Storing Text
7109
71108.4 Digression into C
7111=====================
7112
7113The `copy-region-as-kill' function (*note `copy-region-as-kill':
7114copy-region-as-kill.) uses the `filter-buffer-substring' function,
7115which in turn uses the `delete-and-extract-region' function. It
7116removes the contents of a region and you cannot get them back.
7117
7118Unlike the other code discussed here, the `delete-and-extract-region'
7119function is not written in Emacs Lisp; it is written in C and is one of
7120the primitives of the GNU Emacs system. Since it is very simple, I
7121will digress briefly from Lisp and describe it here.
7122
7123Like many of the other Emacs primitives, `delete-and-extract-region' is
7124written as an instance of a C macro, a macro being a template for code.
7125The complete macro looks like this:
7126
7127 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
7128 Sbuffer_substring_no_properties, 2, 2, 0,
7129 doc: /* Return the characters of part of the buffer,
7130 without the text properties.
7131 The two arguments START and END are character positions;
7132 they can be in either order. */)
7133 (start, end)
7134 Lisp_Object start, end;
7135 {
7136 register int b, e;
7137
7138 validate_region (&start, &end);
7139 b = XINT (start);
7140 e = XINT (end);
7141
7142 return make_buffer_string (b, e, 0);
7143 }
7144
7145Without going into the details of the macro writing process, let me
7146point out that this macro starts with the word `DEFUN'. The word
7147`DEFUN' was chosen since the code serves the same purpose as `defun'
7148does in Lisp. (The `DEFUN' C macro is defined in `emacs/src/lisp.h'.)
7149
7150The word `DEFUN' is followed by seven parts inside of parentheses:
7151
7152 * The first part is the name given to the function in Lisp,
7153 `delete-and-extract-region'.
7154
7155 * The second part is the name of the function in C,
7156 `Fdelete_and_extract_region'. By convention, it starts with `F'.
7157 Since C does not use hyphens in names, underscores are used
7158 instead.
7159
7160 * The third part is the name for the C constant structure that
7161 records information on this function for internal use. It is the
7162 name of the function in C but begins with an `S' instead of an `F'.
7163
7164 * The fourth and fifth parts specify the minimum and maximum number
7165 of arguments the function can have. This function demands exactly
7166 2 arguments.
7167
7168 * The sixth part is nearly like the argument that follows the
7169 `interactive' declaration in a function written in Lisp: a letter
7170 followed, perhaps, by a prompt. The only difference from the Lisp
7171 is when the macro is called with no arguments. Then you write a
7172 `0' (which is a `null string'), as in this macro.
7173
7174 If you were to specify arguments, you would place them between
7175 quotation marks. The C macro for `goto-char' includes `"NGoto
7176 char: "' in this position to indicate that the function expects a
7177 raw prefix, in this case, a numerical location in a buffer, and
7178 provides a prompt.
7179
7180 * The seventh part is a documentation string, just like the one for a
7181 function written in Emacs Lisp, except that every newline must be
7182 written explicitly as `\n' followed by a backslash and carriage
7183 return.
7184
7185 Thus, the first two lines of documentation for `goto-char' are
7186 written like this:
7187
7188 "Set point to POSITION, a number or marker.\n\
7189 Beginning of buffer is position (point-min), end is (point-max).
7190
7191In a C macro, the formal parameters come next, with a statement of what
7192kind of object they are, followed by what might be called the `body' of
7193the macro. For `delete-and-extract-region' the `body' consists of the
7194following four lines:
7195
7196 validate_region (&start, &end);
7197 if (XINT (start) == XINT (end))
7198 return build_string ("");
7199 return del_range_1 (XINT (start), XINT (end), 1, 1);
7200
7201The `validate_region' function checks whether the values passed as
7202the beginning and end of the region are the proper type and are within
7203range. If the beginning and end positions are the same, then return
7204and empty string.
7205
7206The `del_range_1' function actually deletes the text. It is a complex
7207function we will not look into. It updates the buffer and does other
7208things. However, it is worth looking at the two arguments passed to
7209`del_range'. These are `XINT (start)' and `XINT (end)'.
7210
7211As far as the C language is concerned, `start' and `end' are two
7212integers that mark the beginning and end of the region to be deleted(1).
7213
7214In early versions of Emacs, these two numbers were thirty-two bits
7215long, but the code is slowly being generalized to handle other lengths.
7216Three of the available bits are used to specify the type of
7217information; the remaining bits are used as `content'.
7218
7219`XINT' is a C macro that extracts the relevant number from the longer
7220collection of bits; the three other bits are discarded.
7221
7222The command in `delete-and-extract-region' looks like this:
7223
7224 del_range_1 (XINT (start), XINT (end), 1, 1);
7225
7226It deletes the region between the beginning position, `start', and the
7227ending position, `end'.
7228
7229From the point of view of the person writing Lisp, Emacs is all very
7230simple; but hidden underneath is a great deal of complexity to make it
7231all work.
7232
7233---------- Footnotes ----------
7234
7235(1) More precisely, and requiring more expert knowledge to understand,
7236the two integers are of type `Lisp_Object', which can also be a C union
7237instead of an integer type.
7238
7239
7240File: eintr, Node: defvar, Next: cons & search-fwd Review, Prev: Digression into C, Up: Cutting & Storing Text
7241
72428.5 Initializing a Variable with `defvar'
7243=========================================
7244
7245The `copy-region-as-kill' function is written in Emacs Lisp. Two
7246functions within it, `kill-append' and `kill-new', copy a region in a
7247buffer and save it in a variable called the `kill-ring'. This section
7248describes how the `kill-ring' variable is created and initialized using
7249the `defvar' special form.
7250
7251(Again we note that the term `kill-ring' is a misnomer. The text that
7252is clipped out of the buffer can be brought back; it is not a ring of
7253corpses, but a ring of resurrectable text.)
7254
7255In Emacs Lisp, a variable such as the `kill-ring' is created and given
7256an initial value by using the `defvar' special form. The name comes
7257from "define variable".
7258
7259The `defvar' special form is similar to `setq' in that it sets the
7260value of a variable. It is unlike `setq' in two ways: first, it only
7261sets the value of the variable if the variable does not already have a
7262value. If the variable already has a value, `defvar' does not override
7263the existing value. Second, `defvar' has a documentation string.
7264
7265(Another special form, `defcustom', is designed for variables that
7266people customize. It has more features than `defvar'. (*Note Setting
7267Variables with `defcustom': defcustom.)
7268
7269* Menu:
7270
7271* See variable current value::
7272* defvar and asterisk::
7273
7274
7275File: eintr, Node: See variable current value, Next: defvar and asterisk, Prev: defvar, Up: defvar
7276
7277Seeing the Current Value of a Variable
7278--------------------------------------
7279
7280You can see the current value of a variable, any variable, by using the
7281`describe-variable' function, which is usually invoked by typing `C-h
7282v'. If you type `C-h v' and then `kill-ring' (followed by <RET>) when
7283prompted, you will see what is in your current kill ring--this may be
7284quite a lot! Conversely, if you have been doing nothing this Emacs
7285session except read this document, you may have nothing in it. Also,
7286you will see the documentation for `kill-ring':
7287
7288 Documentation:
7289 List of killed text sequences.
7290 Since the kill ring is supposed to interact nicely with cut-and-paste
7291 facilities offered by window systems, use of this variable should
7292 interact nicely with `interprogram-cut-function' and
7293 `interprogram-paste-function'. The functions `kill-new',
7294 `kill-append', and `current-kill' are supposed to implement this
7295 interaction; you may want to use them instead of manipulating the kill
7296 ring directly.
7297
7298The kill ring is defined by a `defvar' in the following way:
7299
7300 (defvar kill-ring nil
7301 "List of killed text sequences.
7302 ...")
7303
7304In this variable definition, the variable is given an initial value of
7305`nil', which makes sense, since if you have saved nothing, you want
7306nothing back if you give a `yank' command. The documentation string is
7307written just like the documentation string of a `defun'. As with the
7308documentation string of the `defun', the first line of the
7309documentation should be a complete sentence, since some commands, like
7310`apropos', print only the first line of documentation. Succeeding
7311lines should not be indented; otherwise they look odd when you use `C-h
7312v' (`describe-variable').
7313