emacs-lisp-intro.texi 778 KB
Newer Older
Glenn Morris's avatar
Glenn Morris committed
1 2
\input texinfo                                      @c -*-texinfo-*-
@comment %**start of header
3
@setfilename ../../info/eintr
Glenn Morris's avatar
Glenn Morris committed
4 5 6 7 8 9 10 11 12 13 14
@c setfilename emacs-lisp-intro.info
@c sethtmlfilename emacs-lisp-intro.html
@settitle Programming in Emacs Lisp
@syncodeindex vr cp
@syncodeindex fn cp
@finalout

@c ---------
@c <<<< For hard copy printing, this file is now
@c      set for smallbook, which works for all sizes
@c      of paper, and with Postscript figures >>>>
15 16
@set smallbook
@ifset smallbook
Glenn Morris's avatar
Glenn Morris committed
17 18
@smallbook
@clear  largebook
19
@end ifset
Glenn Morris's avatar
Glenn Morris committed
20 21 22 23 24 25 26
@set print-postscript-figures
@c set largebook
@c clear print-postscript-figures
@c ---------

@comment %**end of header

27
@c per rms and peterb, use 10pt fonts for the main text, mostly to
Juanma Barranquero's avatar
Juanma Barranquero committed
28
@c save on paper cost.
29 30 31 32
@c Do this inside @tex for now, so current makeinfo does not complain.
@tex
@ifset smallbook
@fonttextsize 10
33

34 35 36 37
@end ifset
\global\hbadness=6666 % don't worry about not-too-underfull boxes
@end tex

38 39
@set edition-number 3.10
@set update-date 28 October 2009
40

Glenn Morris's avatar
Glenn Morris committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
@ignore
 ## Summary of shell commands to create various output formats:

    pushd /usr/local/src/emacs/lispintro/
    ## pushd /u/intro/

    ## Info output
    makeinfo --paragraph-indent=0 --verbose emacs-lisp-intro.texi

      ## ;; (progn (when (bufferp (get-buffer "*info*")) (kill-buffer "*info*")) (info "/usr/local/src/emacs/info/eintr"))

    ## DVI output
    texi2dvi emacs-lisp-intro.texi

      ## xdvi -margins 24pt -topmargin 4pt -offsets 24pt -geometry 760x1140 -s 5 -useTeXpages -mousemode 1 emacs-lisp-intro.dvi &

    ## HTML output
    makeinfo --html --no-split --verbose emacs-lisp-intro.texi

      ## galeon emacs-lisp-intro.html

    ## Plain text output
    makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
    --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi

    popd

# as user `root'
# insert thumbdrive
  mtusb       #   mount -v -t ext3 /dev/sda /mnt
  cp -v /u/intro/emacs-lisp-intro.texi /mnt/backup/intro/emacs-lisp-intro.texi
  umtusb      #   umount -v /mnt
# remove thumbdrive

    ## Other shell commands

    pushd /usr/local/src/emacs/lispintro/
    ## pushd /u/intro/

    ## PDF
    texi2dvi --pdf emacs-lisp-intro.texi
       # xpdf emacs-lisp-intro.pdf &

    ## DocBook                    -- note file extension
    makeinfo --docbook --no-split --paragraph-indent=0 \
    --verbose --output=emacs-lisp-intro.docbook emacs-lisp-intro.texi

    ## XML with a Texinfo DTD     -- note file extension
    makeinfo --xml --no-split --paragraph-indent=0 \
    --verbose --output=emacs-lisp-intro.texinfoxml emacs-lisp-intro.texi

    ## PostScript (needs DVI)
        #     gv emacs-lisp-intro.ps &
        # Create DVI if we lack it
        # texi2dvi emacs-lisp-intro.texi
    dvips emacs-lisp-intro.dvi -o emacs-lisp-intro.ps

    ## RTF (needs HTML)
        # Use OpenOffice to view RTF
        # Create HTML if we lack it
        # makeinfo --no-split --html emacs-lisp-intro.texi
    /usr/local/src/html2rtf.pl emacs-lisp-intro.html

    ## LaTeX (needs RTF)
    /usr/bin/rtf2latex emacs-lisp-intro.rtf

    popd

@end ignore

@c ================ Included Figures ================

@c Set  print-postscript-figures  if you print PostScript figures.
@c If you clear this, the ten figures will be printed as ASCII diagrams.
@c (This is not relevant to Info, since Info only handles ASCII.)
@c Your site may require editing changes to print PostScript; in this
@c case, search for `print-postscript-figures' and make appropriate changes.

@c ================ How to Create an Info file ================

@c If you have `makeinfo' installed, run the following command

@c     makeinfo emacs-lisp-intro.texi

@c or, if you want a single, large Info file, and no paragraph indents:
@c     makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi

@c After creating the Info file, edit your Info `dir' file, if the
@c `dircategory' section below does not enable your system to
@c install the manual automatically.
@c (The `dir' file is often in the `/usr/local/share/info/' directory.)

@c ================ How to Create an HTML file ================

@c To convert to HTML format
@c     makeinfo --html --no-split --verbose emacs-lisp-intro.texi

@c ================ How to Print a Book in Various Sizes ================

@c This book can be printed in any of three different sizes.
@c In the above header, set @-commands appropriately.

@c     7 by 9.25 inches:
@c              @smallbook
@c              @clear largebook

@c     8.5 by 11 inches:
@c              @c smallbook
@c              @set largebook

@c     European A4 size paper:
@c              @c smallbook
@c              @afourpaper
@c              @set largebook

@c ================ How to Typeset and Print ================

@c If you do not include PostScript figures, run either of the
@c following command sequences, or similar commands suited to your
@c system:

@c     texi2dvi emacs-lisp-intro.texi
@c     lpr -d emacs-lisp-intro.dvi

@c or else:

@c     tex emacs-lisp-intro.texi
@c     texindex emacs-lisp-intro.??
@c     tex emacs-lisp-intro.texi
@c     lpr -d emacs-lisp-intro.dvi

@c If you include the PostScript figures, and you have old software,
@c you may need to convert the .dvi file to a .ps file before
@c printing.  Run either of the following command sequences, or one
@c similar:
@c
@c     dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
@c
@c or else:
@c
@c     postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
@c

@c (Note: if you edit the book so as to change the length of the
@c table of contents, you may have to change the value of `pageno' below.)

@c ================ End of Formatting Sections ================

@c For next or subsequent edition:
@c   create function using with-output-to-temp-buffer
@c   create a major mode, with keymaps
@c   run an asynchronous process, like grep or diff

@c For 8.5 by 11 inch format: do not use such a small amount of
@c whitespace between paragraphs as smallbook format
@ifset largebook
@tex
\global\parskip 6pt plus 1pt
@end tex
@end ifset

@c For all sized formats:  print within-book cross
@c reference with ``...''  rather than [...]

@c This works with the texinfo.tex file, version 2003-05-04.08,
@c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.

@tex
\if \xrefprintnodename
 \global\def\xrefprintnodename#1{\unskip, ``#1''}
 \else
 \global\def\xrefprintnodename#1{ ``#1''}
\fi
% \global\def\xrefprintnodename#1{, ``#1''}
@end tex

@c ----------------------------------------------------

@dircategory Emacs
@direntry
* Emacs Lisp Intro: (eintr).
                          A simple introduction to Emacs Lisp programming.
@end direntry

@copying
This is an @cite{Introduction to Programming in Emacs Lisp}, for
people who are not programmers.
@sp 1
Edition @value{edition-number}, @value{update-date}
@sp 1
Copyright @copyright{} 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001,
232 233
   2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
   Free Software Foundation, Inc.
Glenn Morris's avatar
Glenn Morris committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
@sp 1

@iftex
Published by the:@*

GNU Press,                      @hfill  @uref{http://www.gnupress.org}@*
a division of the               @hfill General: @email{press@@gnu.org}@*
Free Software Foundation, Inc.  @hfill Orders:@w{ }  @email{sales@@gnu.org}@*
51 Franklin Street, Fifth Floor @hfill Tel: +1 (617) 542-5942@*
Boston, MA 02110-1301 USA       @hfill Fax: +1 (617) 542-2652@*
@end iftex

@ifnottex
Published by the:

@example
GNU Press,                          Website: http://www.gnupress.org
a division of the                   General: press@@gnu.org
Free Software Foundation, Inc.      Orders:  sales@@gnu.org
51 Franklin Street, Fifth Floor     Tel: +1 (617) 542-5942
Boston, MA 02110-1301 USA           Fax: +1 (617) 542-2652
@end example
@end ifnottex

@sp 1
@c Printed copies are available for $30 each.@*
ISBN 1-882114-43-4

Permission is granted to copy, distribute and/or modify this document
263
under the terms of the GNU Free Documentation License, Version 1.3 or
Glenn Morris's avatar
Glenn Morris committed
264 265 266 267 268 269
any later version published by the Free Software Foundation; there
being no Invariant Section, with the Front-Cover Texts being ``A GNU
Manual'', and with the Back-Cover Texts as in (a) below.  A copy of
the license is included in the section entitled ``GNU Free
Documentation License''.

270 271 272
(a) The FSF's Back-Cover Text is: ``You have the freedom to
copy and modify this GNU manual.  Buying copies from the FSF
supports it in developing GNU and promoting software freedom.''
Glenn Morris's avatar
Glenn Morris committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
@end copying

@c half title; two lines here, so do not use `shorttitlepage'
@tex
{\begingroup%
    \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
        \endgroup}%
{\begingroup\hbox{}\vskip 0.25in \chaprm%
        \centerline{Programming in Emacs Lisp}%
        \endgroup\page\hbox{}\page}
@end tex

@titlepage
@sp 6
@center @titlefont{An Introduction to}
@sp 2
@center @titlefont{Programming in Emacs Lisp}
@sp 2
@center Revised Third Edition
@sp 4
@center by Robert J. Chassell

@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

@iftex
@headings off
@evenheading @thispage @| @| @thischapter
@oddheading @thissection @| @| @thispage
@end iftex

@ifnothtml
@c     Keep T.O.C. short by tightening up for largebook
@ifset largebook
@tex
\global\parskip 2pt plus 1pt
\global\advance\baselineskip by -1pt
@end tex
@end ifset
@end ifnothtml

@shortcontents
@contents

@ifnottex
@node Top, Preface, (dir), (dir)
@top An Introduction to Programming in Emacs Lisp

@insertcopying

This master menu first lists each chapter and index; then it lists
every node in every chapter.
@end ifnottex

@c >>>> Set pageno appropriately <<<<

@c The first page of the Preface is a roman numeral; it is the first
@c right handed page after the Table of Contents; hence the following
@c setting must be for an odd negative number.

335 336 337
@c iftex
@c global@pageno = -11
@c end iftex
Glenn Morris's avatar
Glenn Morris committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

@menu
* Preface::                     What to look for.
* List Processing::             What is Lisp?
* Practicing Evaluation::       Running several programs.
* Writing Defuns::              How to write function definitions.
* Buffer Walk Through::         Exploring a few buffer-related functions.
* More Complex::                A few, even more complex functions.
* Narrowing & Widening::        Restricting your and Emacs attention to
                                    a region.
* car cdr & cons::              Fundamental functions in Lisp.
* Cutting & Storing Text::      Removing text and saving it.
* List Implementation::         How lists are implemented in the computer.
* Yanking::                     Pasting stored text.
* Loops & Recursion::           How to repeat a process.
* Regexp Search::               Regular expression searches.
* Counting Words::              A review of repetition and regexps.
* Words in a defun::            Counting words in a @code{defun}.
* Readying a Graph::            A prototype graph printing function.
* Emacs Initialization::        How to write a @file{.emacs} file.
* Debugging::                   How to run the Emacs Lisp debuggers.
* Conclusion::                  Now you have the basics.
* the-the::                     An appendix: how to find reduplicated words.
* Kill Ring::                   An appendix: how the kill ring works.
* Full Graph::                  How to create a graph with labelled axes.
* Free Software and Free Manuals::
* GNU Free Documentation License::
* Index::
* About the Author::

@detailmenu
 --- The Detailed Node Listing ---

Preface

* Why::                         Why learn Emacs Lisp?
* On Reading this Text::        Read, gain familiarity, pick up habits....
* Who You Are::                 For whom this is written.
* Lisp History::
* Note for Novices::            You can read this as a novice.
* Thank You::

List Processing

* Lisp Lists::                  What are lists?
* Run a Program::               Any list in Lisp is a program ready to run.
* Making Errors::               Generating an error message.
* Names & Definitions::         Names of symbols and function definitions.
* Lisp Interpreter::            What the Lisp interpreter does.
* Evaluation::                  Running a program.
* Variables::                   Returning a value from a variable.
* Arguments::                   Passing information to a function.
* set & setq::                  Setting the value of a variable.
* Summary::                     The major points.
* Error Message Exercises::

Lisp Lists

* Numbers Lists::               List have numbers, other lists, in them.
* Lisp Atoms::                  Elemental entities.
* Whitespace in Lists::         Formatting lists to be readable.
* Typing Lists::                How GNU Emacs helps you type lists.

The Lisp Interpreter

* Complications::               Variables, Special forms, Lists within.
* Byte Compiling::              Specially processing code for speed.

Evaluation

* How the Interpreter Acts::    Returns and Side Effects...
* Evaluating Inner Lists::      Lists within lists...

Variables

* fill-column Example::
* Void Function::               The error message for a symbol
                                  without a function.
* Void Variable::               The error message for a symbol without a value.

Arguments

* Data types::                  Types of data passed to a function.
* Args as Variable or List::    An argument can be the value
                                  of a variable or list.
* Variable Number of Arguments::  Some functions may take a
                                  variable number of arguments.
* Wrong Type of Argument::      Passing an argument of the wrong type
                                  to a function.
* message::                     A useful function for sending messages.

Setting the Value of a Variable

* Using set::                  Setting values.
* Using setq::                 Setting a quoted value.
* Counting::                   Using @code{setq} to count.

Practicing Evaluation

* How to Evaluate::            Typing editing commands or @kbd{C-x C-e}
                                 causes evaluation.
* Buffer Names::               Buffers and files are different.
* Getting Buffers::            Getting a buffer itself, not merely its name.
* Switching Buffers::          How to change to another buffer.
* Buffer Size & Locations::    Where point is located and the size of
                               the buffer.
* Evaluation Exercise::

How To Write Function Definitions

* Primitive Functions::
* defun::                        The @code{defun} special form.
* Install::                      Install a function definition.
* Interactive::                  Making a function interactive.
* Interactive Options::          Different options for @code{interactive}.
* Permanent Installation::       Installing code permanently.
* let::                          Creating and initializing local variables.
* if::                           What if?
* else::                         If--then--else expressions.
* Truth & Falsehood::            What Lisp considers false and true.
* save-excursion::               Keeping track of point, mark, and buffer.
* Review::
* defun Exercises::

Install a Function Definition

* Effect of installation::
* Change a defun::              How to change a function definition.

Make a Function Interactive

* Interactive multiply-by-seven::  An overview.
* multiply-by-seven in detail::    The interactive version.

@code{let}

* Prevent confusion::
* Parts of let Expression::
* Sample let Expression::
* Uninitialized let Variables::

The @code{if} Special Form

* if in more detail::
* type-of-animal in detail::    An example of an @code{if} expression.

Truth and Falsehood in Emacs Lisp

* nil explained::               @code{nil} has two meanings.

@code{save-excursion}

* Point and mark::              A review of various locations.
* Template for save-excursion::

A Few Buffer--Related Functions

* Finding More::                How to find more information.
* simplified-beginning-of-buffer::  Shows @code{goto-char},
                                @code{point-min}, and @code{push-mark}.
* mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
* append-to-buffer::            Uses @code{save-excursion} and
                                @code{insert-buffer-substring}.
* Buffer Related Review::       Review.
* Buffer Exercises::

The Definition of @code{mark-whole-buffer}

* mark-whole-buffer overview::
* Body of mark-whole-buffer::   Only three lines of code.

The Definition of @code{append-to-buffer}

* append-to-buffer overview::
* append interactive::          A two part interactive expression.
* append-to-buffer body::       Incorporates a @code{let} expression.
* append save-excursion::       How the @code{save-excursion} works.

A Few More Complex Functions

* copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
* insert-buffer::               Read-only, and with @code{or}.
* beginning-of-buffer::         Shows @code{goto-char},
                                @code{point-min}, and @code{push-mark}.
* Second Buffer Related Review::
* optional Exercise::

The Definition of @code{insert-buffer}

* insert-buffer code::
* insert-buffer interactive::   When you can read, but not write.
* insert-buffer body::          The body has an @code{or} and a @code{let}.
* if & or::                     Using an @code{if} instead of an @code{or}.
* Insert or::                   How the @code{or} expression works.
* Insert let::                  Two @code{save-excursion} expressions.
* New insert-buffer::

The Interactive Expression in @code{insert-buffer}

* Read-only buffer::            When a buffer cannot be modified.
* b for interactive::           An existing buffer or else its name.

Complete Definition of @code{beginning-of-buffer}

* Optional Arguments::
* beginning-of-buffer opt arg::  Example with optional argument.
* beginning-of-buffer complete::

@code{beginning-of-buffer} with an Argument

* Disentangle beginning-of-buffer::
* Large buffer case::
* Small buffer case::

Narrowing and Widening

* Narrowing advantages::        The advantages of narrowing
* save-restriction::            The @code{save-restriction} special form.
* what-line::                   The number of the line that point is on.
* narrow Exercise::

@code{car}, @code{cdr}, @code{cons}: Fundamental Functions

* Strange Names::               An historical aside: why the strange names?
* car & cdr::                   Functions for extracting part of a list.
* cons::                        Constructing a list.
* nthcdr::                      Calling @code{cdr} repeatedly.
* nth::
* setcar::                      Changing the first element of a list.
* setcdr::                      Changing the rest of a list.
* cons Exercise::

@code{cons}

* Build a list::
* length::                      How to find the length of a list.

Cutting and Storing Text

* Storing Text::                Text is stored in a list.
* zap-to-char::                 Cutting out text up to a character.
* kill-region::                 Cutting text out of a region.
* copy-region-as-kill::         A definition for copying text.
* Digression into C::           Minor note on C programming language macros.
* defvar::                      How to give a variable an initial value.
* cons & search-fwd Review::
* search Exercises::

@code{zap-to-char}

* Complete zap-to-char::        The complete implementation.
* zap-to-char interactive::     A three part interactive expression.
* zap-to-char body::            A short overview.
* search-forward::              How to search for a string.
* progn::                       The @code{progn} special form.
* Summing up zap-to-char::      Using @code{point} and @code{search-forward}.

@code{kill-region}

* Complete kill-region::        The function definition.
* condition-case::              Dealing with a problem.
* Lisp macro::

@code{copy-region-as-kill}

* Complete copy-region-as-kill::  The complete function definition.
* copy-region-as-kill body::      The body of @code{copy-region-as-kill}.

The Body of @code{copy-region-as-kill}

* last-command & this-command::
* kill-append function::
* kill-new function::

Initializing a Variable with @code{defvar}

* See variable current value::
* defvar and asterisk::

How Lists are Implemented

* Lists diagrammed::
* Symbols as Chest::            Exploring a powerful metaphor.
* List Exercise::

Yanking Text Back

* Kill Ring Overview::
* kill-ring-yank-pointer::      The kill ring is a list.
* yank nthcdr Exercises::       The @code{kill-ring-yank-pointer} variable.

Loops and Recursion

* while::                       Causing a stretch of code to repeat.
* dolist dotimes::
* Recursion::                   Causing a function to call itself.
* Looping exercise::

@code{while}

* Looping with while::          Repeat so long as test returns true.
* Loop Example::                A @code{while} loop that uses a list.
* print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
* Incrementing Loop::           A loop with an incrementing counter.
* Incrementing Loop Details::
* Decrementing Loop::           A loop with a decrementing counter.

Details of an Incrementing Loop

* Incrementing Example::        Counting pebbles in a triangle.
* Inc Example parts::           The parts of the function definition.
* Inc Example altogether::      Putting the function definition together.

Loop with a Decrementing Counter

* Decrementing Example::        More pebbles on the beach.
* Dec Example parts::           The parts of the function definition.
* Dec Example altogether::      Putting the function definition together.

Save your time: @code{dolist} and @code{dotimes}

* dolist::
* dotimes::

Recursion

* Building Robots::             Same model, different serial number ...
* Recursive Definition Parts::  Walk until you stop ...
* Recursion with list::         Using a list as the test whether to recurse.
* Recursive triangle function::
* Recursion with cond::
* Recursive Patterns::          Often used templates.
* No Deferment::                Don't store up work ...
* No deferment solution::

Recursion in Place of a Counter

* Recursive Example arg of 1 or 2::
* Recursive Example arg of 3 or 4::

Recursive Patterns

* Every::
* Accumulate::
* Keep::

Regular Expression Searches

* sentence-end::                The regular expression for @code{sentence-end}.
* re-search-forward::           Very similar to @code{search-forward}.
* forward-sentence::            A straightforward example of regexp search.
* forward-paragraph::           A somewhat complex example.
* etags::                       How to create your own @file{TAGS} table.
* Regexp Review::
* re-search Exercises::

@code{forward-sentence}

* Complete forward-sentence::
* fwd-sentence while loops::    Two @code{while} loops.
* fwd-sentence re-search::      A regular expression search.

@code{forward-paragraph}: a Goldmine of Functions

* forward-paragraph in brief::  Key parts of the function definition.
* fwd-para let::                The @code{let*} expression.
* fwd-para while::              The forward motion @code{while} loop.

Counting: Repetition and Regexps

* Why Count Words::
* count-words-region::          Use a regexp, but find a problem.
* recursive-count-words::       Start with case of no words in region.
* Counting Exercise::

The @code{count-words-region} Function

* Design count-words-region::   The definition using a @code{while} loop.
* Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.

Counting Words in a @code{defun}

* Divide and Conquer::
* Words and Symbols::           What to count?
* Syntax::                      What constitutes a word or symbol?
* count-words-in-defun::        Very like @code{count-words}.
* Several defuns::              Counting several defuns in a file.
* Find a File::                 Do you want to look at a file?
* lengths-list-file::           A list of the lengths of many definitions.
* Several files::               Counting in definitions in different files.
* Several files recursively::   Recursively counting in different files.
* Prepare the data::            Prepare the data for display in a graph.

Count Words in @code{defuns} in Different Files

* lengths-list-many-files::     Return a list of the lengths of defuns.
* append::                      Attach one list to another.

Prepare the Data for Display in a Graph

* Data for Display in Detail::
* Sorting::                     Sorting lists.
* Files List::                  Making a list of files.
* Counting function definitions::

Readying a Graph

* Columns of a graph::
* graph-body-print::            How to print the body of a graph.
* recursive-graph-body-print::
* Printed Axes::
* Line Graph Exercise::

Your @file{.emacs} File

* Default Configuration::
* Site-wide Init::              You can write site-wide init files.
* defcustom::                   Emacs will write code for you.
* Beginning a .emacs File::     How to write a @code{.emacs file}.
* Text and Auto-fill::          Automatically wrap lines.
* Mail Aliases::                Use abbreviations for email addresses.
* Indent Tabs Mode::            Don't use tabs with @TeX{}
* Keybindings::                 Create some personal keybindings.
* Keymaps::                     More about key binding.
* Loading Files::               Load (i.e., evaluate) files automatically.
* Autoload::                    Make functions available.
* Simple Extension::            Define a function; bind it to a key.
* X11 Colors::                  Colors in X.
* Miscellaneous::
* Mode Line::                   How to customize your mode line.

Debugging

* debug::                       How to use the built-in debugger.
* debug-on-entry::              Start debugging when you call a function.
* debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
* edebug::                      How to use Edebug, a source level debugger.
* Debugging Exercises::

Handling the Kill Ring

* What the Kill Ring Does::
* current-kill::
* yank::                        Paste a copy of a clipped element.
* yank-pop::                    Insert element pointed to.
* ring file::

The @code{current-kill} Function

787
* Code for current-kill::
Glenn Morris's avatar
Glenn Morris committed
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
* Understanding current-kill::

@code{current-kill} in Outline

* Body of current-kill::
* Digression concerning error::  How to mislead humans, but not computers.
* Determining the Element::

A Graph with Labelled Axes

* Labelled Example::
* print-graph Varlist::         @code{let} expression in @code{print-graph}.
* print-Y-axis::                Print a label for the vertical axis.
* print-X-axis::                Print a horizontal label.
* Print Whole Graph::           The function to print a complete graph.

The @code{print-Y-axis} Function

* print-Y-axis in Detail::
* Height of label::             What height for the Y axis?
* Compute a Remainder::         How to compute the remainder of a division.
* Y Axis Element::              Construct a line for the Y axis.
* Y-axis-column::               Generate a list of Y axis labels.
* print-Y-axis Penultimate::    A not quite final version.

The @code{print-X-axis} Function

* Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
* X Axis Tic Marks::            Create tic marks for the horizontal axis.

Printing the Whole Graph

* The final version::           A few changes.
* Test print-graph::            Run a short test.
* Graphing words in defuns::    Executing the final code.
* lambda::                      How to write an anonymous function.
* mapcar::                      Apply a function to elements of a list.
* Another Bug::                 Yet another bug @dots{} most insidious.
* Final printed graph::         The graph itself!

@end detailmenu
@end menu

@node Preface, List Processing, Top, Top
@comment  node-name,  next,  previous,  up
@unnumbered Preface

Most of the GNU Emacs integrated environment is written in the programming
language called Emacs Lisp.  The code written in this programming
language is the software---the sets of instructions---that tell the
computer what to do when you give it commands.  Emacs is designed so
that you can write new code in Emacs Lisp and easily install it as an
extension to the editor.

(GNU Emacs is sometimes called an ``extensible editor'', but it does
much more than provide editing capabilities.  It is better to refer to
Emacs as an ``extensible computing environment''.  However, that
phrase is quite a mouthful.  It is easier to refer to Emacs simply as
an editor.  Moreover, everything you do in Emacs---find the Mayan date
and phases of the moon, simplify polynomials, debug code, manage
files, read letters, write books---all these activities are kinds of
editing in the most general sense of the word.)

@menu
* Why::                         Why learn Emacs Lisp?
* On Reading this Text::        Read, gain familiarity, pick up habits....
* Who You Are::                 For whom this is written.
* Lisp History::
* Note for Novices::            You can read this as a novice.
* Thank You::
@end menu

@node Why, On Reading this Text, Preface, Preface
@ifnottex
@unnumberedsec Why Study Emacs Lisp?
@end ifnottex

Although Emacs Lisp is usually thought of in association only with Emacs,
it is a full computer programming language.  You can use Emacs Lisp as
you would any other programming language.

Perhaps you want to understand programming; perhaps you want to extend
Emacs; or perhaps you want to become a programmer.  This introduction to
Emacs Lisp is designed to get you started: to guide you in learning the
fundamentals of programming, and more importantly, to show you how you
can teach yourself to go further.

@node On Reading this Text, Who You Are, Why, Preface
@comment  node-name,  next,  previous,  up
@unnumberedsec On Reading this Text

All through this document, you will see little sample programs you can
run inside of Emacs.  If you read this document in Info inside of GNU
Emacs, you can run the programs as they appear.  (This is easy to do and
is explained when the examples are presented.)  Alternatively, you can
read this introduction as a printed book while sitting beside a computer
running Emacs.  (This is what I like to do; I like printed books.)  If
you don't have a running Emacs beside you, you can still read this book,
but in this case, it is best to treat it as a novel or as a travel guide
to a country not yet visited: interesting, but not the same as being
there.

Much of this introduction is dedicated to walk-throughs or guided tours
of code used in GNU Emacs.  These tours are designed for two purposes:
first, to give you familiarity with real, working code (code you use
every day); and, second, to give you familiarity with the way Emacs
works.  It is interesting to see how a working environment is
implemented.
Also, I
hope that you will pick up the habit of browsing through source code.
You can learn from it and mine it for ideas.  Having GNU Emacs is like
having a dragon's cave of treasures.

In addition to learning about Emacs as an editor and Emacs Lisp as a
programming language, the examples and guided tours will give you an
opportunity to get acquainted with Emacs as a Lisp programming
environment.  GNU Emacs supports programming and provides tools that
you will want to become comfortable using, such as @kbd{M-.} (the key
which invokes the @code{find-tag} command).  You will also learn about
buffers and other objects that are part of the environment.
Learning about these features of Emacs is like learning new routes
around your home town.

@ignore
In addition, I have written several programs as extended examples.
Although these are examples, the programs are real.  I use them.
Other people use them.  You may use them.  Beyond the fragments of
programs used for illustrations, there is very little in here that is
`just for teaching purposes'; what you see is used.  This is a great
advantage of Emacs Lisp: it is easy to learn to use it for work.
@end ignore

Finally, I hope to convey some of the skills for using Emacs to
learn aspects of programming that you don't know.  You can often use
Emacs to help you understand what puzzles you or to find out how to do
something new.  This self-reliance is not only a pleasure, but an
advantage.

@node Who You Are, Lisp History, On Reading this Text, Preface
@comment  node-name,  next,  previous,  up
@unnumberedsec For Whom This is Written

This text is written as an elementary introduction for people who are
not programmers.  If you are a programmer, you may not be satisfied with
this primer.  The reason is that you may have become expert at reading
reference manuals and be put off by the way this text is organized.

An expert programmer who reviewed this text said to me:

@quotation
@i{I prefer to learn from reference manuals.  I ``dive into'' each
paragraph, and ``come up for air'' between paragraphs.}

@i{When I get to the end of a paragraph, I assume that that subject is
done, finished, that I know everything I need (with the
possible exception of the case when the next paragraph starts talking
about it in more detail).  I expect that a well written reference manual
will not have a lot of redundancy, and that it will have excellent
pointers to the (one) place where the information I want is.}
@end quotation

This introduction is not written for this person!

Firstly, I try to say everything at least three times: first, to
introduce it; second, to show it in context; and third, to show it in a
different context, or to review it.

Secondly, I hardly ever put all the information about a subject in one
place, much less in one paragraph.  To my way of thinking, that imposes
too heavy a burden on the reader.  Instead I try to explain only what
you need to know at the time.  (Sometimes I include a little extra
information so you won't be surprised later when the additional
information is formally introduced.)

When you read this text, you are not expected to learn everything the
first time.  Frequently, you need only make, as it were, a `nodding
acquaintance' with some of the items mentioned.  My hope is that I have
structured the text and given you enough hints that you will be alert to
what is important, and concentrate on it.

You will need to ``dive into'' some paragraphs; there is no other way
to read them.  But I have tried to keep down the number of such
paragraphs.  This book is intended as an approachable hill, rather than
as a daunting mountain.

This introduction to @cite{Programming in Emacs Lisp} has a companion
document,
@iftex
@cite{The GNU Emacs Lisp Reference Manual}.
@end iftex
@ifnottex
@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
Emacs Lisp Reference Manual}.
@end ifnottex
The reference manual has more detail than this introduction.  In the
reference manual, all the information about one topic is concentrated
in one place.  You should turn to it if you are like the programmer
quoted above.  And, of course, after you have read this
@cite{Introduction}, you will find the @cite{Reference Manual} useful
when you are writing your own programs.

@node Lisp History, Note for Novices, Who You Are, Preface
@unnumberedsec Lisp History
@cindex Lisp history

Lisp was first developed in the late 1950s at the Massachusetts
Institute of Technology for research in artificial intelligence.  The
great power of the Lisp language makes it superior for other purposes as
well, such as writing editor commands and integrated environments.

@cindex Maclisp
@cindex Common Lisp
GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
in the 1960s.  It is somewhat inspired by Common Lisp, which became a
standard in the 1980s.  However, Emacs Lisp is much simpler than Common
Lisp.  (The standard Emacs distribution contains an optional extensions
file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)

@node Note for Novices, Thank You, Lisp History, Preface
@comment  node-name,  next,  previous,  up
@unnumberedsec A Note for Novices

If you don't know GNU Emacs, you can still read this document
profitably.  However, I recommend you learn Emacs, if only to learn to
move around your computer screen.  You can teach yourself how to use
Emacs with the on-line tutorial.  To use it, type @kbd{C-h t}.  (This
means you press and release the @key{CTRL} key and the @kbd{h} at the
same time, and then press and release @kbd{t}.)

Also, I often refer to one of Emacs' standard commands by listing the
keys which you press to invoke the command and then giving the name of
the command in parentheses, like this: @kbd{M-C-\}
(@code{indent-region}).  What this means is that the
@code{indent-region} command is customarily invoked by typing
@kbd{M-C-\}.  (You can, if you wish, change the keys that are typed to
invoke the command; this is called @dfn{rebinding}.  @xref{Keymaps, ,
Keymaps}.)  The abbreviation @kbd{M-C-\} means that you type your
@key{META} key, @key{CTRL} key and @key{\} key all at the same time.
(On many modern keyboards the @key{META} key is labelled
@key{ALT}.)
Sometimes a combination like this is called a keychord, since it is
similar to the way you play a chord on a piano.  If your keyboard does
not have a @key{META} key, the @key{ESC} key prefix is used in place
of it.  In this case, @kbd{M-C-\} means that you press and release your
@key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
the same time.  But usually @kbd{M-C-\} means press the @key{CTRL} key
along with the key that is labelled @key{ALT} and, at the same time,
press the @key{\} key.

In addition to typing a lone keychord, you can prefix what you type
with @kbd{C-u}, which is called the `universal argument'.  The
@kbd{C-u} keychord passes an argument to the subsequent command.
Thus, to indent a region of plain text by 6 spaces, mark the region,
and then type @w{@kbd{C-u 6 M-C-\}}.  (If you do not specify a number,
Emacs either passes the number 4 to the command or otherwise runs the
command differently than it would otherwise.)  @xref{Arguments, ,
Numeric Arguments, emacs, The GNU Emacs Manual}.

If you are reading this in Info using GNU Emacs, you can read through
this whole document just by pressing the space bar, @key{SPC}.
(To learn about Info, type @kbd{C-h i} and then select Info.)

A note on terminology:  when I use the word Lisp alone, I often am
referring to the various dialects of Lisp in general, but when I speak
of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.

@node Thank You,  , Note for Novices, Preface
@comment  node-name,  next,  previous,  up
@unnumberedsec Thank You

My thanks to all who helped me with this book.  My especial thanks to
@r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
Stallman}, and @w{Melissa Weisshaus}.  My thanks also go to both
@w{Philip Johnson} and @w{David Stampe} for their patient
encouragement.  My mistakes are my own.

@flushright
Robert J. Chassell
1067
@email{bob@@gnu.org}
Glenn Morris's avatar
Glenn Morris committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
@end flushright

@c ================ Beginning of main text ================

@c Start main text on right-hand (verso) page

@tex
\par\vfill\supereject
\headings off
\ifodd\pageno
    \par\vfill\supereject
\else
    \par\vfill\supereject
    \page\hbox{}\page
    \par\vfill\supereject
\fi
@end tex

@iftex
@headings off
@evenheading @thispage @| @| @thischapter
@oddheading @thissection @| @| @thispage
@global@pageno = 1
@end iftex

@node List Processing, Practicing Evaluation, Preface, Top
@comment  node-name,  next,  previous,  up
@chapter List Processing

To the untutored eye, Lisp is a strange programming language.  In Lisp
code there are parentheses everywhere.  Some people even claim that
the name stands for `Lots of Isolated Silly Parentheses'.  But the
claim is unwarranted.  Lisp stands for LISt Processing, and the
programming language handles @emph{lists} (and lists of lists) by
putting them between parentheses.  The parentheses mark the boundaries
of the list.  Sometimes a list is preceded by a single apostrophe or
quotation mark, @samp{'}@footnote{The single apostrophe or quotation
mark is an abbreviation for the function @code{quote}; you need not
think about functions now; functions are defined in @ref{Making
Errors, , Generate an Error Message}.}  Lists are the basis of Lisp.

@menu
* Lisp Lists::                  What are lists?
* Run a Program::               Any list in Lisp is a program ready to run.
* Making Errors::               Generating an error message.
* Names & Definitions::         Names of symbols and function definitions.
* Lisp Interpreter::            What the Lisp interpreter does.
* Evaluation::                  Running a program.
* Variables::                   Returning a value from a variable.
* Arguments::                   Passing information to a function.
* set & setq::                  Setting the value of a variable.
* Summary::                     The major points.
* Error Message Exercises::
@end menu

@node Lisp Lists, Run a Program, List Processing, List Processing
@comment  node-name,  next,  previous,  up
@section Lisp Lists
@cindex Lisp Lists

In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
This list is preceded by a single apostrophe.  It could just as well be
written as follows, which looks more like the kind of list you are likely
to be familiar with:

@smallexample
@group
'(rose
  violet
  daisy
  buttercup)
@end group
@end smallexample

@noindent
The elements of this list are the names of the four different flowers,
separated from each other by whitespace and surrounded by parentheses,
like flowers in a field with a stone wall around them.
@cindex Flowers in a field

@menu
* Numbers Lists::               List have numbers, other lists, in them.
* Lisp Atoms::                  Elemental entities.
* Whitespace in Lists::         Formatting lists to be readable.
* Typing Lists::                How GNU Emacs helps you type lists.
@end menu

@node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
@ifnottex
@unnumberedsubsec Numbers, Lists inside of Lists
@end ifnottex

Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
separated by whitespace.

In Lisp, both data and programs are represented the same way; that is,
they are both lists of words, numbers, or other lists, separated by
whitespace and surrounded by parentheses.  (Since a program looks like
data, one program may easily serve as data for another; this is a very
powerful feature of Lisp.)  (Incidentally, these two parenthetical
remarks are @emph{not} Lisp lists, because they contain @samp{;} and
@samp{.} as punctuation marks.)

@need 1200
Here is another list, this time with a list inside of it:

@smallexample
'(this list has (a list inside of it))
@end smallexample

The components of this list are the words @samp{this}, @samp{list},
@samp{has}, and the list @samp{(a list inside of it)}.  The interior
list is made up of the words @samp{a}, @samp{list}, @samp{inside},
@samp{of}, @samp{it}.

@node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
@comment  node-name,  next,  previous,  up
@subsection Lisp Atoms
@cindex Lisp Atoms

In Lisp, what we have been calling words are called @dfn{atoms}.  This
term comes from the historical meaning of the word atom, which means
`indivisible'.  As far as Lisp is concerned, the words we have been
using in the lists cannot be divided into any smaller parts and still
mean the same thing as part of a program; likewise with numbers and
single character symbols like @samp{+}.  On the other hand, unlike an
ancient atom, a list can be split into parts.  (@xref{car cdr & cons,
, @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)

In a list, atoms are separated from each other by whitespace.  They can be
right next to a parenthesis.

@cindex @samp{empty list} defined
Technically speaking, a list in Lisp consists of parentheses surrounding
atoms separated by whitespace or surrounding other lists or surrounding
both atoms and other lists.  A list can have just one atom in it or
have nothing in it at all.  A list with nothing in it looks like this:
@code{()}, and is called the @dfn{empty list}.  Unlike anything else, an
empty list is considered both an atom and a list at the same time.

@cindex Symbolic expressions, introduced
@cindex @samp{expression} defined
@cindex @samp{form} defined
The printed representation of both atoms and lists are called
@dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
The word @dfn{expression} by itself can refer to either the printed
representation, or to the atom or list as it is held internally in the
computer.  Often, people use the term @dfn{expression}
indiscriminately.  (Also, in many texts, the word @dfn{form} is used
as a synonym for expression.)

Incidentally, the atoms that make up our universe were named such when
they were thought to be indivisible; but it has been found that physical
atoms are not indivisible.  Parts can split off an atom or it can
fission into two parts of roughly equal size.  Physical atoms were named
prematurely, before their truer nature was found.  In Lisp, certain
kinds of atom, such as an array, can be separated into parts; but the
mechanism for doing this is different from the mechanism for splitting a
list.  As far as list operations are concerned, the atoms of a list are
unsplittable.

As in English, the meanings of the component letters of a Lisp atom
are different from the meaning the letters make as a word.  For
example, the word for the South American sloth, the @samp{ai}, is
completely different from the two words, @samp{a}, and @samp{i}.

There are many kinds of atom in nature but only a few in Lisp: for
example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
as @samp{+}, @samp{foo}, or @samp{forward-line}.  The words we have
listed in the examples above are all symbols.  In everyday Lisp
conversation, the word ``atom'' is not often used, because programmers
usually try to be more specific about what kind of atom they are dealing
with.  Lisp programming is mostly about symbols (and sometimes numbers)
within lists.  (Incidentally, the preceding three word parenthetical
remark is a proper list in Lisp, since it consists of atoms, which in
this case are symbols, separated by whitespace and enclosed by
parentheses, without any non-Lisp punctuation.)

@need 1250
1248 1249
Text between double quotation marks---even sentences or
paragraphs---is also an atom.  Here is an example:
Glenn Morris's avatar
Glenn Morris committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
@cindex Text between double quotation marks

@smallexample
'(this list includes "text between quotation marks.")
@end smallexample

@cindex @samp{string} defined
@noindent
In Lisp, all of the quoted text including the punctuation mark and the
blank spaces is a single atom.  This kind of atom is called a
@dfn{string} (for `string of characters') and is the sort of thing that
is used for messages that a computer can print for a human to read.
Strings are a different kind of atom than numbers or symbols and are
used differently.

@node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
@comment  node-name,  next,  previous,  up
@subsection Whitespace in Lists
@cindex Whitespace in lists

@need 1200
The amount of whitespace in a list does not matter.  From the point of view
of the Lisp language,

@smallexample
@group
'(this list
   looks like this)
@end group
@end smallexample

@need 800
@noindent
is exactly the same as this:

@smallexample
'(this list looks like this)
@end smallexample

Both examples show what to Lisp is the same list, the list made up of
the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
@samp{this} in that order.

Extra whitespace and newlines are designed to make a list more readable
by humans.  When Lisp reads the expression, it gets rid of all the extra
whitespace (but it needs to have at least one space between atoms in
order to tell them apart.)

Odd as it seems, the examples we have seen cover almost all of what Lisp
lists look like!  Every other list in Lisp looks more or less like one
of these examples, except that the list may be longer and more complex.
In brief, a list is between parentheses, a string is between quotation
marks, a symbol looks like a word, and a number looks like a number.
(For certain situations, square brackets, dots and a few other special
characters may be used; however, we will go quite far without them.)

@node Typing Lists,  , Whitespace in Lists, Lisp Lists
@comment  node-name,  next,  previous,  up
@subsection GNU Emacs Helps You Type Lists
@cindex Help typing lists
@cindex Formatting help

When you type a Lisp expression in GNU Emacs using either Lisp
Interaction mode or Emacs Lisp mode, you have available to you several
commands to format the Lisp expression so it is easy to read.  For
example, pressing the @key{TAB} key automatically indents the line the
cursor is on by the right amount.  A command to properly indent the
code in a region is customarily bound to @kbd{M-C-\}.  Indentation is
designed so that you can see which elements of a list belong to which
list---elements of a sub-list are indented more than the elements of
the enclosing list.

In addition, when you type a closing parenthesis, Emacs momentarily
jumps the cursor back to the matching opening parenthesis, so you can
see which one it is.  This is very useful, since every list you type
in Lisp must have its closing parenthesis match its opening
parenthesis.  (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
Manual}, for more information about Emacs' modes.)

@node Run a Program, Making Errors, Lisp Lists, List Processing
@comment  node-name,  next,  previous,  up
@section Run a Program
@cindex Run a program
@cindex Program, running one

@cindex @samp{evaluate} defined
A list in Lisp---any list---is a program ready to run.  If you run it
(for which the Lisp jargon is @dfn{evaluate}), the computer will do one
of three things: do nothing except return to you the list itself; send
you an error message; or, treat the first symbol in the list as a
command to do something.  (Usually, of course, it is the last of these
three things that you really want!)

@c use code for the single apostrophe, not samp.
The single apostrophe, @code{'}, that I put in front of some of the
example lists in preceding sections is called a @dfn{quote}; when it
precedes a list, it tells Lisp to do nothing with the list, other than
take it as it is written.  But if there is no quote preceding a list,
the first item of the list is special: it is a command for the computer
to obey.  (In Lisp, these commands are called @emph{functions}.)  The list
@code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
understands that the @code{+} is an instruction to do something with the
rest of the list: add the numbers that follow.

@need 1250
If you are reading this inside of GNU Emacs in Info, here is how you can
evaluate such a list:  place your cursor immediately after the right
hand parenthesis of the following list and then type @kbd{C-x C-e}:

@smallexample
(+ 2 2)
@end smallexample

@c use code for the number four, not samp.
@noindent
You will see the number @code{4} appear in the echo area.  (In the
jargon, what you have just done is ``evaluate the list.''  The echo area
is the line at the bottom of the screen that displays or ``echoes''
text.)  Now try the same thing with a quoted list:  place the cursor
right after the following list and type @kbd{C-x C-e}:

@smallexample
'(this is a quoted list)
@end smallexample

@noindent
You will see @code{(this is a quoted list)} appear in the echo area.

@cindex Lisp interpreter, explained
@cindex Interpreter, Lisp, explained
In both cases, what you are doing is giving a command to the program
inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
interpreter a command to evaluate the expression.  The name of the Lisp
interpreter comes from the word for the task done by a human who comes
up with the meaning of an expression---who ``interprets'' it.

You can also evaluate an atom that is not part of a list---one that is
not surrounded by parentheses; again, the Lisp interpreter translates
from the humanly readable expression to the language of the computer.
But before discussing this (@pxref{Variables}), we will discuss what the
Lisp interpreter does when you make an error.

@node Making Errors, Names & Definitions, Run a Program, List Processing
@comment  node-name,  next,  previous,  up
@section Generate an Error Message
@cindex Generate an error message
@cindex Error message generation

Partly so you won't worry if you do it accidentally, we will now give
a command to the Lisp interpreter that generates an error message.
This is a harmless activity; and indeed, we will often try to generate
error messages intentionally.  Once you understand the jargon, error
messages can be informative.  Instead of being called ``error''
messages, they should be called ``help'' messages.  They are like
signposts to a traveller in a strange country; deciphering them can be
hard, but once understood, they can point the way.

The error message is generated by a built-in GNU Emacs debugger.  We
will `enter the debugger'.  You get out of the debugger by typing @code{q}.

What we will do is evaluate a list that is not quoted and does not
have a meaningful command as its first element.  Here is a list almost
exactly the same as the one we just used, but without the single-quote
in front of it.  Position the cursor right after it and type @kbd{C-x
C-e}:

@smallexample
(this is an unquoted list)
@end smallexample

@noindent
What you see depends on which version of Emacs you are running.  GNU
Emacs version 22 provides more information than version 20 and before.
First, the more recent result of generating an error; then the
earlier, version 20 result.

@need 1250
@noindent
In GNU Emacs version 22, a @file{*Backtrace*} window will open up and
you will see the following in it:

@smallexample
@group
---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function this)
  (this is an unquoted list)
  eval((this is an unquoted list))
  eval-last-sexp-1(nil)
  eval-last-sexp(nil)
  call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
@end group
@end smallexample

@need 1200
@noindent
Your cursor will be in this window (you may have to wait a few seconds
before it becomes visible).  To quit the debugger and make the
debugger window go away, type:

@smallexample
q
@end smallexample

@noindent
Please type @kbd{q} right now, so you become confident that you can
get out of the debugger.  Then, type @kbd{C-x C-e} again to re-enter
it.

@cindex @samp{function} defined
Based on what we already know, we can almost read this error message.

You read the @file{*Backtrace*} buffer from the bottom up; it tells
you what Emacs did.  When you typed @kbd{C-x C-e}, you made an
interactive call to the command @code{eval-last-sexp}.  @code{eval} is
an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
`symbolic expression'.  The command means `evaluate last symbolic
expression', which is the expression just before your cursor.

Each line above tells you what the Lisp interpreter evaluated next.
The most recent action is at the top.  The buffer is called the
@file{*Backtrace*} buffer because it enables you to track Emacs
backwards.

@need 800
At the top of the @file{*Backtrace*} buffer, you see the line:

@smallexample
Debugger entered--Lisp error: (void-function this)
@end smallexample

@noindent
The Lisp interpreter tried to evaluate the first atom of the list, the
word @samp{this}.  It is this action that generated the error message
@samp{void-function this}.

The message contains the words @samp{void-function} and @samp{this}.

@cindex @samp{function} defined
The word @samp{function} was mentioned once before.  It is a very
important word.  For our purposes, we can define it by saying that a
@dfn{function} is a set of instructions to the computer that tell the
computer to do something.

Now we can begin to understand the error message: @samp{void-function
this}.  The function (that is, the word @samp{this}) does not have a
definition of any set of instructions for the computer to carry out.

The slightly odd word, @samp{void-function}, is designed to cover the
way Emacs Lisp is implemented, which is that when a symbol does not
have a function definition attached to it, the place that should
contain the instructions is `void'.

On the other hand, since we were able to add 2 plus 2 successfully, by
evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
have a set of instructions for the computer to obey and those
instructions must be to add the numbers that follow the @code{+}.

@need 1250
In GNU Emacs version 20, and in earlier versions, you will see only
one line of error message; it will appear in the echo area and look
like this:

@smallexample
Symbol's function definition is void:@: this
@end smallexample

@noindent
(Also, your terminal may beep at you---some do, some don't; and others
blink.  This is just a device to get your attention.)  The message goes
away as soon as you type another key, even just to move the cursor.

We know the meaning of the word @samp{Symbol}.  It refers to the first
atom of the list, the word @samp{this}.  The word @samp{function}
refers to the instructions that tell the computer what to do.
(Technically, the symbol tells the computer where to find the
instructions, but this is a complication we can ignore for the
moment.)

The error message can be understood: @samp{Symbol's function
definition is void:@: this}.  The symbol (that is, the word
@samp{this}) lacks instructions for the computer to carry out.

@node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
@comment  node-name,  next,  previous,  up
@section Symbol Names and Function Definitions
@cindex Symbol names

We can articulate another characteristic of Lisp based on what we have
discussed so far---an important characteristic: a symbol, like
@code{+}, is not itself the set of instructions for the computer to
carry out.  Instead, the symbol is used, perhaps temporarily, as a way
of locating the definition or set of instructions.  What we see is the
name through which the instructions can be found.  Names of people
work the same way.  I can be referred to as @samp{Bob}; however, I am
not the letters @samp{B}, @samp{o}, @samp{b} but am, or was, the
consciousness consistently associated with a particular life-form.
The name is not me, but it can be used to refer to me.

In Lisp, one set of instructions can be attached to several names.
For example, the computer instructions for adding numbers can be
linked to the symbol @code{plus} as well as to the symbol @code{+}
(and are in some dialects of Lisp).  Among humans, I can be referred
to as @samp{Robert} as well as @samp{Bob} and by other words as well.

On the other hand, a symbol can have only one function definition
attached to it at a time.  Otherwise, the computer would be confused as
to which definition to use.  If this were the case among people, only
one person in the world could be named @samp{Bob}.  However, the function
definition to which the name refers can be changed readily.
(@xref{Install, , Install a Function Definition}.)

Since Emacs Lisp is large, it is customary to name symbols in a way
that identifies the part of Emacs to which the function belongs.
Thus, all the names for functions that deal with Texinfo start with
@samp{texinfo-} and those for functions that deal with reading mail
start with @samp{rmail-}.

@node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
@comment  node-name,  next,  previous,  up
@section The Lisp Interpreter
@cindex Lisp interpreter, what it does
@cindex Interpreter, what it does

Based on what we have seen, we can now start to figure out what the
Lisp interpreter does when we command it to evaluate a list.
First, it looks to see whether there is a quote before the list; if
there is, the interpreter just gives us the list.  On the other
hand, if there is no quote, the interpreter looks at the first element
in the list and sees whether it has a function definition.  If it does,
the interpreter carries out the instructions in the function definition.
Otherwise, the interpreter prints an error message.

This is how Lisp works.  Simple.  There are added complications which we
will get to in a minute, but these are the fundamentals.  Of course, to
write Lisp programs, you need to know how to write function definitions
and attach them to names, and how to do this without confusing either
yourself or the computer.

@menu
* Complications::               Variables, Special forms, Lists within.
* Byte Compiling::              Specially processing code for speed.
@end menu

@node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
@ifnottex
@unnumberedsubsec Complications
@end ifnottex

Now, for the first complication.  In addition to lists, the Lisp
interpreter can evaluate a symbol that is not quoted and does not have
parentheses around it.  The Lisp interpreter will attempt to determine
the symbol's value as a @dfn{variable}.  This situation is described
in the section on variables.  (@xref{Variables}.)

@cindex Special form
The second complication occurs because some functions are unusual and do
not work in the usual manner.  Those that don't are called @dfn{special
forms}.  They are used for special jobs, like defining a function, and
there are not many of them.  In the next few chapters, you will be
introduced to several of the more important special forms.

The third and final complication is this: if the function that the
Lisp interpreter is looking at is not a special form, and if it is part
of a list, the Lisp interpreter looks to see whether the list has a list
inside of it.  If there is an inner list, the Lisp interpreter first
figures out what it should do with the inside list, and then it works on
the outside list.  If there is yet another list embedded inside the
inner list, it works on that one first, and so on.  It always works on
the innermost list first.  The interpreter works on the innermost list
first, to evaluate the result of that list.  The result may be
used by the enclosing expression.

Otherwise, the interpreter works left to right, from one expression to
the next.

@node Byte Compiling,  , Complications, Lisp Interpreter
@subsection Byte Compiling
@cindex Byte compiling

One other aspect of interpreting: the Lisp interpreter is able to
interpret two kinds of entity: humanly readable code, on which we will
focus exclusively, and specially processed code, called @dfn{byte
compiled} code, which is not humanly readable.  Byte compiled code
runs faster than humanly readable code.

You can transform humanly readable code into byte compiled code by
running one of the compile commands such as @code{byte-compile-file}.
Byte compiled code is usually stored in a file that ends with a
@file{.elc} extension rather than a @file{.el} extension.  You will
see both kinds of file in the @file{emacs/lisp} directory; the files
to read are those with @file{.el} extensions.

As a practical matter, for most things you might do to customize or
extend Emacs, you do not need to byte compile; and I will not discuss
the topic here.  @xref{Byte Compilation, , Byte Compilation, elisp,
The GNU Emacs Lisp Reference Manual}, for a full description of byte
compilation.

@node Evaluation, Variables, Lisp Interpreter, List Processing
@comment  node-name,  next,  previous,  up
@section Evaluation
@cindex Evaluation

When the Lisp interpreter works on an expression, the term for the
activity is called @dfn{evaluation}.  We say that the interpreter
`evaluates the expression'.  I've used this term several times before.
The word comes from its use in everyday language, `to ascertain the
value or amount of; to appraise', according to @cite{Webster's New
Collegiate Dictionary}.

@menu
* How the Interpreter Acts::    Returns and Side Effects...
* Evaluating Inner Lists::      Lists within lists...
@end menu

@node How the Interpreter Acts, Evaluating Inner Lists, Evaluation, Evaluation
@ifnottex
@unnumberedsubsec How the Lisp Interpreter Acts
@end ifnottex

@cindex @samp{returned value} explained
After evaluating an expression, the Lisp interpreter will most likely
@dfn{return} the value that the computer produces by carrying out the
instructions it found in the function definition, or perhaps it will
give up on that function and produce an error message.  (The interpreter
may also find itself tossed, so to speak, to a different function or it
may attempt to repeat continually what it is doing for ever and ever in
what is called an `infinite loop'.  These actions are less common; and
we can ignore them.)  Most frequently, the interpreter returns a value.

@cindex @samp{side effect} defined
At the same time the interpreter returns a value, it may do something
else as well, such as move a cursor or copy a file; this other kind of
action is called a @dfn{side effect}.  Actions that we humans think are
important, such as printing results, are often ``side effects'' to the
Lisp interpreter.  The jargon can sound peculiar, but it turns out that
it is fairly easy to learn to use side effects.

In summary, evaluating a symbolic expression most commonly causes the
Lisp interpreter to return a value and perhaps carry out a side effect;
or else produce an error.

@node Evaluating Inner Lists,  , How the Interpreter Acts, Evaluation
@comment  node-name,  next,  previous,  up
@subsection Evaluating Inner Lists
@cindex Inner list evaluation
@cindex Evaluating inner lists

If evaluation applies to a list that is inside another list, the outer
list may use the value returned by the first evaluation as information
when the outer list is evaluated.  This explains why inner expressions
are evaluated first: the values they return are used by the outer
expressions.

@need 1250
We can investigate this process by evaluating another addition example.
Place your cursor after the following expression and type @kbd{C-x C-e}:

@smallexample
(+ 2 (+ 3 3))
@end smallexample

@noindent
The number 8 will appear in the echo area.

What happens is that the Lisp interpreter first evaluates the inner
expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
evaluates the outer expression as if it were written @code{(+ 2 6)}, which
returns the value 8.  Since there are no more enclosing expressions to
evaluate, the interpreter prints that value in the echo area.

Now it is easy to understand the name of the command invoked by the
keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}.  The
letters @code{sexp} are an abbreviation for `symbolic expression', and
@code{eval} is an abbreviation for `evaluate'.  The command means
`evaluate last symbolic expression'.

As an experiment, you can try evaluating the expression by putting the
cursor at the beginning of the next line immediately following the
expression, or inside the expression.

@need 800
Here is another copy of the expression:

@smallexample
(+ 2 (+ 3 3))
@end smallexample

@noindent
If you place the cursor at the beginning of the blank line that
immediately follows the expression and type @kbd{C-x C-e}, you will
still get the value 8 printed in the echo area.  Now try putting the
cursor inside the expression.  If you put it right after the next to
last parenthesis (so it appears to sit on top of the last parenthesis),
you will get a 6 printed in the echo area!  This is because the command
evaluates the expression @code{(+ 3 3)}.

Now put the cursor immediately after a number.  Type @kbd{C-x C-e} and
you will get the number itself.  In Lisp, if you evaluate a number, you
get the number itself---this is how numbers differ from symbols.  If you
evaluate a list starting with a symbol like @code{+}, you will get a
value returned that is the result of the computer carrying out the
instructions in the function definition attached to that name.  If a
symbol by itself is evaluated, something different happens, as we will
see in the next section.

@node Variables, Arguments, Evaluation, List Processing
@comment  node-name,  next,  previous,  up
@section Variables
@cindex Variables

In Emacs Lisp, a symbol can have a value attached to it just as it can
have a function definition attached to it.  The two are different.
The function definition is a set of instructions that a computer will
obey.  A value, on the other hand, is something, such as number or a
name, that can vary (which is why such a symbol is called a variable).
The value of a symbol can be any expression in Lisp, such as a symbol,
number, list, or string.  A symbol that has a value is often called a
@dfn{variable}.

A symbol can have both a function definition and a value attached to
it at the same time.  Or it can have just one or the other.
The two are separate.  This is somewhat similar
to the way the name Cambridge can refer to the city in Massachusetts
and have some information attached to the name as well, such as
``great programming center''.

@ignore
(Incidentally, in Emacs Lisp, a symbol can have two
other things attached to it, too: a property list and a documentation
string; these are discussed later.)
@end ignore

Another way to think about this is to imagine a symbol as being a chest
of drawers.  The function definition is put in one drawer, the value in
another, and so on.  What is put in the drawer holding the value can be
changed without affecting the contents of the drawer holding the
function definition, and vice-verse.

@menu
* fill-column Example::
* Void Function::               The error message for a symbol
                                  without a function.
* Void Variable::               The error message for a symbol without a value.
@end menu

@node fill-column Example, Void Function, Variables, Variables
@ifnottex
@unnumberedsubsec @code{fill-column}, an Example Variable
@end ifnottex

@findex fill-column, @r{an example variable}
@cindex Example variable, @code{fill-column}
@cindex Variable, example of, @code{fill-column}
The variable @code{fill-column} illustrates a symbol with a value
attached to it: in every GNU Emacs buffer, this symbol is set to some
value, usually 72 or 70, but sometimes to some other value.  To find the
value of this symbol, evaluate it by itself.  If you are reading this in
Info inside of GNU Emacs, you can do this by putting the cursor after
the symbol and typing @kbd{C-x C-e}:

@smallexample
fill-column
@end smallexample

@noindent
After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
area.  This is the value for which @code{fill-column} is set for me as I
write this.  It may be different for you in your Info buffer.  Notice
that the value returned as a variable is printed in exactly the same way
as the value returned by a function carrying out its instructions.  From
the point of view of the Lisp interpreter, a value returned is a value
returned.  What kind of expression it came from ceases to matter once
the value is known.

A symbol can have any value attached to it or, to use the jargon, we can
@dfn{bind} the variable to a value: to a number, such as 72; to a
string, @code{"such as this"}; to a list, such as @code{(spruce pine
oak)}; we can even bind a variable to a function definition.

A symbol can be bound to a value in several ways.  @xref{set & setq, ,
Setting the Value of a Variable}, for information about one way to do
this.

@node Void Function, Void Variable, fill-column Example, Variables
@comment  node-name,  next,  previous,  up
@subsection Error Message for a Symbol Without a Function
@cindex Symbol without function error
@cindex Error for symbol without function

When we evaluated @code{fill-column} to find its value as a variable,
we did not place parentheses around the word.  This is because we did
not intend to use it as a function name.

If @code{fill-column} were the first or only element of a list, the
Lisp interpreter would attempt to find the function definition
attached to it.  But @code{fill-column} has no function definition.
Try evaluating this:

@smallexample
(fill-column)
@end smallexample

@need 1250
@noindent
In GNU Emacs version 22, you will create a @file{*Backtrace*} buffer
that says:

@smallexample
@group
---------- Buffer: *Backtrace* ----------