\input texinfo @c -*-texinfo-*- @comment %**start of header @setfilename ../info/eintr @c sethtmlfilename emacs-lisp-intro.html @settitle Programming in Emacs Lisp @syncodeindex vr cp @syncodeindex fn cp @setchapternewpage odd @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 >>>> @smallbook @clear largebook @set print-postscript-figures @c set largebook @c clear print-postscript-figures @c --------- @comment %**end of header @set edition-number 2.07 @set update-date 2003 Apr 17 @ignore ## Summary of shell commands to create various output formats: ## Info output makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi ## DVI output texi2dvi emacs-lisp-intro.texi ## HTML output makeinfo --html --no-split --verbose emacs-lisp-intro.texi ## Plain text output makeinfo --fill-column=70 --no-split --paragraph-indent=0 \ --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi ## DocBook output makeinfo --docbook --no-split --paragraph-indent=0 \ --verbose emacs-lisp-intro.texi ## XML output makeinfo --xml --no-split --paragraph-indent=0 \ --verbose emacs-lisp-intro.texi @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/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 [...] @tex % Need following so comma appears after section numbers. \global\def\Ysectionnumberandtype{% \ifnum\secno=0 \putwordChapter\xreftie\the\chapno, \space % \else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno, \space % \else \ifnum \subsubsecno=0 % \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno, \space % \else % \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno, \space% \fi \fi \fi } \global\def\Yappendixletterandtype{% \ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}, \space% \else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno, \space % \else \ifnum \subsubsecno=0 % \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno, \space % \else % \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno, \space % \fi \fi \fi } \global\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup \def\printedmanual{\ignorespaces #5}% \def\printednodename{\ignorespaces #3}% \setbox1=\hbox{\printedmanual}% \setbox0=\hbox{\printednodename}% \ifdim \wd0 = 0pt % No printed node name was explicitly given. \ifx\SETxref-automatic-section-title\relax % % Use the actual chapter/section title appear inside % the square brackets. Use the real section title if we have it. \ifdim \wd1>0pt% % It is in another manual, so we don't have it. \def\printednodename{\ignorespaces #1}% \else \ifhavexrefs % We know the real title if we have the xref values. \def\printednodename{\refx{#1-title}}% \else % Otherwise just copy the Info node name. \def\printednodename{\ignorespaces #1}% \fi% \fi \def\printednodename{#1-title}% \else % Use the node name inside the square brackets. \def\printednodename{\ignorespaces #1}% \fi \fi % % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not % insert empty discretionaries after hyphens, which means that it will % not find a line break at a hyphen in a node names. Since some manuals % are best written with fairly long node names, containing hyphens, this % is a loss. Therefore, we give the text of the node name again, so it % is as if TeX is seeing it for the first time. \ifdim \wd1 > 0pt \putwordsection{} ``\printednodename'' in \cite{\printedmanual}% \else % _ (for example) has to be the character _ for the purposes of the % control sequence corresponding to the node, but it has to expand % into the usual \leavevmode...\vrule stuff for purposes of % printing. So we \turnoffactive for the \refx-snt, back on for the % printing, back off for the \refx-pg. {\turnoffactive \refx{#1-snt}{}}% % \space [\printednodename],\space % <= original % \putwordsection{} ``\printednodename'',\space ``\printednodename'',\space \turnoffactive \putwordpage\tie\refx{#1-pg}{}% \fi \endgroup} @end tex @c ---------------------------------------------------- @dircategory Emacs @direntry * Emacs Lisp Intro: (eintr). A simple introduction to Emacs Lisp programming. @end direntry @copying This is an introduction to @cite{Programming in Emacs Lisp}, for people who are not programmers. Edition @value{edition-number}, @value{update-date} Copyright @copyright{} 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002, 2003 Free Software Foundation, Inc. @sp 2 Published by the Free Software Foundation, Inc.@* 59 Temple Place, Suite 330@* Boston, MA 02111-1307 USA@* @c Printed copies are available for $30 each.@* ISBN 1-882114-43-4 Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or 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''. (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.'' @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 Second 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. @ifset largebook @tex \global\parskip 2pt plus 1pt \global\advance\baselineskip by -1pt @end tex @end ifset @shortcontents @contents @ifset largebook @tex \global\parskip 6pt plus 1pt \global\advance\baselineskip by 1pt @end tex @end ifset @end ifnothtml @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. @c if largebook, there are 8 pages in Table of Contents @ifset largebook @iftex @pageno = -9 @end iftex @end ifset @c if smallbook, there are 10 pages in Table of Contents @ifclear largebook @iftex @pageno = -11 @end iftex @end ifclear @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 @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. * 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:: Formating 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 * 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. 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. * Digression into C:: Minor note on C programming language macros. * defvar:: How to give a variable an initial value. * copy-region-as-kill:: A definition for copying text. * 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. * delete-and-extract-region:: Doing the work. Initializing a Variable with @code{defvar} * See variable current value:: * defvar and asterisk:: An old-time convention. @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:: How Lists are Implemented * Lists diagrammed:: * Symbols as Chest:: Exploring a powerful metaphor. * List Exercise:: Yanking Text Back * Kill Ring Overview:: The kill ring is a list. * kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable. * yank nthcdr Exercises:: 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. * Decrementing Loop:: A loop with a decrementing counter. A Loop with an Incrementing Counter * 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. * fwd-para between paragraphs:: Movement between paragraphs. * fwd-para within paragraph:: Movement within paragraphs. * fwd-para no fill prefix:: When there is no fill prefix. * fwd-para with fill prefix:: When there is a fill prefix. * fwd-para summary:: Summary of @code{forward-paragraph} code. 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 * 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 version 19 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 * rotate-yank-pointer:: Move a pointer along a list and around. * yank:: Paste a copy of a clipped element. * yank-pop:: Insert first element pointed to. The @code{rotate-yank-pointer} Function * Understanding rotate-yk-ptr:: * rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}. The Body of @code{rotate-yank-pointer} * Digression concerning error:: How to mislead humans, but not computers. * rotate-yk-ptr else-part:: The else-part of the @code{if} expression. * Remainder Function:: The remainder, @code{%}, function. * rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}. * kill-rng-yk-ptr last elt:: Pointing to the last element. @code{yank} * rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}. * rotate-yk-ptr negative arg:: Pass a negative argument. 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 * 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 @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 @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{'}. 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:: Formating 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 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 In addition, text between double quotation marks---even sentences or paragraphs---is an atom. Here is an example: @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 21 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 21, 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 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}. 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. @menu * Evaluating Inner Lists:: Lists within lists... @end menu @node Evaluating Inner Lists, , Evaluation, 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-versa. @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 21, you will create a @file{*Backtrace*} buffer that says: @smallexample @group ---------- Buffer: *Backtrace* ---------- Debugger entered--Lisp error: (void-function fill-column) (fill-column) eval((fill-column)) eval-last-sexp-1(nil) eval-last-sexp(nil) call-interactively(eval-last-sexp) ---------- Buffer: *Backtrace* ---------- @end group @end smallexample @noindent (Remember, to quit the debugger and make the debugger window go away, type @kbd{q} in the @file{*Backtrace*} buffer.) @need 800 In GNU Emacs 20 and before, you will produce an error message that says: @smallexample Symbol's function definition is void:@: fill-column @end smallexample @noindent (The message will go away away as soon as you move the cursor or type another key.) @node Void Variable, , Void Function, Variables @comment node-name, next, previous, up @subsection Error Message for a Symbol Without a Value @cindex Symbol without value error @cindex Error for symbol without value If you attempt to evaluate a symbol that does not have a value bound to it, you will receive an error message. You can see this by experimenting with our 2 plus 2 addition. In the following expression, put your cursor right after the @code{+}, before the first number 2, type @kbd{C-x C-e}: @smallexample (+ 2 2) @end smallexample @need 1500 @noindent In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that says: @smallexample @group ---------- Buffer: *Backtrace* ---------- Debugger entered--Lisp error: (void-variable +) eval(+) eval-last-sexp-1(nil) eval-last-sexp(nil) call-interactively(eval-last-sexp) ---------- Buffer: *Backtrace* ---------- @end group @end smallexample @noindent (As with the other times we entered the debugger, you can quit by typing @kbd{q} in the @file{*Backtrace*} buffer.) This backtrace is different from the very first error message we saw, which said, @samp{Debugger entered--Lisp error: (void-function this)}. In this case, the function does not have a value as a variable; while in the other error message, the function (the word `this') did not have a definition. In this experiment with the @code{+}, what we did was cause the Lisp interpreter to evaluate the @code{+} and look for the value of the variable instead of the function definition. We did this by placing the cursor right after the symbol rather than after the parenthesis of the enclosing list as we did before. As a consequence, the Lisp interpreter evaluated the preceding s-expression, which in this case was the @code{+} by itself. Since @code{+} does not have a value bound to it, just the function definition, the error message reported that the symbol's value as a variable was void. @need 800 In GNU Emacs version 20 and before, your error message will say: @example Symbol's value as variable is void:@: + @end example @noindent The meaning is the same as in GNU Emacs 21. @node Arguments, set & setq, Variables, List Processing @comment node-name, next, previous, up @section Arguments @cindex Arguments @cindex Passing information to functions To see how information is passed to functions, let's look again at our old standby, the addition of two plus two. In Lisp, this is written as follows: @smallexample (+ 2 2) @end smallexample If you evaluate this expression, the number 4 will appear in your echo area. What the Lisp interpreter does is add the numbers that follow the @code{+}. @cindex @samp{argument} defined The numbers added by @code{+} are called the @dfn{arguments} of the function @code{+}. These numbers are the information that is given to or @dfn{passed} to the function. The word `argument' comes from the way it is used in mathematics and does not refer to a disputation between two people; instead it refers to the information presented to the function, in this case, to the @code{+}. In Lisp, the arguments to a function are the atoms or lists that follow the function. The values returned by the evaluation of these atoms or lists are passed to the function. Different functions require different numbers of arguments; some functions require none at all.@footnote{It is curious to track the path by which the word `argument' came to have two different meanings, one in mathematics and the other in everyday English. According to the @cite{Oxford English Dictionary}, the word derives from the Latin for @samp{to make clear, prove}; thus it came to mean, by one thread of derivation, `the evidence offered as proof', which is to say, `the information offered', which led to its meaning in Lisp. But in the other thread of derivation, it came to mean `to assert in a manner against which others may make counter assertions', which led to the meaning of the word as a disputation. (Note here that the English word has two different definitions attached to it at the same time. By contrast, in Emacs Lisp, a symbol cannot have two different function definitions at the same time.)} @menu * 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. @end menu @node Data types, Args as Variable or List, Arguments, Arguments @comment node-name, next, previous, up @subsection Arguments' Data Types @cindex Data types @cindex Types of data @cindex Arguments' data types The type of data that should be passed to a function depends on what kind of information it uses. The arguments to a function such as @code{+} must have values that are numbers, since @code{+} adds numbers. Other functions use different kinds of data for their arguments. @findex concat For example, the @code{concat} function links together or unites two or more strings of text to produce a string. The arguments are strings. Concatenating the two character strings @code{abc}, @code{def} produces the single string @code{abcdef}. This can be seen by evaluating the following: @smallexample (concat "abc" "def") @end smallexample @noindent The value produced by evaluating this expression is @code{"abcdef"}. A function such as @code{substring} uses both a string and numbers as arguments. The function returns a part of the string, a substring of the first argument. This function takes three arguments. Its first argument is the string of characters, the second and third arguments are numbers that indicate the beginning and end of the substring. The numbers are a count of the number of characters (including spaces and punctuations) from the beginning of the string. @need 800 For example, if you evaluate the following: @smallexample (substring "The quick brown fox jumped." 16 19) @end smallexample @noindent you will see @code{"fox"} appear in the echo area. The arguments are the string and the two numbers. Note that the string passed to @code{substring} is a single atom even though it is made up of several words separated by spaces. Lisp counts everything between the two quotation marks as part of the string, including the spaces. You can think of the @code{substring} function as a kind of `atom smasher' since it takes an otherwise indivisible atom and extracts a part. However, @code{substring} is only able to extract a substring from an argument that is a string, not from another type of atom such as a number or symbol. @node Args as Variable or List, Variable Number of Arguments, Data types, Arguments @comment node-name, next, previous, up @subsection An Argument as the Value of a Variable or List An argument can be a symbol that returns a value when it is evaluated. For example, when the symbol @code{fill-column} by itself is evaluated, it returns a number. This number can be used in an addition. @need 1250 Position the cursor after the following expression and type @kbd{C-x C-e}: @smallexample (+ 2 fill-column) @end smallexample @noindent The value will be a number two more than what you get by evaluating @code{fill-column} alone. For me, this is 74, because the value of @code{fill-column} is 72. As we have just seen, an argument can be a symbol that returns a value when evaluated. In addition, an argument can be a list that returns a value when it is evaluated. For example, in the following expression, the arguments to the function @code{concat} are the strings @w{@code{"The "}} and @w{@code{" red foxes."}} and the list @code{(number-to-string (+ 2 fill-column))}. @c For Emacs 21, need number-to-string @smallexample (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.") @end smallexample @noindent If you evaluate this expression---and if, as with my Emacs, @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will appear in the echo area. (Note that you must put spaces after the word @samp{The} and before the word @samp{red} so they will appear in the final string. The function @code{number-to-string} converts the integer that the addition function returns to a string. @code{number-to-string} is also known as @code{int-to-string}.) @node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments @comment node-name, next, previous, up @subsection Variable Number of Arguments @cindex Variable number of arguments @cindex Arguments, variable number of Some functions, such as @code{concat}, @code{+} or @code{*}, take any number of arguments. (The @code{*} is the symbol for multiplication.) This can be seen by evaluating each of the following expressions in the usual way. What you will see in the echo area is printed in this text after @samp{@result{}}, which you may read as `evaluates to'. @need 1250 In the first set, the functions have no arguments: @smallexample @group (+) @result{} 0 (*) @result{} 1 @end group @end smallexample @need 1250 In this set, the functions have one argument each: @smallexample @group (+ 3) @result{} 3 (* 3) @result{} 3 @end group @end smallexample @need 1250 In this set, the functions have three arguments each: @smallexample @group (+ 3 4 5) @result{} 12 (* 3 4 5) @result{} 60 @end group @end smallexample @node Wrong Type of Argument, message, Variable Number of Arguments, Arguments @comment node-name, next, previous, up @subsection Using the Wrong Type Object as an Argument @cindex Wrong type of argument @cindex Argument, wrong type of When a function is passed an argument of the wrong type, the Lisp interpreter produces an error message. For example, the @code{+} function expects the values of its arguments to be numbers. As an experiment we can pass it the quoted symbol @code{hello} instead of a number. Position the cursor after the following expression and type @kbd{C-x C-e}: @smallexample (+ 2 'hello) @end smallexample @noindent When you do this you will generate an error message. What has happened is that @code{+} has tried to add the 2 to the value returned by @code{'hello}, but the value returned by @code{'hello} is the symbol @code{hello}, not a number. Only numbers can be added. So @code{+} could not carry out its addition. @need 1250 In GNU Emacs version 21, you will create and enter a @file{*Backtrace*} buffer that says: @noindent @smallexample @group ---------- Buffer: *Backtrace* ---------- Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p hello) +(2 hello) eval((+ 2 (quote hello))) eval-last-sexp-1(nil) eval-last-sexp(nil) call-interactively(eval-last-sexp) ---------- Buffer: *Backtrace* ---------- @end group @end smallexample @need 1250 As usual, the error message tries to be helpful and makes sense after you learn how to read it. The first part of the error message is straightforward; it says @samp{wrong type argument}. Next comes the mysterious jargon word @w{@samp{number-or-marker-p}}. This word is trying to tell you what kind of argument the @code{+} expected. The symbol @code{number-or-marker-p} says that the Lisp interpreter is trying to determine whether the information presented it (the value of the argument) is a number or a marker (a special object representing a buffer position). What it does is test to see whether the @code{+} is being given numbers to add. It also tests to see whether the argument is something called a marker, which is a specific feature of Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers. When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command, its position is kept as a marker. The mark can be considered a number---the number of characters the location is from the beginning of the buffer.) In Emacs Lisp, @code{+} can be used to add the numeric value of marker positions as numbers. The @samp{p} of @code{number-or-marker-p} is the embodiment of a practice started in the early days of Lisp programming. The @samp{p} stands for `predicate'. In the jargon used by the early Lisp researchers, a predicate refers to a function to determine whether some property is true or false. So the @samp{p} tells us that @code{number-or-marker-p} is the name of a function that determines whether it is true or false that the argument supplied is a number or a marker. Other Lisp symbols that end in @samp{p} include @code{zerop}, a function that tests whether its argument has the value of zero, and @code{listp}, a function that tests whether its argument is a list. Finally, the last part of the error message is the symbol @code{hello}. This is the value of the argument that was passed to @code{+}. If the addition had been passed the correct type of object, the value passed would have been a number, such as 37, rather than a symbol like @code{hello}. But then you would not have got the error message. @need 1250 In GNU Emacs version 20 and before, the echo area displays an error message that says: @smallexample Wrong type argument:@: number-or-marker-p, hello @end smallexample This says, in different words, the same as the top line of the @file{*Backtrace*} buffer. @node message, , Wrong Type of Argument, Arguments @comment node-name, next, previous, up @subsection The @code{message} Function @findex message Like @code{+}, the @code{message} function takes a variable number of arguments. It is used to send messages to the user and is so useful that we will describe it here. @need 1250 A message is printed in the echo area. For example, you can print a message in your echo area by evaluating the following list: @smallexample (message "This message appears in the echo area!") @end smallexample The whole string between double quotation marks is a single argument and is printed @i{in toto}. (Note that in this example, the message itself will appear in the echo area within double quotes; that is because you see the value returned by the @code{message} function. In most uses of @code{message} in programs that you write, the text will be printed in the echo area as a side-effect, without the quotes. @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in detail}, for an example of this.) However, if there is a @samp{%s} in the quoted string of characters, the @code{message} function does not print the @samp{%s} as such, but looks to the argument that follows the string. It evaluates the second argument and prints the value at the location in the string where the @samp{%s} is. @need 1250 You can see this by positioning the cursor after the following expression and typing @kbd{C-x C-e}: @smallexample (message "The name of this buffer is: %s." (buffer-name)) @end smallexample @noindent In Info, @code{"The name of this buffer is: *info*."} will appear in the echo area. The function @code{buffer-name} returns the name of the buffer as a string, which the @code{message} function inserts in place of @code{%s}. To print a value as an integer, use @samp{%d} in the same way as @samp{%s}. For example, to print a message in the echo area that states the value of the @code{fill-column}, evaluate the following: @smallexample (message "The value of fill-column is %d." fill-column) @end smallexample @noindent On my system, when I evaluate this list, @code{"The value of fill-column is 72."} appears in my echo area@footnote{Actually, you can use @code{%s} to print a number. It is non-specific. @code{%d} prints only the part of a number left of a decimal point, and not anything that is not a number.}. If there is more than one @samp{%s} in the quoted string, the value of the first argument following the quoted string is printed at the location of the first @samp{%s} and the value of the second argument is printed at the location of the second @samp{%s}, and so on. @need 1250 For example, if you evaluate the following, @smallexample @group (message "There are %d %s in the office!" (- fill-column 14) "pink elephants") @end group @end smallexample @noindent a rather whimsical message will appear in your echo area. On my system it says, @code{"There are 58 pink elephants in the office!"}. The expression @code{(- fill-column 14)} is evaluated and the resulting number is inserted in place of the @samp{%d}; and the string in double quotes, @code{"pink elephants"}, is treated as a single argument and inserted in place of the @samp{%s}. (That is to say, a string between double quotes evaluates to itself, like a number.) Finally, here is a somewhat complex example that not only illustrates the computation of a number, but also shows how you can use an expression within an expression to generate the text that is substituted for @samp{%s}: @smallexample @group (message "He saw %d %s" (- fill-column 34) (concat "red " (substring "The quick brown foxes jumped." 16 21) " leaping.")) @end group @end smallexample In this example, @code{message} has three arguments: the string, @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and the expression beginning with the function @code{concat}. The value resulting from the evaluation of @code{(- fill-column 32)} is inserted in place of the @samp{%d}; and the value returned by the expression beginning with @code{concat} is inserted in place of the @samp{%s}. When I evaluate the expression, the message @code{"He saw 38 red foxes leaping."} appears in my echo area. @node set & setq, Summary, Arguments, List Processing @comment node-name, next, previous, up @section Setting the Value of a Variable @cindex Variable, setting value @cindex Setting value of variable @cindex @samp{bind} defined There are several ways by which a variable can be given a value. One of the ways is to use either the function @code{set} or the function @code{setq}. Another way is to use @code{let} (@pxref{let}). (The jargon for this process is to @dfn{bind} a variable to a value.) The following sections not only describe how @code{set} and @code{setq} work but also illustrate how arguments are passed. @menu * Using set:: Setting values. * Using setq:: Setting a quoted value. * Counting:: Using @code{setq} to count. @end menu @node Using set, Using setq, set & setq, set & setq @comment node-name, next, previous, up @subsection Using @code{set} @findex set To set the value of the symbol @code{flowers} to the list @code{'(rose violet daisy buttercup)}, evaluate the following expression by positioning the cursor after the expression and typing @kbd{C-x C-e}. @smallexample (set 'flowers '(rose violet daisy buttercup)) @end smallexample @noindent The list @code{(rose violet daisy buttercup)} will appear in the echo area. This is what is @emph{returned} by the @code{set} function. As a side effect, the symbol @code{flowers} is bound to the list ; that is, the symbol @code{flowers}, which can be viewed as a variable, is given the list as its value. (This process, by the way, illustrates how a side effect to the Lisp interpreter, setting the value, can be the primary effect that we humans are interested in. This is because every Lisp function must return a value if it does not get an error, but it will only have a side effect if it is designed to have one.) After evaluating the @code{set} expression, you can evaluate the symbol @code{flowers} and it will return the value you just set. Here is the symbol. Place your cursor after it and type @kbd{C-x C-e}. @smallexample flowers @end smallexample @noindent When you evaluate @code{flowers}, the list @code{(rose violet daisy buttercup)} appears in the echo area. Incidentally, if you evaluate @code{'flowers}, the variable with a quote in front of it, what you will see in the echo area is the symbol itself, @code{flowers}. Here is the quoted symbol, so you can try this: @smallexample 'flowers @end smallexample Note also, that when you use @code{set}, you need to quote both arguments to @code{set}, unless you want them evaluated. Since we do not want either argument evaluated, neither the variable @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both are quoted. (When you use @code{set} without quoting its first argument, the first argument is evaluated before anything else is done. If you did this and @code{flowers} did not have a value already, you would get an error message that the @samp{Symbol's value as variable is void}; on the other hand, if @code{flowers} did return a value after it was evaluated, the @code{set} would attempt to set the value that was returned. There are situations where this is the right thing for the function to do; but such situations are rare.) @node Using setq, Counting, Using set, set & setq @comment node-name, next, previous, up @subsection Using @code{setq} @findex setq As a practical matter, you almost always quote the first argument to @code{set}. The combination of @code{set} and a quoted first argument is so common that it has its own name: the special form @code{setq}. This special form is just like @code{set} except that the first argument is quoted automatically, so you don't need to type the quote mark yourself. Also, as an added convenience, @code{setq} permits you to set several different variables to different values, all in one expression. To set the value of the variable @code{carnivores} to the list @code{'(lion tiger leopard)} using @code{setq}, the following expression is used: @smallexample (setq carnivores '(lion tiger leopard)) @end smallexample @noindent This is exactly the same as using @code{set} except the first argument is automatically quoted by @code{setq}. (The @samp{q} in @code{setq} means @code{quote}.) @need 1250 With @code{set}, the expression would look like this: @smallexample (set 'carnivores '(lion tiger leopard)) @end smallexample Also, @code{setq} can be used to assign different values to different variables. The first argument is bound to the value of the second argument, the third argument is bound to the value of the fourth argument, and so on. For example, you could use the following to assign a list of trees to the symbol @code{trees} and a list of herbivores to the symbol @code{herbivores}: @smallexample @group (setq trees '(pine fir oak maple) herbivores '(gazelle antelope zebra)) @end group @end smallexample @noindent (The expression could just as well have been on one line, but it might not have fit on a page; and humans find it easier to read nicely formatted lists.) Although I have been using the term `assign', there is another way of thinking about the workings of @code{set} and @code{setq}; and that is to say that @code{set} and @code{setq} make the symbol @emph{point} to the list. This latter way of thinking is very common and in forthcoming chapters we shall come upon at least one symbol that has `pointer' as part of its name. The name is chosen because the symbol has a value, specifically a list, attached to it; or, expressed another way, the symbol is set to ``point'' to the list. @node Counting, , Using setq, set & setq @comment node-name, next, previous, up @subsection Counting @cindex Counting Here is an example that shows how to use @code{setq} in a counter. You might use this to count how many times a part of your program repeats itself. First set a variable to zero; then add one to the number each time the program repeats itself. To do this, you need a variable that serves as a counter, and two expressions: an initial @code{setq} expression that sets the counter variable to zero; and a second @code{setq} expression that increments the counter each time it is evaluated. @smallexample @group (setq counter 0) ; @r{Let's call this the initializer.} (setq counter (+ counter 1)) ; @r{This is the incrementer.} counter ; @r{This is the counter.} @end group @end smallexample @noindent (The text following the @samp{;} are comments. @xref{Change a defun, , Change a Function Definition}.) If you evaluate the first of these expressions, the initializer, @code{(setq counter 0)}, and then evaluate the third expression, @code{counter}, the number @code{0} will appear in the echo area. If you then evaluate the second expression, the incrementer, @code{(setq counter (+ counter 1))}, the counter will get the value 1. So if you again evaluate @code{counter}, the number @code{1} will appear in the echo area. Each time you evaluate the second expression, the value of the counter will be incremented. When you evaluate the incrementer, @code{(setq counter (+ counter 1))}, the Lisp interpreter first evaluates the innermost list; this is the addition. In order to evaluate this list, it must evaluate the variable @code{counter} and the number @code{1}. When it evaluates the variable @code{counter}, it receives its current value. It passes this value and the number @code{1} to the @code{+} which adds them together. The sum is then returned as the value of the inner list and passed to the @code{setq} which sets the variable @code{counter} to this new value. Thus, the value of the variable, @code{counter}, is changed. @node Summary, Error Message Exercises, set & setq, List Processing @comment node-name, next, previous, up @section Summary Learning Lisp is like climbing a hill in which the first part is the steepest. You have now climbed the most difficult part; what remains becomes easier as you progress onwards. In summary, @itemize @bullet @item Lisp programs are made up of expressions, which are lists or single atoms. @item Lists are made up of zero or more atoms or inner lists, separated by whitespace and surrounded by parentheses. A list can be empty. @item Atoms are multi-character symbols, like @code{forward-paragraph}, single character symbols like @code{+}, strings of characters between double quotation marks, or numbers. @item A number evaluates to itself. @item A string between double quotes also evaluates to itself. @item When you evaluate a symbol by itself, its value is returned. @item When you evaluate a list, the Lisp interpreter looks at the first symbol in the list and then at the function definition bound to that symbol. Then the instructions in the function definition are carried out. @item A single-quote, @code{'}, tells the Lisp interpreter that it should return the following expression as written, and not evaluate it as it would if the quote were not there. @item Arguments are the information passed to a function. The arguments to a function are computed by evaluating the rest of the elements of the list of which the function is the first element. @item A function always returns a value when it is evaluated (unless it gets an error); in addition, it may also carry out some action called a ``side effect''. In many cases, a function's primary purpose is to create a side effect. @end itemize @node Error Message Exercises, , Summary, List Processing @comment node-name, next, previous, up @section Exercises A few simple exercises: @itemize @bullet @item Generate an error message by evaluating an appropriate symbol that is not within parentheses. @item Generate an error message by evaluating an appropriate symbol that is between parentheses. @item Create a counter that increments by two rather than one. @item Write an expression that prints a message in the echo area when evaluated. @end itemize @node Practicing Evaluation, Writing Defuns, List Processing, Top @comment node-name, next, previous, up @chapter Practicing Evaluation @cindex Practicing evaluation @cindex Evaluation practice Before learning how to write a function definition in Emacs Lisp, it is useful to spend a little time evaluating various expressions that have already been written. These expressions will be lists with the functions as their first (and often only) element. Since some of the functions associated with buffers are both simple and interesting, we will start with those. In this section, we will evaluate a few of these. In another section, we will study the code of several other buffer-related functions, to see how they were written. @menu * 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:: @end menu @node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation @ifnottex @unnumberedsec How to Evaluate @end ifnottex @i{Whenever you give an editing command} to Emacs Lisp, such as the command to move the cursor or to scroll the screen, @i{you are evaluating an expression,} the first element of which is a function. @i{This is how Emacs works.} @cindex @samp{interactive function} defined @cindex @samp{command} defined When you type keys, you cause the Lisp interpreter to evaluate an expression and that is how you get your results. Even typing plain text involves evaluating an Emacs Lisp function, in this case, one that uses @code{self-insert-command}, which simply inserts the character you typed. The functions you evaluate by typing keystrokes are called @dfn{interactive} functions, or @dfn{commands}; how you make a function interactive will be illustrated in the chapter on how to write function definitions. @xref{Interactive, , Making a Function Interactive}. In addition to typing keyboard commands, we have seen a second way to evaluate an expression: by positioning the cursor after a list and typing @kbd{C-x C-e}. This is what we will do in the rest of this section. There are other ways to evaluate an expression as well; these will be described as we come to them. Besides being used for practicing evaluation, the functions shown in the next few sections are important in their own right. A study of these functions makes clear the distinction between buffers and files, how to switch to a buffer, and how to determine a location within it. @node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation @comment node-name, next, previous, up @section Buffer Names @findex buffer-name @findex buffer-file-name The two functions, @code{buffer-name} and @code{buffer-file-name}, show the difference between a file and a buffer. When you evaluate the following expression, @code{(buffer-name)}, the name of the buffer appears in the echo area. When you evaluate @code{(buffer-file-name)}, the name of the file to which the buffer refers appears in the echo area. Usually, the name returned by @code{(buffer-name)} is the same as the name of the file to which it refers, and the name returned by @code{(buffer-file-name)} is the full path-name of the file. A file and a buffer are two different entities. A file is information recorded permanently in the computer (unless you delete it). A buffer, on the other hand, is information inside of Emacs that will vanish at the end of the editing session (or when you kill the buffer). Usually, a buffer contains information that you have copied from a file; we say the buffer is @dfn{visiting} that file. This copy is what you work on and modify. Changes to the buffer do not change the file, until you save the buffer. When you save the buffer, the buffer is copied to the file and is thus saved permanently. @need 1250 If you are reading this in Info inside of GNU Emacs, you can evaluate each of the following expressions by positioning the cursor after it and typing @kbd{C-x C-e}. @smallexample @group (buffer-name) (buffer-file-name) @end group @end smallexample @noindent When I do this, @file{"introduction.texinfo"} is the value returned by evaluating @code{(buffer-name)}, and @file{"/gnu/work/intro/introduction.texinfo"} is the value returned by evaluating @code{(buffer-file-name)}. The former is the name of the buffer and the latter is the name of the file. (In the expressions, the parentheses tell the Lisp interpreter to treat @code{buffer-name} and @code{buffer-file-name} as functions; without the parentheses, the interpreter would attempt to evaluate the symbols as variables. @xref{Variables}.) In spite of the distinction between files and buffers, you will often find that people refer to a file when they mean a buffer and vice-versa. Indeed, most people say, ``I am editing a file,'' rather than saying, ``I am editing a buffer which I will soon save to a file.'' It is almost always clear from context what people mean. When dealing with computer programs, however, it is important to keep the distinction in mind, since the computer is not as smart as a person. @cindex Buffer, history of word The word `buffer', by the way, comes from the meaning of the word as a cushion that deadens the force of a collision. In early computers, a buffer cushioned the interaction between files and the computer's central processing unit. The drums or tapes that held a file and the central processing unit were pieces of equipment that were very different from each other, working at their own speeds, in spurts. The buffer made it possible for them to work together effectively. Eventually, the buffer grew from being an intermediary, a temporary holding place, to being the place where work is done. This transformation is rather like that of a small seaport that grew into a great city: once it was merely the place where cargo was warehoused temporarily before being loaded onto ships; then it became a business and cultural center in its own right. Not all buffers are associated with files. For example, when you start an Emacs session by typing the command @code{emacs} alone, without naming any files, Emacs will start with the @file{*scratch*} buffer on the screen. This buffer is not visiting any file. Similarly, a @file{*Help*} buffer is not associated with any file. @cindex @code{nil}, history of word If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)}, position the cursor after it, and type @kbd{C-x C-e} to evaluate the expression, the name @code{"*scratch*"} is returned and will appear in the echo area. @code{"*scratch*"} is the name of the buffer. However, if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and evaluate that, @code{nil} will appear in the echo area. @code{nil} is from the Latin word for `nothing'; in this case, it means that the @file{*scratch*} buffer is not associated with any file. (In Lisp, @code{nil} is also used to mean `false' and is a synonym for the empty list, @code{()}.) Incidentally, if you are in the @file{*scratch*} buffer and want the value returned by an expression to appear in the @file{*scratch*} buffer itself rather than in the echo area, type @kbd{C-u C-x C-e} instead of @kbd{C-x C-e}. This causes the value returned to appear after the expression. The buffer will look like this: @smallexample (buffer-name)"*scratch*" @end smallexample @noindent You cannot do this in Info since Info is read-only and it will not allow you to change the contents of the buffer. But you can do this in any buffer you can edit; and when you write code or documentation (such as this book), this feature is very useful. @node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation @comment node-name, next, previous, up @section Getting Buffers @findex current-buffer @findex other-buffer @cindex Getting a buffer The @code{buffer-name} function returns the @emph{name} of the buffer; to get the buffer @emph{itself}, a different function is needed: the @code{current-buffer} function. If you use this function in code, what you get is the buffer itself. A name and the object or entity to which the name refers are different from each other. You are not your name. You are a person to whom others refer by name. If you ask to speak to George and someone hands you a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r}, @samp{g}, and @samp{e} written on it, you might be amused, but you would not be satisfied. You do not want to speak to the name, but to the person to whom the name refers. A buffer is similar: the name of the scratch buffer is @file{*scratch*}, but the name is not the buffer. To get a buffer itself, you need to use a function such as @code{current-buffer}. However, there is a slight complication: if you evaluate @code{current-buffer} in an expression on its own, as we will do here, what you see is a printed representation of the name of the buffer without the contents of the buffer. Emacs works this way for two reasons: the buffer may be thousands of lines long---too long to be conveniently displayed; and, another buffer may have the same contents but a different name, and it is important to distinguish between them. @need 800 Here is an expression containing the function: @smallexample (current-buffer) @end smallexample @noindent If you evaluate the expression in the usual way, @file{#} appears in the echo area. The special format indicates that the buffer itself is being returned, rather than just its name. Incidentally, while you can type a number or symbol into a program, you cannot do that with the printed representation of a buffer: the only way to get a buffer itself is with a function such as @code{current-buffer}. A related function is @code{other-buffer}. This returns the most recently selected buffer other than the one you are in currently. If you have recently switched back and forth from the @file{*scratch*} buffer, @code{other-buffer} will return that buffer. @need 800 You can see this by evaluating the expression: @smallexample (other-buffer) @end smallexample @noindent You should see @file{#} appear in the echo area, or the name of whatever other buffer you switched back from most recently@footnote{Actually, by default, if the buffer from which you just switched is visible to you in another window, @code{other-buffer} will choose the most recent buffer that you cannot see; this is a subtlety that I often forget.}. @node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation @comment node-name, next, previous, up @section Switching Buffers @findex switch-to-buffer @findex set-buffer @cindex Switching to a buffer The @code{other-buffer} function actually provides a buffer when it is used as an argument to a function that requires one. We can see this by using @code{other-buffer} and @code{switch-to-buffer} to switch to a different buffer. But first, a brief introduction to the @code{switch-to-buffer} function. When you switched back and forth from Info to the @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or rather, to save typing, you probably typed just part of the name, such as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to expand to the full name; and then typed your @kbd{RET} key.} when prompted in the minibuffer for the name of the buffer to which you wanted to switch. The keystrokes, @kbd{C-x b}, cause the Lisp interpreter to evaluate the interactive function @code{switch-to-buffer}. As we said before, this is how Emacs works: different keystrokes call or run different functions. For example, @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls @code{forward-sentence}, and so on. By writing @code{switch-to-buffer} in an expression, and giving it a buffer to switch to, we can switch buffers just the way @kbd{C-x b} does. @need 1000 Here is the Lisp expression: @smallexample (switch-to-buffer (other-buffer)) @end smallexample @noindent The symbol @code{switch-to-buffer} is the first element of the list, so the Lisp interpreter will treat it as a function and carry out the instructions that are attached to it. But before doing that, the interpreter will note that @code{other-buffer} is inside parentheses and work on that symbol first. @code{other-buffer} is the first (and in this case, the only) element of this list, so the Lisp interpreter calls or runs the function. It returns another buffer. Next, the interpreter runs @code{switch-to-buffer}, passing to it, as an argument, the other buffer, which is what Emacs will switch to. If you are reading this in Info, try this now. Evaluate the expression. (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this expression will move you to your most recent other buffer that you cannot see. If you really want to go to your most recently selected buffer, even if you can still see it, you need to evaluate the following more complex expression: @smallexample (switch-to-buffer (other-buffer (current-buffer) t)) @end smallexample @c noindent In this case, the first argument to @code{other-buffer} tells it which buffer to skip---the current one---and the second argument tells @code{other-buffer} it is OK to switch to a visible buffer. In regular use, @code{switch-to-buffer} takes you to an invisible window since you would most likely use @kbd{C-x o} (@code{other-window}) to go to another visible buffer.} In the programming examples in later sections of this document, you will see the function @code{set-buffer} more often than @code{switch-to-buffer}. This is because of a difference between computer programs and humans: humans have eyes and expect to see the buffer on which they are working on their computer terminals. This is so obvious, it almost goes without saying. However, programs do not have eyes. When a computer program works on a buffer, that buffer does not need to be visible on the screen. @code{switch-to-buffer} is designed for humans and does two different things: it switches the buffer to which Emacs' attention is directed; and it switches the buffer displayed in the window to the new buffer. @code{set-buffer}, on the other hand, does only one thing: it switches the attention of the computer program to a different buffer. The buffer on the screen remains unchanged (of course, normally nothing happens there until the command finishes running). @cindex @samp{call} defined Also, we have just introduced another jargon term, the word @dfn{call}. When you evaluate a list in which the first symbol is a function, you are calling that function. The use of the term comes from the notion of the function as an entity that can do something for you if you `call' it---just as a plumber is an entity who can fix a leak if you call him or her. @node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation @comment node-name, next, previous, up @section Buffer Size and the Location of Point @cindex Size of buffer @cindex Buffer size @cindex Point location @cindex Location of point Finally, let's look at several rather simple functions, @code{buffer-size}, @code{point}, @code{point-min}, and @code{point-max}. These give information about the size of a buffer and the location of point within it. The function @code{buffer-size} tells you the size of the current buffer; that is, the function returns a count of the number of characters in the buffer. @smallexample (buffer-size) @end smallexample @noindent You can evaluate this in the usual way, by positioning the cursor after the expression and typing @kbd{C-x C-e}. @cindex @samp{point} defined In Emacs, the current position of the cursor is called @dfn{point}. The expression @code{(point)} returns a number that tells you where the cursor is located as a count of the number of characters from the beginning of the buffer up to point. @need 1250 You can see the character count for point in this buffer by evaluating the following expression in the usual way: @smallexample (point) @end smallexample @noindent As I write this, the value of @code{point} is 65724. The @code{point} function is frequently used in some of the examples later in this book. @need 1250 The value of point depends, of course, on its location within the buffer. If you evaluate point in this spot, the number will be larger: @smallexample (point) @end smallexample @noindent For me, the value of point in this location is 66043, which means that there are 319 characters (including spaces) between the two expressions. @cindex @samp{narrowing} defined The function @code{point-min} is somewhat similar to @code{point}, but it returns the value of the minimum permissible value of point in the current buffer. This is the number 1 unless @dfn{narrowing} is in effect. (Narrowing is a mechanism whereby you can restrict yourself, or a program, to operations on just a part of a buffer. @xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the function @code{point-max} returns the value of the maximum permissible value of point in the current buffer. @node Evaluation Exercise, , Buffer Size & Locations, Practicing Evaluation @section Exercise Find a file with which you are working and move towards its middle. Find its buffer name, file name, length, and your position in the file. @node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top @comment node-name, next, previous, up @chapter How To Write Function Definitions @cindex Definition writing @cindex Function definition writing @cindex Writing a function definition When the Lisp interpreter evaluates a list, it looks to see whether the first symbol on the list has a function definition attached to it; or, put another way, whether the symbol points to a function definition. If it does, the computer carries out the instructions in the definition. A symbol that has a function definition is called, simply, a function (although, properly speaking, the definition is the function and the symbol refers to it.) @menu * 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:: @end menu @node Primitive Functions, defun, Writing Defuns, Writing Defuns @ifnottex @unnumberedsec An Aside about Primitive Functions @end ifnottex @cindex Primitive functions @cindex Functions, primitive @cindex C language primitives @cindex Primitives written in C All functions are defined in terms of other functions, except for a few @dfn{primitive} functions that are written in the C programming language. When you write functions' definitions, you will write them in Emacs Lisp and use other functions as your building blocks. Some of the functions you will use will themselves be written in Emacs Lisp (perhaps by you) and some will be primitives written in C. The primitive functions are used exactly like those written in Emacs Lisp and behave like them. They are written in C so we can easily run GNU Emacs on any computer that has sufficient power and can run C. Let me re-emphasize this: when you write code in Emacs Lisp, you do not distinguish between the use of functions written in C and the use of functions written in Emacs Lisp. The difference is irrelevant. I mention the distinction only because it is interesting to know. Indeed, unless you investigate, you won't know whether an already-written function is written in Emacs Lisp or C. @node defun, Install, Primitive Functions, Writing Defuns @comment node-name, next, previous, up @section The @code{defun} Special Form @findex defun @cindex Special form of @code{defun} @cindex @samp{function definition} defined In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to it that tells the computer what to do when the function is called. This code is called the @dfn{function definition} and is created by evaluating a Lisp expression that starts with the symbol @code{defun} (which is an abbreviation for @emph{define function}). Because @code{defun} does not evaluate its arguments in the usual way, it is called a @dfn{special form}. In subsequent sections, we will look at function definitions from the Emacs source code, such as @code{mark-whole-buffer}. In this section, we will describe a simple function definition so you can see how it looks. This function definition uses arithmetic because it makes for a simple example. Some people dislike examples using arithmetic; however, if you are such a person, do not despair. Hardly any of the code we will study in the remainder of this introduction involves arithmetic or mathematics. The examples mostly involve text in one way or another. A function definition has up to five parts following the word @code{defun}: @enumerate @item The name of the symbol to which the function definition should be attached. @item A list of the arguments that will be passed to the function. If no arguments will be passed to the function, this is an empty list, @code{()}. @item Documentation describing the function. (Technically optional, but strongly recommended.) @item Optionally, an expression to make the function interactive so you can use it by typing @kbd{M-x} and then the name of the function; or by typing an appropriate key or keychord. @cindex @samp{body} defined @item The code that instructs the computer what to do: the @dfn{body} of the function definition. @end enumerate It is helpful to think of the five parts of a function definition as being organized in a template, with slots for each part: @smallexample @group (defun @var{function-name} (@var{arguments}@dots{}) "@var{optional-documentation}@dots{}" (interactive @var{argument-passing-info}) ; @r{optional} @var{body}@dots{}) @end group @end smallexample As an example, here is the code for a function that multiplies its argument by 7. (This example is not interactive. @xref{Interactive, , Making a Function Interactive}, for that information.) @smallexample @group (defun multiply-by-seven (number) "Multiply NUMBER by seven." (* 7 number)) @end group @end smallexample This definition begins with a parenthesis and the symbol @code{defun}, followed by the name of the function. @cindex @samp{argument list} defined The name of the function is followed by a list that contains the arguments that will be passed to the function. This list is called the @dfn{argument list}. In this example, the list has only one element, the symbol, @code{number}. When the function is used, the symbol will be bound to the value that is used as the argument to the function. Instead of choosing the word @code{number} for the name of the argument, I could have picked any other name. For example, I could have chosen the word @code{multiplicand}. I picked the word `number' because it tells what kind of value is intended for this slot; but I could just as well have chosen the word `multiplicand' to indicate the role that the value placed in this slot will play in the workings of the function. I could have called it @code{foogle}, but that would have been a bad choice because it would not tell humans what it means. The choice of name is up to the programmer and should be chosen to make the meaning of the function clear. Indeed, you can choose any name you wish for a symbol in an argument list, even the name of a symbol used in some other function: the name you use in an argument list is private to that particular definition. In that definition, the name refers to a different entity than any use of the same name outside the function definition. Suppose you have a nick-name `Shorty' in your family; when your family members refer to `Shorty', they mean you. But outside your family, in a movie, for example, the name `Shorty' refers to someone else. Because a name in an argument list is private to the function definition, you can change the value of such a symbol inside the body of a function without changing its value outside the function. The effect is similar to that produced by a @code{let} expression. (@xref{let, , @code{let}}.) @ignore Note also that we discuss the word `number' in two different ways: as a symbol that appears in the code, and as the name of something that will be replaced by a something else during the evaluation of the function. In the first case, @code{number} is a symbol, not a number; it happens that within the function, it is a variable who value is the number in question, but our primary interest in it is as a symbol. On the other hand, when we are talking about the function, our interest is that we will substitute a number for the word @var{number}. To keep this distinction clear, we use different typography for the two circumstances. When we talk about this function, or about how it works, we refer to this number by writing @var{number}. In the function itself, we refer to it by writing @code{number}. @end ignore The argument list is followed by the documentation string that describes the function. This is what you see when you type @w{@kbd{C-h f}} and the name of a function. Incidentally, when you write a documentation string like this, you should make the first line a complete sentence since some commands, such as @code{apropos}, print only the first line of a multi-line documentation string. Also, you should not indent the second line of a documentation string, if you have one, because that looks odd when you use @kbd{C-h f} (@code{describe-function}). The documentation string is optional, but it is so useful, it should be included in almost every function you write. @findex * @r{(multiplication)} The third line of the example consists of the body of the function definition. (Most functions' definitions, of course, are longer than this.) In this function, the body is the list, @code{(* 7 number)}, which says to multiply the value of @var{number} by 7. (In Emacs Lisp, @code{*} is the function for multiplication, just as @code{+} is the function for addition.) When you use the @code{multiply-by-seven} function, the argument @code{number} evaluates to the actual number you want used. Here is an example that shows how @code{multiply-by-seven} is used; but don't try to evaluate this yet! @smallexample (multiply-by-seven 3) @end smallexample @noindent The symbol @code{number}, specified in the function definition in the next section, is given or ``bound to'' the value 3 in the actual use of the function. Note that although @code{number} was inside parentheses in the function definition, the argument passed to the @code{multiply-by-seven} function is not in parentheses. The parentheses are written in the function definition so the computer can figure out where the argument list ends and the rest of the function definition begins. If you evaluate this example, you are likely to get an error message. (Go ahead, try it!) This is because we have written the function definition, but not yet told the computer about the definition---we have not yet installed (or `loaded') the function definition in Emacs. Installing a function is the process that tells the Lisp interpreter the definition of the function. Installation is described in the next section. @node Install, Interactive, defun, Writing Defuns @comment node-name, next, previous, up @section Install a Function Definition @cindex Install a Function Definition @cindex Definition installation @cindex Function definition installation If you are reading this inside of Info in Emacs, you can try out the @code{multiply-by-seven} function by first evaluating the function definition and then evaluating @code{(multiply-by-seven 3)}. A copy of the function definition follows. Place the cursor after the last parenthesis of the function definition and type @kbd{C-x C-e}. When you do this, @code{multiply-by-seven} will appear in the echo area. (What this means is that when a function definition is evaluated, the value it returns is the name of the defined function.) At the same time, this action installs the function definition. @smallexample @group (defun multiply-by-seven (number) "Multiply NUMBER by seven." (* 7 number)) @end group @end smallexample @noindent By evaluating this @code{defun}, you have just installed @code{multiply-by-seven} in Emacs. The function is now just as much a part of Emacs as @code{forward-word} or any other editing function you use. (@code{multiply-by-seven} will stay installed until you quit Emacs. To reload code automatically whenever you start Emacs, see @ref{Permanent Installation, , Installing Code Permanently}.) @menu * Effect of installation:: * Change a defun:: How to change a function definition. @end menu @node Effect of installation, Change a defun, Install, Install @ifnottex @unnumberedsubsec The effect of installation @end ifnottex You can see the effect of installing @code{multiply-by-seven} by evaluating the following sample. Place the cursor after the following expression and type @kbd{C-x C-e}. The number 21 will appear in the echo area. @smallexample (multiply-by-seven 3) @end smallexample If you wish, you can read the documentation for the function by typing @kbd{C-h f} (@code{describe-function}) and then the name of the function, @code{multiply-by-seven}. When you do this, a @file{*Help*} window will appear on your screen that says: @smallexample @group multiply-by-seven: Multiply NUMBER by seven. @end group @end smallexample @noindent (To return to a single window on your screen, type @kbd{C-x 1}.) @node Change a defun, , Effect of installation, Install @comment node-name, next, previous, up @subsection Change a Function Definition @cindex Changing a function definition @cindex Function definition, how to change @cindex Definition, how to change If you want to change the code in @code{multiply-by-seven}, just rewrite it. To install the new version in place of the old one, evaluate the function definition again. This is how you modify code in Emacs. It is very simple. As an example, you can change the @code{multiply-by-seven} function to add the number to itself seven times instead of multiplying the number by seven. It produces the same answer, but by a different path. At the same time, we will add a comment to the code; a comment is text that the Lisp interpreter ignores, but that a human reader may find useful or enlightening. The comment is that this is the ``second version''. @smallexample @group (defun multiply-by-seven (number) ; @r{Second version.} "Multiply NUMBER by seven." (+ number number number number number number number)) @end group @end smallexample @cindex Comments in Lisp code The comment follows a semicolon, @samp{;}. In Lisp, everything on a line that follows a semicolon is a comment. The end of the line is the end of the comment. To stretch a comment over two or more lines, begin each line with a semicolon. @xref{Beginning a .emacs File, , Beginning a @file{.emacs} File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp Reference Manual}, for more about comments. You can install this version of the @code{multiply-by-seven} function by evaluating it in the same way you evaluated the first function: place the cursor after the last parenthesis and type @kbd{C-x C-e}. In summary, this is how you write code in Emacs Lisp: you write a function; install it; test it; and then make fixes or enhancements and install it again. @node Interactive, Interactive Options, Install, Writing Defuns @comment node-name, next, previous, up @section Make a Function Interactive @cindex Interactive functions @findex interactive You make a function interactive by placing a list that begins with the special form @code{interactive} immediately after the documentation. A user can invoke an interactive function by typing @kbd{M-x} and then the name of the function; or by typing the keys to which it is bound, for example, by typing @kbd{C-n} for @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}. Interestingly, when you call an interactive function interactively, the value returned is not automatically displayed in the echo area. This is because you often call an interactive function for its side effects, such as moving forward by a word or line, and not for the value returned. If the returned value were displayed in the echo area each time you typed a key, it would be very distracting. @menu * Interactive multiply-by-seven:: An overview. * multiply-by-seven in detail:: The interactive version. @end menu @node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive @ifnottex @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview @end ifnottex Both the use of the special form @code{interactive} and one way to display a value in the echo area can be illustrated by creating an interactive version of @code{multiply-by-seven}. @need 1250 Here is the code: @smallexample @group (defun multiply-by-seven (number) ; @r{Interactive version.} "Multiply NUMBER by seven." (interactive "p") (message "The result is %d" (* 7 number))) @end group @end smallexample @noindent You can install this code by placing your cursor after it and typing @kbd{C-x C-e}. The name of the function will appear in your echo area. Then, you can use this code by typing @kbd{C-u} and a number and then typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase @samp{The result is @dots{}} followed by the product will appear in the echo area. Speaking more generally, you invoke a function like this in either of two ways: @enumerate @item By typing a prefix argument that contains the number to be passed, and then typing @kbd{M-x} and the name of the function, as with @kbd{C-u 3 M-x forward-sentence}; or, @item By typing whatever key or keychord the function is bound to, as with @kbd{C-u 3 M-e}. @end enumerate @noindent Both the examples just mentioned work identically to move point forward three sentences. (Since @code{multiply-by-seven} is not bound to a key, it could not be used as an example of key binding.) (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command to a key.) A prefix argument is passed to an interactive function by typing the @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you type @kbd{C-u} without a number, it defaults to 4). @node multiply-by-seven in detail, , Interactive multiply-by-seven, Interactive @comment node-name, next, previous, up @subsection An Interactive @code{multiply-by-seven} Let's look at the use of the special form @code{interactive} and then at the function @code{message} in the interactive version of @code{multiply-by-seven}. You will recall that the function definition looks like this: @smallexample @group (defun multiply-by-seven (number) ; @r{Interactive version.} "Multiply NUMBER by seven." (interactive "p") (message "The result is %d" (* 7 number))) @end group @end smallexample In this function, the expression, @code{(interactive "p")}, is a list of two elements. The @code{"p"} tells Emacs to pass the prefix argument to the function and use its value for the argument of the function. @need 1000 The argument will be a number. This means that the symbol @code{number} will be bound to a number in the line: @smallexample (message "The result is %d" (* 7 number)) @end smallexample @need 1250 @noindent For example, if your prefix argument is 5, the Lisp interpreter will evaluate the line as if it were: @smallexample (message "The result is %d" (* 7 5)) @end smallexample @noindent (If you are reading this in GNU Emacs, you can evaluate this expression yourself.) First, the interpreter will evaluate the inner list, which is @code{(* 7 5)}. This returns a value of 35. Next, it will evaluate the outer list, passing the values of the second and subsequent elements of the list to the function @code{message}. As we have seen, @code{message} is an Emacs Lisp function especially designed for sending a one line message to a user. (@xref{message, , The @code{message} function}.) In summary, the @code{message} function prints its first argument in the echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or @samp{%c}. When it sees one of these control sequences, the function looks to the second and subsequent arguments and prints the value of the argument in the location in the string where the control sequence is located. In the interactive @code{multiply-by-seven} function, the control string is @samp{%d}, which requires a number, and the value returned by evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35 is printed in place of the @samp{%d} and the message is @samp{The result is 35}. (Note that when you call the function @code{multiply-by-seven}, the message is printed without quotes, but when you call @code{message}, the text is printed in double quotes. This is because the value returned by @code{message} is what appears in the echo area when you evaluate an expression whose first element is @code{message}; but when embedded in a function, @code{message} prints the text as a side effect without quotes.) @node Interactive Options, Permanent Installation, Interactive, Writing Defuns @comment node-name, next, previous, up @section Different Options for @code{interactive} @cindex Options for @code{interactive} @cindex Interactive options In the example, @code{multiply-by-seven} used @code{"p"} as the argument to @code{interactive}. This argument told Emacs to interpret your typing either @kbd{C-u} followed by a number or @key{META} followed by a number as a command to pass that number to the function as its argument. Emacs has more than twenty characters predefined for use with @code{interactive}. In almost every case, one of these options will enable you to pass the right information interactively to a function. (@xref{Interactive Codes, , Code Characters for @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.) @need 1250 For example, the character @samp{r} causes Emacs to pass the beginning and end of the region (the current values of point and mark) to the function as two separate arguments. It is used as follows: @smallexample (interactive "r") @end smallexample On the other hand, a @samp{B} tells Emacs to ask for the name of a buffer that will be passed to the function. When it sees a @samp{B}, Emacs will ask for the name by prompting the user in the minibuffer, using a string that follows the @samp{B}, as in @code{"BAppend to buffer:@: "}. Not only will Emacs prompt for the name, but Emacs will complete the name if you type enough of it and press @key{TAB}. A function with two or more arguments can have information passed to each argument by adding parts to the string that follows @code{interactive}. When you do this, the information is passed to each argument in the same order it is specified in the @code{interactive} list. In the string, each part is separated from the next part by a @samp{\n}, which is a newline. For example, you could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an @samp{r}. This would cause Emacs to pass the values of point and mark to the function as well as prompt you for the buffer---three arguments in all. In this case, the function definition would look like the following, where @code{buffer}, @code{start}, and @code{end} are the symbols to which @code{interactive} binds the buffer and the current values of the beginning and ending of the region: @smallexample @group (defun @var{name-of-function} (buffer start end) "@var{documentation}@dots{}" (interactive "BAppend to buffer:@: \nr") @var{body-of-function}@dots{}) @end group @end smallexample @noindent (The space after the colon in the prompt makes it look better when you are prompted. The @code{append-to-buffer} function looks exactly like this. @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.) If a function does not have arguments, then @code{interactive} does not require any. Such a function contains the simple expression @code{(interactive)}. The @code{mark-whole-buffer} function is like this. Alternatively, if the special letter-codes are not right for your application, you can pass your own arguments to @code{interactive} as a list. @xref{interactive, , Using @code{Interactive}, elisp, The GNU Emacs Lisp Reference Manual}, for more information about this advanced technique. @node Permanent Installation, let, Interactive Options, Writing Defuns @comment node-name, next, previous, up @section Install Code Permanently @cindex Install code permanently @cindex Permanent code installation @cindex Code installation When you install a function definition by evaluating it, it will stay installed until you quit Emacs. The next time you start a new session of Emacs, the function will not be installed unless you evaluate the function definition again. At some point, you may want to have code installed automatically whenever you start a new session of Emacs. There are several ways of doing this: @itemize @bullet @item If you have code that is just for yourself, you can put the code for the function definition in your @file{.emacs} initialization file. When you start Emacs, your @file{.emacs} file is automatically evaluated and all the function definitions within it are installed. @xref{Emacs Initialization, , Your @file{.emacs} File}. @item Alternatively, you can put the function definitions that you want installed in one or more files of their own and use the @code{load} function to cause Emacs to evaluate and thereby install each of the functions in the files. @xref{Loading Files, , Loading Files}. @item On the other hand, if you have code that your whole site will use, it is usual to put it in a file called @file{site-init.el} that is loaded when Emacs is built. This makes the code available to everyone who uses your machine. (See the @file{INSTALL} file that is part of the Emacs distribution.) @end itemize Finally, if you have code that everyone who uses Emacs may want, you can post it on a computer network or send a copy to the Free Software Foundation. (When you do this, please license the code and its documentation under a license that permits other people to run, copy, study, modify, and redistribute the code and which protects you from having your work taken from you.) If you send a copy of your code to the Free Software Foundation, and properly protect yourself and others, it may be included in the next release of Emacs. In large part, this is how Emacs has grown over the past years, by donations. @node let, if, Permanent Installation, Writing Defuns @comment node-name, next, previous, up @section @code{let} @findex let The @code{let} expression is a special form in Lisp that you will need to use in most function definitions. @code{let} is used to attach or bind a symbol to a value in such a way that the Lisp interpreter will not confuse the variable with a variable of the same name that is not part of the function. To understand why the @code{let} special form is necessary, consider the situation in which you own a home that you generally refer to as `the house', as in the sentence, ``The house needs painting.'' If you are visiting a friend and your host refers to `the house', he is likely to be referring to @emph{his} house, not yours, that is, to a different house. If your friend is referring to his house and you think he is referring to your house, you may be in for some confusion. The same thing could happen in Lisp if a variable that is used inside of one function has the same name as a variable that is used inside of another function, and the two are not intended to refer to the same value. The @code{let} special form prevents this kind of confusion. @menu * Prevent confusion:: * Parts of let Expression:: * Sample let Expression:: * Uninitialized let Variables:: @end menu @node Prevent confusion, Parts of let Expression, let, let @ifnottex @unnumberedsubsec @code{let} Prevents Confusion @end ifnottex @cindex @samp{local variable} defined The @code{let} special form prevents confusion. @code{let} creates a name for a @dfn{local variable} that overshadows any use of the same name outside the @code{let} expression. This is like understanding that whenever your host refers to `the house', he means his house, not yours. (Symbols used in argument lists work the same way. @xref{defun, , The @code{defun} Special Form}.) Local variables created by a @code{let} expression retain their value @emph{only} within the @code{let} expression itself (and within expressions called within the @code{let} expression); the local variables have no effect outside the @code{let} expression. Another way to think about @code{let} is that it is like a @code{setq} that is temporary and local. The values set by @code{let} are automatically undone when the @code{let} is finished. The setting only affects expressions that are inside the bounds of the @code{let} expression. In computer science jargon, we would say ``the binding of a symbol is visible only in functions called in the @code{let} form; in Emacs Lisp, scoping is dynamic, not lexical.'' @code{let} can create more than one variable at once. Also, @code{let} gives each variable it creates an initial value, either a value specified by you, or @code{nil}. (In the jargon, this is called `binding the variable to the value'.) After @code{let} has created and bound the variables, it executes the code in the body of the @code{let}, and returns the value of the last expression in the body, as the value of the whole @code{let} expression. (`Execute' is a jargon term that means to evaluate a list; it comes from the use of the word meaning `to give practical effect to' (@cite{Oxford English Dictionary}). Since you evaluate an expression to perform an action, `execute' has evolved as a synonym to `evaluate'.) @node Parts of let Expression, Sample let Expression, Prevent confusion, let @comment node-name, next, previous, up @subsection The Parts of a @code{let} Expression @cindex @code{let} expression, parts of @cindex Parts of @code{let} expression @cindex @samp{varlist} defined A @code{let} expression is a list of three parts. The first part is the symbol @code{let}. The second part is a list, called a @dfn{varlist}, each element of which is either a symbol by itself or a two-element list, the first element of which is a symbol. The third part of the @code{let} expression is the body of the @code{let}. The body usually consists of one or more lists. @need 800 A template for a @code{let} expression looks like this: @smallexample (let @var{varlist} @var{body}@dots{}) @end smallexample @noindent The symbols in the varlist are the variables that are given initial values by the @code{let} special form. Symbols by themselves are given the initial value of @code{nil}; and each symbol that is the first element of a two-element list is bound to the value that is returned when the Lisp interpreter evaluates the second element. Thus, a varlist might look like this: @code{(thread (needles 3))}. In this case, in a @code{let} expression, Emacs binds the symbol @code{thread} to an initial value of @code{nil}, and binds the symbol @code{needles} to an initial value of 3. When you write a @code{let} expression, what you do is put the appropriate expressions in the slots of the @code{let} expression template. If the varlist is composed of two-element lists, as is often the case, the template for the @code{let} expression looks like this: @smallexample @group (let ((@var{variable} @var{value}) (@var{variable} @var{value}) @dots{}) @var{body}@dots{}) @end group @end smallexample @node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let @comment node-name, next, previous, up @subsection Sample @code{let} Expression @cindex Sample @code{let} expression @cindex @code{let} expression sample The following expression creates and gives initial values to the two variables @code{zebra} and @code{tiger}. The body of the @code{let} expression is a list which calls the @code{message} function. @smallexample @group (let ((zebra 'stripes) (tiger 'fierce)) (message "One kind of animal has %s and another is %s." zebra tiger)) @end group @end smallexample Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}. The two variables are @code{zebra} and @code{tiger}. Each variable is the first element of a two-element list and each value is the second element of its two-element list. In the varlist, Emacs binds the variable @code{zebra} to the value @code{stripes}, and binds the variable @code{tiger} to the value @code{fierce}. In this example, both values are symbols preceded by a quote. The values could just as well have been another list or a string. The body of the @code{let} follows after the list holding the variables. In this example, the body is a list that uses the @code{message} function to print a string in the echo area. @need 1500 You may evaluate the example in the usual fashion, by placing the cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do this, the following will appear in the echo area: @smallexample "One kind of animal has stripes and another is fierce." @end smallexample As we have seen before, the @code{message} function prints its first argument, except for @samp{%s}. In this example, the value of the variable @code{zebra} is printed at the location of the first @samp{%s} and the value of the variable @code{tiger} is printed at the location of the second @samp{%s}. @node Uninitialized let Variables, , Sample let Expression, let @comment node-name, next, previous, up @subsection Uninitialized Variables in a @code{let} Statement @cindex Uninitialized @code{let} variables @cindex @code{let} variables uninitialized If you do not bind the variables in a @code{let} statement to specific initial values, they will automatically be bound to an initial value of @code{nil}, as in the following expression: @smallexample @group (let ((birch 3) pine fir (oak 'some)) (message "Here are %d variables with %s, %s, and %s value." birch pine fir oak)) @end group @end smallexample @noindent Here, the varlist is @code{((birch 3) pine fir (oak 'some))}. @need 1250 If you evaluate this expression in the usual way, the following will appear in your echo area: @smallexample "Here are 3 variables with nil, nil, and some value." @end smallexample @noindent In this example, Emacs binds the symbol @code{birch} to the number 3, binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds the symbol @code{oak} to the value @code{some}. Note that in the first part of the @code{let}, the variables @code{pine} and @code{fir} stand alone as atoms that are not surrounded by parentheses; this is because they are being bound to @code{nil}, the empty list. But @code{oak} is bound to @code{some} and so is a part of the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the number 3 and so is in a list with that number. (Since a number evaluates to itself, the number does not need to be quoted. Also, the number is printed in the message using a @samp{%d} rather than a @samp{%s}.) The four variables as a group are put into a list to delimit them from the body of the @code{let}. @node if, else, let, Writing Defuns @comment node-name, next, previous, up @section The @code{if} Special Form @findex if @cindex Conditional with @code{if} A third special form, in addition to @code{defun} and @code{let}, is the conditional @code{if}. This form is used to instruct the computer to make decisions. You can write function definitions without using @code{if}, but it is used often enough, and is important enough, to be included here. It is used, for example, in the code for the function @code{beginning-of-buffer}. The basic idea behind an @code{if}, is that ``@emph{if} a test is true, @emph{then} an expression is evaluated.'' If the test is not true, the expression is not evaluated. For example, you might make a decision such as, ``if it is warm and sunny, then go to the beach!'' @menu * if in more detail:: * type-of-animal in detail:: An example of an @code{if} expression. @end menu @node if in more detail, type-of-animal in detail, if, if @ifnottex @unnumberedsubsec @code{if} in more detail @end ifnottex @cindex @samp{if-part} defined @cindex @samp{then-part} defined An @code{if} expression written in Lisp does not use the word `then'; the test and the action are the second and third elements of the list whose first element is @code{if}. Nonetheless, the test part of an @code{if} expression is often called the @dfn{if-part} and the second argument is often called the @dfn{then-part}. Also, when an @code{if} expression is written, the true-or-false-test is usually written on the same line as the symbol @code{if}, but the action to carry out if the test is true, the ``then-part'', is written on the second and subsequent lines. This makes the @code{if} expression easier to read. @smallexample @group (if @var{true-or-false-test} @var{action-to-carry-out-if-test-is-true}) @end group @end smallexample @noindent The true-or-false-test will be an expression that is evaluated by the Lisp interpreter. Here is an example that you can evaluate in the usual manner. The test is whether the number 5 is greater than the number 4. Since it is, the message @samp{5 is greater than 4!} will be printed. @smallexample @group (if (> 5 4) ; @r{if-part} (message "5 is greater than 4!")) ; @r{then-part} @end group @end smallexample @noindent (The function @code{>} tests whether its first argument is greater than its second argument and returns true if it is.) @findex > (greater than) Of course, in actual use, the test in an @code{if} expression will not be fixed for all time as it is by the expression @code{(> 5 4)}. Instead, at least one of the variables used in the test will be bound to a value that is not known ahead of time. (If the value were known ahead of time, we would not need to run the test!) For example, the value may be bound to an argument of a function definition. In the following function definition, the character of the animal is a value that is passed to the function. If the value bound to @code{characteristic} is @code{fierce}, then the message, @samp{It's a tiger!} will be printed; otherwise, @code{nil} will be returned. @smallexample @group (defun type-of-animal (characteristic) "Print message in echo area depending on CHARACTERISTIC. If the CHARACTERISTIC is the symbol `fierce', then warn of a tiger." (if (equal characteristic 'fierce) (message "It's a tiger!"))) @end group @end smallexample @need 1500 @noindent If you are reading this inside of GNU Emacs, you can evaluate the function definition in the usual way to install it in Emacs, and then you can evaluate the following two expressions to see the results: @smallexample @group (type-of-animal 'fierce) (type-of-animal 'zebra) @end group @end smallexample @c Following sentences rewritten to prevent overfull hbox. @noindent When you evaluate @code{(type-of-animal 'fierce)}, you will see the following message printed in the echo area: @code{"It's a tiger!"}; and when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil} printed in the echo area. @node type-of-animal in detail, , if in more detail, if @comment node-name, next, previous, up @subsection The @code{type-of-animal} Function in Detail Let's look at the @code{type-of-animal} function in detail. The function definition for @code{type-of-animal} was written by filling the slots of two templates, one for a function definition as a whole, and a second for an @code{if} expression. @need 1250 The template for every function that is not interactive is: @smallexample @group (defun @var{name-of-function} (@var{argument-list}) "@var{documentation}@dots{}" @var{body}@dots{}) @end group @end smallexample @need 800 The parts of the function that match this template look like this: @smallexample @group (defun type-of-animal (characteristic) "Print message in echo area depending on CHARACTERISTIC. If the CHARACTERISTIC is the symbol `fierce', then warn of a tiger." @var{body: the} @code{if} @var{expression}) @end group @end smallexample The name of function is @code{type-of-animal}; it is passed the value of one argument. The argument list is followed by a multi-line documentation string. The documentation string is included in the example because it is a good habit to write documentation string for every function definition. The body of the function definition consists of the @code{if} expression. @need 800 The template for an @code{if} expression looks like this: @smallexample @group (if @var{true-or-false-test} @var{action-to-carry-out-if-the-test-returns-true}) @end group @end smallexample @need 1250 In the @code{type-of-animal} function, the code for the @code{if} looks like this: @smallexample @group (if (equal characteristic 'fierce) (message "It's a tiger!"))) @end group @end smallexample @need 800 Here, the true-or-false-test is the expression: @smallexample (equal characteristic 'fierce) @end smallexample @noindent In Lisp, @code{equal} is a function that determines whether its first argument is equal to its second argument. The second argument is the quoted symbol @code{'fierce} and the first argument is the value of the symbol @code{characteristic}---in other words, the argument passed to this function. In the first exercise of @code{type-of-animal}, the argument @code{fierce} is passed to @code{type-of-animal}. Since @code{fierce} is equal to @code{fierce}, the expression, @code{(equal characteristic 'fierce)}, returns a value of true. When this happens, the @code{if} evaluates the second argument or then-part of the @code{if}: @code{(message "It's tiger!")}. On the other hand, in the second exercise of @code{type-of-animal}, the argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra} is not equal to @code{fierce}, so the then-part is not evaluated and @code{nil} is returned by the @code{if} expression. @node else, Truth & Falsehood, if, Writing Defuns @comment node-name, next, previous, up @section If--then--else Expressions @cindex Else An @code{if} expression may have an optional third argument, called the @dfn{else-part}, for the case when the true-or-false-test returns false. When this happens, the second argument or then-part of the overall @code{if} expression is @emph{not} evaluated, but the third or else-part @emph{is} evaluated. You might think of this as the cloudy day alternative for the decision `if it is warm and sunny, then go to the beach, else read a book!''. The word ``else'' is not written in the Lisp code; the else-part of an @code{if} expression comes after the then-part. In the written Lisp, the else-part is usually written to start on a line of its own and is indented less than the then-part: @smallexample @group (if @var{true-or-false-test} @var{action-to-carry-out-if-the-test-returns-true} @var{action-to-carry-out-if-the-test-returns-false}) @end group @end smallexample For example, the following @code{if} expression prints the message @samp{4 is not greater than 5!} when you evaluate it in the usual way: @smallexample @group (if (> 4 5) ; @r{if-part} (message "5 is greater than 4!") ; @r{then-part} (message "4 is not greater than 5!")) ; @r{else-part} @end group @end smallexample @noindent Note that the different levels of indentation make it easy to distinguish the then-part from the else-part. (GNU Emacs has several commands that automatically indent @code{if} expressions correctly. @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.) We can extend the @code{type-of-animal} function to include an else-part by simply incorporating an additional part to the @code{if} expression. @need 1500 You can see the consequences of doing this if you evaluate the following version of the @code{type-of-animal} function definition to install it and then evaluate the two subsequent expressions to pass different arguments to the function. @smallexample @group (defun type-of-animal (characteristic) ; @r{Second version.} "Print message in echo area depending on CHARACTERISTIC. If the CHARACTERISTIC is the symbol `fierce', then warn of a tiger; else say it's not fierce." (if (equal characteristic 'fierce) (message "It's a tiger!") (message "It's not fierce!"))) @end group @end smallexample @sp 1 @smallexample @group (type-of-animal 'fierce) (type-of-animal 'zebra) @end group @end smallexample @c Following sentence rewritten to prevent overfull hbox. @noindent When you evaluate @code{(type-of-animal 'fierce)}, you will see the following message printed in the echo area: @code{"It's a tiger!"}; but when you evaluate @code{(type-of-animal 'zebra)}, you will see @code{"It's not fierce!"}. (Of course, if the @var{characteristic} were @code{ferocious}, the message @code{"It's not fierce!"} would be printed; and it would be misleading! When you write code, you need to take into account the possibility that some such argument will be tested by the @code{if} and write your program accordingly.) @node Truth & Falsehood, save-excursion, else, Writing Defuns @comment node-name, next, previous, up @section Truth and Falsehood in Emacs Lisp @cindex Truth and falsehood in Emacs Lisp @cindex Falsehood and truth in Emacs Lisp @findex nil There is an important aspect to the truth test in an @code{if} expression. So far, we have spoken of `true' and `false' as values of predicates as if they were new kinds of Emacs Lisp objects. In fact, `false' is just our old friend @code{nil}. Anything else---anything at all---is `true'. The expression that tests for truth is interpreted as @dfn{true} if the result of evaluating it is a value that is not @code{nil}. In other words, the result of the test is considered true if the value returned is a number such as 47, a string such as @code{"hello"}, or a symbol (other than @code{nil}) such as @code{flowers}, or a list, or even a buffer! @menu * nil explained:: @code{nil} has two meanings. @end menu @node nil explained, , Truth & Falsehood, Truth & Falsehood @ifnottex @unnumberedsubsec An explanation of @code{nil} @end ifnottex Before illustrating a test for truth, we need an explanation of @code{nil}. In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the empty list. Second, it means false and is the value returned when a true-or-false-test tests false. @code{nil} can be written as an empty list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is concerned, @code{()} and @code{nil} are the same. Humans, however, tend to use @code{nil} for false and @code{()} for the empty list. In Emacs Lisp, any value that is not @code{nil}---is not the empty list---is considered true. This means that if an evaluation returns something that is not an empty list, an @code{if} expression will test true. For example, if a number is put in the slot for the test, it will be evaluated and will return itself, since that is what numbers do when evaluated. In this conditional, the @code{if} expression will test true. The expression tests false only when @code{nil}, an empty list, is returned by evaluating the expression. You can see this by evaluating the two expressions in the following examples. In the first example, the number 4 is evaluated as the test in the @code{if} expression and returns itself; consequently, the then-part of the expression is evaluated and returned: @samp{true} appears in the echo area. In the second example, the @code{nil} indicates false; consequently, the else-part of the expression is evaluated and returned: @samp{false} appears in the echo area. @smallexample @group (if 4 'true 'false) @end group @group (if nil 'true 'false) @end group @end smallexample @need 1250 Incidentally, if some other useful value is not available for a test that returns true, then the Lisp interpreter will return the symbol @code{t} for true. For example, the expression @code{(> 5 4)} returns @code{t} when evaluated, as you can see by evaluating it in the usual way: @smallexample (> 5 4) @end smallexample @need 1250 @noindent On the other hand, this function returns @code{nil} if the test is false. @smallexample (> 4 5) @end smallexample @node save-excursion, Review, Truth & Falsehood, Writing Defuns @comment node-name, next, previous, up @section @code{save-excursion} @findex save-excursion @cindex Region, what it is @cindex Preserving point, mark, and buffer @cindex Point, mark, buffer preservation @findex point @findex mark The @code{save-excursion} function is the fourth and final special form that we will discuss in this chapter. In Emacs Lisp programs used for editing, the @code{save-excursion} function is very common. It saves the location of point and mark, executes the body of the function, and then restores point and mark to their previous positions if their locations were changed. Its primary purpose is to keep the user from being surprised and disturbed by unexpected movement of point or mark. @menu * Point and mark:: A review of various locations. * Template for save-excursion:: @end menu @node Point and mark, Template for save-excursion, save-excursion, save-excursion @ifnottex @unnumberedsubsec Point and Mark @end ifnottex Before discussing @code{save-excursion}, however, it may be useful first to review what point and mark are in GNU Emacs. @dfn{Point} is the current location of the cursor. Wherever the cursor is, that is point. More precisely, on terminals where the cursor appears to be on top of a character, point is immediately before the character. In Emacs Lisp, point is an integer. The first character in a buffer is number one, the second is number two, and so on. The function @code{point} returns the current position of the cursor as a number. Each buffer has its own value for point. The @dfn{mark} is another position in the buffer; its value can be set with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If a mark has been set, you can use the command @kbd{C-x C-x} (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark and set the mark to be the previous position of point. In addition, if you set another mark, the position of the previous mark is saved in the mark ring. Many mark positions can be saved this way. You can jump the cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more times. The part of the buffer between point and mark is called @dfn{the region}. Numerous commands work on the region, including @code{center-region}, @code{count-lines-region}, @code{kill-region}, and @code{print-region}. The @code{save-excursion} special form saves the locations of point and mark and restores those positions after the code within the body of the special form is evaluated by the Lisp interpreter. Thus, if point were in the beginning of a piece of text and some code moved point to the end of the buffer, the @code{save-excursion} would put point back to where it was before, after the expressions in the body of the function were evaluated. In Emacs, a function frequently moves point as part of its internal workings even though a user would not expect this. For example, @code{count-lines-region} moves point. To prevent the user from being bothered by jumps that are both unexpected and (from the user's point of view) unnecessary, @code{save-excursion} is often used to keep point and mark in the location expected by the user. The use of @code{save-excursion} is good housekeeping. To make sure the house stays clean, @code{save-excursion} restores the values of point and mark even if something goes wrong in the code inside of it (or, to be more precise and to use the proper jargon, ``in case of abnormal exit''). This feature is very helpful. In addition to recording the values of point and mark, @code{save-excursion} keeps track of the current buffer, and restores it, too. This means you can write code that will change the buffer and have @code{save-excursion} switch you back to the original buffer. This is how @code{save-excursion} is used in @code{append-to-buffer}. (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.) @node Template for save-excursion, , Point and mark, save-excursion @comment node-name, next, previous, up @subsection Template for a @code{save-excursion} Expression @need 800 The template for code using @code{save-excursion} is simple: @smallexample @group (save-excursion @var{body}@dots{}) @end group @end smallexample @noindent The body of the function is one or more expressions that will be evaluated in sequence by the Lisp interpreter. If there is more than one expression in the body, the value of the last one will be returned as the value of the @code{save-excursion} function. The other expressions in the body are evaluated only for their side effects; and @code{save-excursion} itself is used only for its side effect (which is restoring the positions of point and mark). @need 1250 In more detail, the template for a @code{save-excursion} expression looks like this: @smallexample @group (save-excursion @var{first-expression-in-body} @var{second-expression-in-body} @var{third-expression-in-body} @dots{} @var{last-expression-in-body}) @end group @end smallexample @noindent An expression, of course, may be a symbol on its own or a list. In Emacs Lisp code, a @code{save-excursion} expression often occurs within the body of a @code{let} expression. It looks like this: @smallexample @group (let @var{varlist} (save-excursion @var{body}@dots{})) @end group @end smallexample @node Review, defun Exercises, save-excursion, Writing Defuns @comment node-name, next, previous, up @section Review In the last few chapters we have introduced a fair number of functions and special forms. Here they are described in brief, along with a few similar functions that have not been mentioned yet. @table @code @item eval-last-sexp Evaluate the last symbolic expression before the current location of point. The value is printed in the echo area unless the function is invoked with an argument; in that case, the output is printed in the current buffer. This command is normally bound to @kbd{C-x C-e}. @item defun Define function. This special form has up to five parts: the name, a template for the arguments that will be passed to the function, documentation, an optional interactive declaration, and the body of the definition. @need 1250 For example: @smallexample @group (defun back-to-indentation () "Move point to first visible character on line." (interactive) (beginning-of-line 1) (skip-chars-forward " \t")) @end group @end smallexample @item interactive Declare to the interpreter that the function can be used interactively. This special form may be followed by a string with one or more parts that pass the information to the arguments of the function, in sequence. These parts may also tell the interpreter to prompt for information. Parts of the string are separated by newlines, @samp{\n}. Common code characters are: @table @code @item b The name of an existing buffer. @item f The name of an existing file. @item p The numeric prefix argument. (Note that this `p' is lower case.) @item r Point and the mark, as two numeric arguments, smallest first. This is the only code letter that specifies two successive arguments rather than one. @end table @xref{Interactive Codes, , Code Characters for @samp{interactive}, elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of code characters. @item let Declare that a list of variables is for use within the body of the @code{let} and give them an initial value, either @code{nil} or a specified value; then evaluate the rest of the expressions in the body of the @code{let} and return the value of the last one. Inside the body of the @code{let}, the Lisp interpreter does not see the values of the variables of the same names that are bound outside of the @code{let}. @need 1250 For example, @smallexample @group (let ((foo (buffer-name)) (bar (buffer-size))) (message "This buffer is %s and has %d characters." foo bar)) @end group @end smallexample @item save-excursion Record the values of point and mark and the current buffer before evaluating the body of this special form. Restore the values of point and mark and buffer afterward. @need 1250 For example, @smallexample @group (message "We are %d characters into this buffer." (- (point) (save-excursion (goto-char (point-min)) (point)))) @end group @end smallexample @item if Evaluate the first argument to the function; if it is true, evaluate the second argument; else evaluate the third argument, if there is one. The @code{if} special form is called a @dfn{conditional}. There are other conditionals in Emacs Lisp, but @code{if} is perhaps the most commonly used. @need 1250 For example, @smallexample @group (if (string-equal (number-to-string 21) (substring (emacs-version) 10 12)) (message "This is version 21 Emacs") (message "This is not version 21 Emacs")) @end group @end smallexample @item equal @itemx eq Test whether two objects are the same. @code{equal} uses one meaning of the word `same' and @code{eq} uses another: @code{equal} returns true if the two objects have a similar structure and contents, such as two copies of the same book. On the other hand, @code{eq}, returns true if both arguments are actually the same object. @findex equal @findex eq @need 1250 @item < @itemx > @itemx <= @itemx >= The @code{<} function tests whether its first argument is smaller than its second argument. A corresponding function, @code{>}, tests whether the first argument is greater than the second. Likewise, @code{<=} tests whether the first argument is less than or equal to the second and @code{>=} tests whether the first argument is greater than or equal to the second. In all cases, both arguments must be numbers or markers (markers indicate positions in buffers). @item string< @itemx string-lessp @itemx string= @itemx string-equal The @code{string-lessp} function tests whether its first argument is smaller than the second argument. A shorter, alternative name for the same function (a @code{defalias}) is @code{string<}. The arguments to @code{string-lessp} must be strings or symbols; the ordering is lexicographic, so case is significant. The print names of symbols are used instead of the symbols themselves. @cindex @samp{empty string} defined An empty string, @samp{""}, a string with no characters in it, is smaller than any string of characters. @code{string-equal} provides the corresponding test for equality. Its shorter, alternative name is @code{string=}. There are no string test functions that correspond to @var{>}, @code{>=}, or @code{<=}. @item message Print a message in the echo area. The first argument is a string that can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of arguments that follow the string. The argument used by @samp{%s} must be a string or a symbol; the argument used by @samp{%d} must be a number. The argument used by @samp{%c} must be an ascii code number; it will be printed as the character with that @sc{ascii} code. @item setq @itemx set The @code{setq} function sets the value of its first argument to the value of the second argument. The first argument is automatically quoted by @code{setq}. It does the same for succeeding pairs of arguments. Another function, @code{set}, takes only two arguments and evaluates both of them before setting the value returned by its first argument to the value returned by its second argument. @item buffer-name Without an argument, return the name of the buffer, as a string. @itemx buffer-file-name Without an argument, return the name of the file the buffer is visiting. @item current-buffer Return the buffer in which Emacs is active; it may not be the buffer that is visible on the screen. @item other-buffer Return the most recently selected buffer (other than the buffer passed to @code{other-buffer} as an argument and other than the current buffer). @item switch-to-buffer Select a buffer for Emacs to be active in and display it in the current window so users can look at it. Usually bound to @kbd{C-x b}. @item set-buffer Switch Emacs' attention to a buffer on which programs will run. Don't alter what the window is showing. @item buffer-size Return the number of characters in the current buffer. @item point Return the value of the current position of the cursor, as an integer counting the number of characters from the beginning of the buffer. @item point-min Return the minimum permissible value of point in the current buffer. This is 1, unless narrowing is in effect. @item point-max Return the value of the maximum permissible value of point in the current buffer. This is the end of the buffer, unless narrowing is in effect. @end table @need 1500 @node defun Exercises, , Review, Writing Defuns @section Exercises @itemize @bullet @item Write a non-interactive function that doubles the value of its argument, a number. Make that function interactive. @item Write a function that tests whether the current value of @code{fill-column} is greater than the argument passed to the function, and if so, prints an appropriate message. @end itemize @node Buffer Walk Through, More Complex, Writing Defuns, Top @comment node-name, next, previous, up @chapter A Few Buffer--Related Functions In this chapter we study in detail several of the functions used in GNU Emacs. This is called a ``walk-through''. These functions are used as examples of Lisp code, but are not imaginary examples; with the exception of the first, simplified function definition, these functions show the actual code used in GNU Emacs. You can learn a great deal from these definitions. The functions described here are all related to buffers. Later, we will study other functions. @menu * 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:: @end menu @node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through @section Finding More Information @findex describe-function, @r{introduced} @cindex Find function documentation In this walk-through, I will describe each new function as we come to it, sometimes in detail and sometimes briefly. If you are interested, you can get the full documentation of any Emacs Lisp function at any time by typing @kbd{C-h f} and then the name of the function (and then @key{RET}). Similarly, you can get the full documentation for a variable by typing @kbd{C-h v} and then the name of the variable (and then @key{RET}). @cindex Find source of function In versions 20 and higher, when a function is written in Emacs Lisp, @code{describe-function} will also tell you the location of the function definition. If you move point over the file name and press the @key{RET} key, which is this case means @code{help-follow} rather than `return' or `enter', Emacs will take you directly to the function definition. More generally, if you want to see a function in its original source file, you can use the @code{find-tags} function to jump to it. @code{find-tags} works with a wide variety of languages, not just Lisp, and C, and it works with non-programming text as well. For example, @code{find-tags} will jump to the various nodes in the Texinfo source file of this document. The @code{find-tags} function depends on `tags tables' that record the locations of the functions, variables, and other items to which @code{find-tags} jumps. To use the @code{find-tags} command, type @kbd{M-.} (i.e., type the @key{META} key and the period key at the same time, or else type the @key{ESC} key and then type the period key), and then, at the prompt, type in the name of the function whose source code you want to see, such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will switch buffers and display the source code for the function on your screen. To switch back to your current buffer, type @kbd{C-x b @key{RET}}. (On some keyboards, the @key{META} key is labelled @key{ALT}.) @c !!! 21.0.100 tags table location in this paragraph @cindex TAGS table, specifying @findex find-tags Depending on how the initial default values of your copy of Emacs are set, you may also need to specify the location of your `tags table', which is a file called @file{TAGS}. For example, if you are interested in Emacs sources, the tags table you will most likely want, if it has already been created for you, will be in a subdirectory of the @file{/usr/local/share/emacs/} directory; thus you would use the @code{M-x visit-tags-table} command and specify a pathname such as @file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or @file{/usr/local/src/emacs/lisp/TAGS}. If the tags table has not already been created, you will have to create it yourself. @need 1250 To create a @file{TAGS} file in a specific directory, switch to that directory in Emacs using @kbd{M-x cd} command, or list the directory with @kbd{C-x d} (@code{dired}). Then run the compile command, with @w{@code{etags *.el}} as the command to execute @smallexample M-x compile RET etags *.el RET @end smallexample For more information, see @ref{etags, , Create Your Own @file{TAGS} File}. After you become more familiar with Emacs Lisp, you will find that you will frequently use @code{find-tags} to navigate your way around source code; and you will create your own @file{TAGS} tables. @cindex Library, as term for `file' Incidentally, the files that contain Lisp code are conventionally called @dfn{libraries}. The metaphor is derived from that of a specialized library, such as a law library or an engineering library, rather than a general library. Each library, or file, contains functions that relate to a particular topic or activity, such as @file{abbrev.el} for handling abbreviations and other typing shortcuts, and @file{help.el} for on-line help. (Sometimes several libraries provide code for a single activity, as the various @file{rmail@dots{}} files provide code for reading electronic mail.) In @cite{The GNU Emacs Manual}, you will see sentences such as ``The @kbd{C-h p} command lets you search the standard Emacs Lisp libraries by topic keywords.'' @node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through @comment node-name, next, previous, up @section A Simplified @code{beginning-of-buffer} Definition @findex simplified-beginning-of-buffer The @code{beginning-of-buffer} command is a good function to start with since you are likely to be familiar with it and it is easy to understand. Used as an interactive command, @code{beginning-of-buffer} moves the cursor to the beginning of the buffer, leaving the mark at the previous position. It is generally bound to @kbd{M-<}. In this section, we will discuss a shortened version of the function that shows how it is most frequently used. This shortened function works as written, but it does not contain the code for a complex option. In another section, we will describe the entire function. (@xref{beginning-of-buffer, , Complete Definition of @code{beginning-of-buffer}}.) Before looking at the code, let's consider what the function definition has to contain: it must include an expression that makes the function interactive so it can be called by typing @kbd{M-x beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it must include code to leave a mark at the original position in the buffer; and it must include code to move the cursor to the beginning of the buffer. @need 1250 Here is the complete text of the shortened version of the function: @smallexample @group (defun simplified-beginning-of-buffer () "Move point to the beginning of the buffer; leave mark at previous position." (interactive) (push-mark) (goto-char (point-min))) @end group @end smallexample Like all function definitions, this definition has five parts following the special form @code{defun}: @enumerate @item The name: in this example, @code{simplified-beginning-of-buffer}. @item A list of the arguments: in this example, an empty list, @code{()}, @item The documentation string. @item The interactive expression. @item The body. @end enumerate @noindent In this function definition, the argument list is empty; this means that this function does not require any arguments. (When we look at the definition for the complete function, we will see that it may be passed an optional argument.) The interactive expression tells Emacs that the function is intended to be used interactively. In this example, @code{interactive} does not have an argument because @code{simplified-beginning-of-buffer} does not require one. @need 800 The body of the function consists of the two lines: @smallexample @group (push-mark) (goto-char (point-min)) @end group @end smallexample The first of these lines is the expression, @code{(push-mark)}. When this expression is evaluated by the Lisp interpreter, it sets a mark at the current position of the cursor, wherever that may be. The position of this mark is saved in the mark ring. The next line is @code{(goto-char (point-min))}. This expression jumps the cursor to the minimum point in the buffer, that is, to the beginning of the buffer (or to the beginning of the accessible portion of the buffer if it is narrowed. @xref{Narrowing & Widening, , Narrowing and Widening}.) The @code{push-mark} command sets a mark at the place where the cursor was located before it was moved to the beginning of the buffer by the @code{(goto-char (point-min))} expression. Consequently, you can, if you wish, go back to where you were originally by typing @kbd{C-x C-x}. That is all there is to the function definition! @findex describe-function When you are reading code such as this and come upon an unfamiliar function, such as @code{goto-char}, you can find out what it does by using the @code{describe-function} command. To use this command, type @kbd{C-h f} and then type in the name of the function and press @key{RET}. The @code{describe-function} command will print the function's documentation string in a @file{*Help*} window. For example, the documentation for @code{goto-char} is: @smallexample @group One arg, a number. Set point to that number. Beginning of buffer is position (point-min), end is (point-max). @end group @end smallexample @noindent (The prompt for @code{describe-function} will offer you the symbol under or preceding the cursor, so you can save typing by positioning the cursor right over or after the function and then typing @kbd{C-h f @key{RET}}.) The @code{end-of-buffer} function definition is written in the same way as the @code{beginning-of-buffer} definition except that the body of the function contains the expression @code{(goto-char (point-max))} in place of @code{(goto-char (point-min))}. @node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through @comment node-name, next, previous, up @section The Definition of @code{mark-whole-buffer} @findex mark-whole-buffer The @code{mark-whole-buffer} function is no harder to understand than the @code{simplified-beginning-of-buffer} function. In this case, however, we will look at the complete function, not a shortened version. The @code{mark-whole-buffer} function is not as commonly used as the @code{beginning-of-buffer} function, but is useful nonetheless: it marks a whole buffer as a region by putting point at the beginning and a mark at the end of the buffer. It is generally bound to @kbd{C-x h}. @menu * mark-whole-buffer overview:: * Body of mark-whole-buffer:: Only three lines of code. @end menu @node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer @ifnottex @unnumberedsubsec An overview of @code{mark-whole-buffer} @end ifnottex @need 1250 In GNU Emacs 20, the code for the complete function looks like this: @smallexample @group (defun mark-whole-buffer () "Put point at beginning and mark at end of buffer." (interactive) (push-mark (point)) (push-mark (point-max)) (goto-char (point-min))) @end group @end smallexample @need 1250 Like all other functions, the @code{mark-whole-buffer} function fits into the template for a function definition. The template looks like this: @smallexample @group (defun @var{name-of-function} (@var{argument-list}) "@var{documentation}@dots{}" (@var{interactive-expression}@dots{}) @var{body}@dots{}) @end group @end smallexample Here is how the function works: the name of the function is @code{mark-whole-buffer}; it is followed by an empty argument list, @samp{()}, which means that the function does not require arguments. The documentation comes next. The next line is an @code{(interactive)} expression that tells Emacs that the function will be used interactively. These details are similar to the @code{simplified-beginning-of-buffer} function described in the previous section. @node Body of mark-whole-buffer, , mark-whole-buffer overview, mark-whole-buffer @comment node-name, next, previous, up @subsection Body of @code{mark-whole-buffer} The body of the @code{mark-whole-buffer} function consists of three lines of code: @smallexample @group (push-mark (point)) (push-mark (point-max)) (goto-char (point-min)) @end group @end smallexample The first of these lines is the expression, @code{(push-mark (point))}. This line does exactly the same job as the first line of the body of the @code{simplified-beginning-of-buffer} function, which is written @code{(push-mark)}. In both cases, the Lisp interpreter sets a mark at the current position of the cursor. I don't know why the expression in @code{mark-whole-buffer} is written @code{(push-mark (point))} and the expression in @code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps whoever wrote the code did not know that the arguments for @code{push-mark} are optional and that if @code{push-mark} is not passed an argument, the function automatically sets mark at the location of point by default. Or perhaps the expression was written so as to parallel the structure of the next line. In any case, the line causes Emacs to determine the position of point and set a mark there. The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}. This expression sets a mark at the point in the buffer that has the highest number. This will be the end of the buffer (or, if the buffer is narrowed, the end of the accessible portion of the buffer. @xref{Narrowing & Widening, , Narrowing and Widening}, for more about narrowing.) After this mark has been set, the previous mark, the one set at point, is no longer set, but Emacs remembers its position, just as all other recent marks are always remembered. This means that you can, if you wish, go back to that position by typing @kbd{C-u C-@key{SPC}} twice. (In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more complicated than shown here. The line reads @smallexample (push-mark (point-max) nil t) @end smallexample @noindent (The expression works nearly the same as before. It sets a mark at the highest numbered place in the buffer that it can. However, in this version, @code{push-mark} has two additional arguments. The second argument to @code{push-mark} is @code{nil}. This tells the function it @emph{should} display a message that says `Mark set' when it pushes the mark. The third argument is @code{t}. This tells @code{push-mark} to activate the mark when Transient Mark mode is turned on. Transient Mark mode highlights the currently active region. It is usually turned off.) Finally, the last line of the function is @code{(goto-char (point-min)))}. This is written exactly the same way as it is written in @code{beginning-of-buffer}. The expression moves the cursor to the minimum point in the buffer, that is, to the beginning of the buffer (or to the beginning of the accessible portion of the buffer). As a result of this, point is placed at the beginning of the buffer and mark is set at the end of the buffer. The whole buffer is, therefore, the region. @node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through @comment node-name, next, previous, up @section The Definition of @code{append-to-buffer} @findex append-to-buffer The @code{append-to-buffer} command is very nearly as simple as the @code{mark-whole-buffer} command. What it does is copy the region (that is, the part of the buffer between point and mark) from the current buffer to a specified buffer. @menu * 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. @end menu @node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer @ifnottex @unnumberedsubsec An Overview of @code{append-to-buffer} @end ifnottex @findex insert-buffer-substring The @code{append-to-buffer} command uses the @code{insert-buffer-substring} function to copy the region. @code{insert-buffer-substring} is described by its name: it takes a string of characters from part of a buffer, a ``substring'', and inserts them into another buffer. Most of @code{append-to-buffer} is concerned with setting up the conditions for @code{insert-buffer-substring} to work: the code must specify both the buffer to which the text will go and the region that will be copied. Here is the complete text of the function: @smallexample @group (defun append-to-buffer (buffer start end) "Append to specified buffer the text of the region. It is inserted into that buffer before its point. @end group @group When calling from a program, give three arguments: a buffer or the name of one, and two character numbers specifying the portion of the current buffer to be copied." (interactive "BAppend to buffer:@: \nr") (let ((oldbuf (current-buffer))) (save-excursion (set-buffer (get-buffer-create buffer)) (insert-buffer-substring oldbuf start end)))) @end group @end smallexample The function can be understood by looking at it as a series of filled-in templates. The outermost template is for the function definition. In this function, it looks like this (with several slots filled in): @smallexample @group (defun append-to-buffer (buffer start end) "@var{documentation}@dots{}" (interactive "BAppend to buffer:@: \nr") @var{body}@dots{}) @end group @end smallexample The first line of the function includes its name and three arguments. The arguments are the @code{buffer} to which the text will be copied, and the @code{start} and @code{end} of the region in the current buffer that will be copied. The next part of the function is the documentation, which is clear and complete. @node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer @comment node-name, next, previous, up @subsection The @code{append-to-buffer} Interactive Expression Since the @code{append-to-buffer} function will be used interactively, the function must have an @code{interactive} expression. (For a review of @code{interactive}, see @ref{Interactive, , Making a Function Interactive}.) The expression reads as follows: @smallexample (interactive "BAppend to buffer:@: \nr") @end smallexample @noindent This expression has an argument inside of quotation marks and that argument has two parts, separated by @samp{\n}. The first part is @samp{BAppend to buffer:@: }. Here, the @samp{B} tells Emacs to ask for the name of the buffer that will be passed to the function. Emacs will ask for the name by prompting the user in the minibuffer, using the string following the @samp{B}, which is the string @samp{Append to buffer:@: }. Emacs then binds the variable @code{buffer} in the function's argument list to the specified buffer. The newline, @samp{\n}, separates the first part of the argument from the second part. It is followed by an @samp{r} that tells Emacs to bind the two arguments that follow the symbol @code{buffer} in the function's argument list (that is, @code{start} and @code{end}) to the values of point and mark. @node append-to-buffer body, append save-excursion, append interactive, append-to-buffer @comment node-name, next, previous, up @subsection The Body of @code{append-to-buffer} The body of the @code{append-to-buffer} function begins with @code{let}. As we have seen before (@pxref{let, , @code{let}}), the purpose of a @code{let} expression is to create and give initial values to one or more variables that will only be used within the body of the @code{let}. This means that such a variable will not be confused with any variable of the same name outside the @code{let} expression. We can see how the @code{let} expression fits into the function as a whole by showing a template for @code{append-to-buffer} with the @code{let} expression in outline: @smallexample @group (defun append-to-buffer (buffer start end) "@var{documentation}@dots{}" (interactive "BAppend to buffer:@: \nr") (let ((@var{variable} @var{value})) @var{body}@dots{}) @end group @end smallexample The @code{let} expression has three elements: @enumerate @item The symbol @code{let}; @item A varlist containing, in this case, a single two-element list, @code{(@var{variable} @var{value})}; @item The body of the @code{let} expression. @end enumerate @need 800 In the @code{append-to-buffer} function, the varlist looks like this: @smallexample (oldbuf (current-buffer)) @end smallexample @noindent In this part of the @code{let} expression, the one variable, @code{oldbuf}, is bound to the value returned by the @code{(current-buffer)} expression. The variable, @code{oldbuf}, is used to keep track of the buffer in which you are working and from which you will copy. The element or elements of a varlist are surrounded by a set of parentheses so the Lisp interpreter can distinguish the varlist from the body of the @code{let}. As a consequence, the two-element list within the varlist is surrounded by a circumscribing set of parentheses. The line looks like this: @smallexample @group (let ((oldbuf (current-buffer))) @dots{} ) @end group @end smallexample @noindent The two parentheses before @code{oldbuf} might surprise you if you did not realize that the first parenthesis before @code{oldbuf} marks the boundary of the varlist and the second parenthesis marks the beginning of the two-element list, @code{(oldbuf (current-buffer))}. @node append save-excursion, , append-to-buffer body, append-to-buffer @comment node-name, next, previous, up @subsection @code{save-excursion} in @code{append-to-buffer} The body of the @code{let} expression in @code{append-to-buffer} consists of a @code{save-excursion} expression. The @code{save-excursion} function saves the locations of point and mark, and restores them to those positions after the expressions in the body of the @code{save-excursion} complete execution. In addition, @code{save-excursion} keeps track of the original buffer, and restores it. This is how @code{save-excursion} is used in @code{append-to-buffer}. @need 1500 @cindex Indentation for formatting @cindex Formatting convention Incidentally, it is worth noting here that a Lisp function is normally formatted so that everything that is enclosed in a multi-line spread is indented more to the right than the first symbol. In this function definition, the @code{let} is indented more than the @code{defun}, and the @code{save-excursion} is indented more than the @code{let}, like this: @smallexample @group (defun @dots{} @dots{} @dots{} (let@dots{} (save-excursion @dots{} @end group @end smallexample @need 1500 @noindent This formatting convention makes it easy to see that the two lines in the body of the @code{save-excursion} are enclosed by the parentheses associated with @code{save-excursion}, just as the @code{save-excursion} itself is enclosed by the parentheses associated with the @code{let}: @smallexample @group (let ((oldbuf (current-buffer))) (save-excursion (set-buffer (get-buffer-create buffer)) (insert-buffer-substring oldbuf start end)))) @end group @end smallexample @need 1200 The use of the @code{save-excursion} function can be viewed as a process of filling in the slots of a template: @smallexample @group (save-excursion @var{first-expression-in-body} @var{second-expression-in-body} @dots{} @var{last-expression-in-body}) @end group @end smallexample @need 1200 @noindent In this function, the body of the @code{save-excursion} contains only two expressions. The body looks like this: @smallexample @group (set-buffer (get-buffer-create buffer)) (insert-buffer-substring oldbuf start end) @end group @end smallexample When the @code{append-to-buffer} function is evaluated, the two expressions in the body of the @code{save-excursion} are evaluated in sequence. The value of the last expression is returned as the value of the @code{save-excursion} function; the other expression is evaluated only for its side effects. The first line in the body of the @code{save-excursion} uses the @code{set-buffer} function to change the current buffer to the one specified in the first argument to @code{append-to-buffer}. (Changing the buffer is the side effect; as we have said before, in Lisp, a side effect is often the primary thing we want.) The second line does the primary work of the function. The @code{set-buffer} function changes Emacs' attention to the buffer to which the text will be copied and from which @code{save-excursion} will return. @need 800 The line looks like this: @smallexample (set-buffer (get-buffer-create buffer)) @end smallexample The innermost expression of this list is @code{(get-buffer-create buffer)}. This expression uses the @code{get-buffer-create} function, which either gets the named buffer, or if it does not exist, creates one with the given name. This means you can use @code{append-to-buffer} to put text into a buffer that did not previously exist. @code{get-buffer-create} also keeps @code{set-buffer} from getting an unnecessary error: @code{set-buffer} needs a buffer to go to; if you were to specify a buffer that does not exist, Emacs would baulk. Since @code{get-buffer-create} will create a buffer if none exists, @code{set-buffer} is always provided with a buffer. @need 1250 The last line of @code{append-to-buffer} does the work of appending the text: @smallexample (insert-buffer-substring oldbuf start end) @end smallexample @noindent The @code{insert-buffer-substring} function copies a string @emph{from} the buffer specified as its first argument and inserts the string into the present buffer. In this case, the argument to @code{insert-buffer-substring} is the value of the variable created and bound by the @code{let}, namely the value of @code{oldbuf}, which was the current buffer when you gave the @code{append-to-buffer} command. After @code{insert-buffer-substring} has done its work, @code{save-excursion} will restore the action to the original buffer and @code{append-to-buffer} will have done its job. @need 800 Written in skeletal form, the workings of the body look like this: @smallexample @group (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer}) (save-excursion ; @r{Keep track of buffer.} @var{change-buffer} @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer}) @var{change-back-to-original-buffer-when-finished} @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished} @end group @end smallexample In summary, @code{append-to-buffer} works as follows: it saves the value of the current buffer in the variable called @code{oldbuf}. It gets the new buffer, creating one if need be, and switches Emacs to it. Using the value of @code{oldbuf}, it inserts the region of text from the old buffer into the new buffer; and then using @code{save-excursion}, it brings you back to your original buffer. In looking at @code{append-to-buffer}, you have explored a fairly complex function. It shows how to use @code{let} and @code{save-excursion}, and how to change to and come back from another buffer. Many function definitions use @code{let}, @code{save-excursion}, and @code{set-buffer} this way. @node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through @comment node-name, next, previous, up @section Review Here is a brief summary of the various functions discussed in this chapter. @table @code @item describe-function @itemx describe-variable Print the documentation for a function or variable. Conventionally bound to @kbd{C-h f} and @kbd{C-h v}. @item find-tag Find the file containing the source for a function or variable and switch buffers to it, positioning point at the beginning of the item. Conventionally bound to @kbd{M-.} (that's a period following the @key{META} key). @item save-excursion Save the location of point and mark and restore their values after the arguments to @code{save-excursion} have been evaluated. Also, remember the current buffer and return to it. @item push-mark Set mark at a location and record the value of the previous mark on the mark ring. The mark is a location in the buffer that will keep its relative position even if text is added to or removed from the buffer. @item goto-char Set point to the location specified by the value of the argument, which can be a number, a marker, or an expression that returns the number of a position, such as @code{(point-min)}. @item insert-buffer-substring Copy a region of text from a buffer that is passed to the function as an argument and insert the region into the current buffer. @item mark-whole-buffer Mark the whole buffer as a region. Normally bound to @kbd{C-x h}. @item set-buffer Switch the attention of Emacs to another buffer, but do not change the window being displayed. Used when the program rather than a human is to work on a different buffer. @item get-buffer-create @itemx get-buffer Find a named buffer or create one if a buffer of that name does not exist. The @code{get-buffer} function returns @code{nil} if the named buffer does not exist. @end table @need 1500 @node Buffer Exercises, , Buffer Related Review, Buffer Walk Through @section Exercises @itemize @bullet @item Write your own @code{simplified-end-of-buffer} function definition; then test it to see whether it works. @item Use @code{if} and @code{get-buffer} to write a function that prints a message telling you whether a buffer exists. @item Using @code{find-tag}, find the source for the @code{copy-to-buffer} function. @end itemize @node More Complex, Narrowing & Widening, Buffer Walk Through, Top @comment node-name, next, previous, up @chapter A Few More Complex Functions In this chapter, we build on what we have learned in previous chapters by looking at more complex functions. The @code{copy-to-buffer} function illustrates use of two @code{save-excursion} expressions in one definition, while the @code{insert-buffer} function illustrates use of an asterisk in an @code{interactive} expression, use of @code{or}, and the important distinction between a name and the object to which the name refers. @menu * 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:: @end menu @node copy-to-buffer, insert-buffer, More Complex, More Complex @comment node-name, next, previous, up @section The Definition of @code{copy-to-buffer} @findex copy-to-buffer After understanding how @code{append-to-buffer} works, it is easy to understand @code{copy-to-buffer}. This function copies text into a buffer, but instead of adding to the second buffer, it replaces the previous text in the second buffer. The code for the @code{copy-to-buffer} function is almost the same as the code for @code{append-to-buffer}, except that @code{erase-buffer} and a second @code{save-excursion} are used. (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}, for the description of @code{append-to-buffer}.) @need 800 The body of @code{copy-to-buffer} looks like this @smallexample @group @dots{} (interactive "BCopy to buffer:@: \nr") (let ((oldbuf (current-buffer))) (save-excursion (set-buffer (get-buffer-create buffer)) (erase-buffer) (save-excursion (insert-buffer-substring oldbuf start end))))) @end group @end smallexample This code is similar to the code in @code{append-to-buffer}: it is only after changing to the buffer to which the text will be copied that the definition for this function diverges from the definition for @code{append-to-buffer}: the @code{copy-to-buffer} function erases the buffer's former contents. (This is what is meant by `replacement'; to replace text, Emacs erases the previous text and then inserts new text.) After erasing the previous contents of the buffer, @code{save-excursion} is used for a second time and the new text is inserted. Why is @code{save-excursion} used twice? Consider again what the function does. @need 1250 In outline, the body of @code{copy-to-buffer} looks like this: @smallexample @group (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer}) (save-excursion ; @r{First use of @code{save-excursion}.} @var{change-buffer} (erase-buffer) (save-excursion ; @r{Second use of @code{save-excursion}.} @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer}))) @end group @end smallexample The first use of @code{save-excursion} returns Emacs to the buffer from which the text is being copied. That is clear, and is just like its use in @code{append-to-buffer}. Why the second use? The reason is that @code{insert-buffer-substring} always leaves point at the @emph{end} of the region being inserted. The second @code{save-excursion} causes Emacs to leave point at the beginning of the text being inserted. In most circumstances, users prefer to find point at the beginning of inserted text. (Of course, the @code{copy-to-buffer} function returns the user to the original buffer when done---but if the user @emph{then} switches to the copied-to buffer, point will go to the beginning of the text. Thus, this use of a second @code{save-excursion} is a little nicety.) @node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex @comment node-name, next, previous, up @section The Definition of @code{insert-buffer} @findex insert-buffer @code{insert-buffer} is yet another buffer-related function. This command copies another buffer @emph{into} the current buffer. It is the reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they copy a region of text @emph{from} the current buffer to another buffer. In addition, this code illustrates the use of @code{interactive} with a buffer that might be @dfn{read-only} and the important distinction between the name of an object and the object actually referred to. @menu * 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. @end menu @node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer @ifnottex @unnumberedsubsec The Code for @code{insert-buffer} @end ifnottex @need 800 Here is the code: @smallexample @group (defun insert-buffer (buffer) "Insert after point the contents of BUFFER. Puts mark after the inserted text. BUFFER may be a buffer or a buffer name." (interactive "*bInsert buffer:@: ") @end group @group (or (bufferp buffer) (setq buffer (get-buffer buffer))) (let (start end newmark) (save-excursion (save-excursion (set-buffer buffer) (setq start (point-min) end (point-max))) @end group @group (insert-buffer-substring buffer start end) (setq newmark (point))) (push-mark newmark))) @end group @end smallexample @need 1200 As with other function definitions, you can use a template to see an outline of the function: @smallexample @group (defun insert-buffer (buffer) "@var{documentation}@dots{}" (interactive "*bInsert buffer:@: ") @var{body}@dots{}) @end group @end smallexample @node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer @comment node-name, next, previous, up @subsection The Interactive Expression in @code{insert-buffer} @findex interactive, @r{example use of} In @code{insert-buffer}, the argument to the @code{interactive} declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert buffer:@: }. @menu * Read-only buffer:: When a buffer cannot be modified. * b for interactive:: An existing buffer or else its name. @end menu @node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive @comment node-name, next, previous, up @unnumberedsubsubsec A Read-only Buffer @cindex Read-only buffer @cindex Asterisk for read-only buffer @findex * @r{for read-only buffer} The asterisk is for the situation when the current buffer is a read-only buffer---a buffer that cannot be modified. If @code{insert-buffer} is called when the current buffer is read-only, a message to this effect is printed in the echo area and the terminal may beep or blink at you; you will not be permitted to insert anything into current buffer. The asterisk does not need to be followed by a newline to separate it from the next argument. @node b for interactive, , Read-only buffer, insert-buffer interactive @comment node-name, next, previous, up @unnumberedsubsubsec @samp{b} in an Interactive Expression The next argument in the interactive expression starts with a lower case @samp{b}. (This is different from the code for @code{append-to-buffer}, which uses an upper-case @samp{B}. @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.) The lower-case @samp{b} tells the Lisp interpreter that the argument for @code{insert-buffer} should be an existing buffer or else its name. (The upper-case @samp{B} option provides for the possibility that the buffer does not exist.) Emacs will prompt you for the name of the buffer, offering you a default buffer, with name completion enabled. If the buffer does not exist, you receive a message that says ``No match''; your terminal may beep at you as well. @node insert-buffer body, if & or, insert-buffer interactive, insert-buffer @comment node-name, next, previous, up @subsection The Body of the @code{insert-buffer} Function The body of the @code{insert-buffer} function has two major parts: an @code{or} expression and a @code{let} expression. The purpose of the @code{or} expression is to ensure that the argument @code{buffer} is bound to a buffer and not just the name of a buffer. The body of the @code{let} expression contains the code which copies the other buffer into the current buffer. @need 1250 In outline, the two expressions fit into the @code{insert-buffer} function like this: @smallexample @group (defun insert-buffer (buffer) "@var{documentation}@dots{}" (interactive "*bInsert buffer:@: ") (or @dots{} @dots{} @end group @group (let (@var{varlist}) @var{body-of-}@code{let}@dots{} ) @end group @end smallexample To understand how the @code{or} expression ensures that the argument @code{buffer} is bound to a buffer and not to the name of a buffer, it is first necessary to understand the @code{or} function. Before doing this, let me rewrite this part of the function using @code{if} so that you can see what is done in a manner that will be familiar. @node if & or, Insert or, insert-buffer body, insert-buffer @comment node-name, next, previous, up @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or} The job to be done is to make sure the value of @code{buffer} is a buffer itself and not the name of a buffer. If the value is the name, then the buffer itself must be got. You can imagine yourself at a conference where an usher is wandering around holding a list with your name on it and looking for you: the usher is ``bound'' to your name, not to you; but when the usher finds you and takes your arm, the usher becomes ``bound'' to you. @need 800 In Lisp, you might describe this situation like this: @smallexample @group (if (not (holding-on-to-guest)) (find-and-take-arm-of-guest)) @end group @end smallexample We want to do the same thing with a buffer---if we do not have the buffer itself, we want to get it. @need 1200 Using a predicate called @code{bufferp} that tells us whether we have a buffer (rather than its name), we can write the code like this: @smallexample @group (if (not (bufferp buffer)) ; @r{if-part} (setq buffer (get-buffer buffer))) ; @r{then-part} @end group @end smallexample @noindent Here, the true-or-false-test of the @code{if} expression is @w{@code{(not (bufferp buffer))}}; and the then-part is the expression @w{@code{(setq buffer (get-buffer buffer))}}. In the test, the function @code{bufferp} returns true if its argument is a buffer---but false if its argument is the name of the buffer. (The last character of the function name @code{bufferp} is the character @samp{p}; as we saw earlier, such use of @samp{p} is a convention that indicates that the function is a predicate, which is a term that means that the function will determine whether some property is true or false. @xref{Wrong Type of Argument, , Using the Wrong Type Object as an Argument}.) @need 1200 The function @code{not} precedes the expression @code{(bufferp buffer)}, so the true-or-false-test looks like this: @smallexample (not (bufferp buffer)) @end smallexample @noindent @code{not} is a function that returns true if its argument is false and false if its argument is true. So if @code{(bufferp buffer)} returns true, the @code{not} expression returns false and vice-versa: what is ``not true'' is false and what is ``not false'' is true. Using this test, the @code{if} expression works as follows: when the value of the variable @code{buffer} is actually a buffer rather than its name, the true-or-false-test returns false and the @code{if} expression does not evaluate the then-part. This is fine, since we do not need to do anything to the variable @code{buffer} if it really is a buffer. On the other hand, when the value of @code{buffer} is not a buffer itself, but the name of a buffer, the true-or-false-test returns true and the then-part of the expression is evaluated. In this case, the then-part is @code{(setq buffer (get-buffer buffer))}. This expression uses the @code{get-buffer} function to return an actual buffer itself, given its name. The @code{setq} then sets the variable @code{buffer} to the value of the buffer itself, replacing its previous value (which was the name of the buffer). @node Insert or, Insert let, if & or, insert-buffer @comment node-name, next, previous, up @subsection The @code{or} in the Body The purpose of the @code{or} expression in the @code{insert-buffer} function is to ensure that the argument @code{buffer} is bound to a buffer and not just to the name of a buffer. The previous section shows how the job could have been done using an @code{if} expression. However, the @code{insert-buffer} function actually uses @code{or}. To understand this, it is necessary to understand how @code{or} works. @findex or An @code{or} function can have any number of arguments. It evaluates each argument in turn and returns the value of the first of its arguments that is not @code{nil}. Also, and this is a crucial feature of @code{or}, it does not evaluate any subsequent arguments after returning the first non-@code{nil} value. @need 800 The @code{or} expression looks like this: @smallexample @group (or (bufferp buffer) (setq buffer (get-buffer buffer))) @end group @end smallexample @noindent The first argument to @code{or} is the expression @code{(bufferp buffer)}. This expression returns true (a non-@code{nil} value) if the buffer is actually a buffer, and not just the name of a buffer. In the @code{or} expression, if this is the case, the @code{or} expression returns this true value and does not evaluate the next expression---and this is fine with us, since we do not want to do anything to the value of @code{buffer} if it really is a buffer. On the other hand, if the value of @code{(bufferp buffer)} is @code{nil}, which it will be if the value of @code{buffer} is the name of a buffer, the Lisp interpreter evaluates the next element of the @code{or} expression. This is the expression @code{(setq buffer (get-buffer buffer))}. This expression returns a non-@code{nil} value, which is the value to which it sets the variable @code{buffer}---and this value is a buffer itself, not the name of a buffer. The result of all this is that the symbol @code{buffer} is always bound to a buffer itself rather than to the name of a buffer. All this is necessary because the @code{set-buffer} function in a following line only works with a buffer itself, not with the name to a buffer. @need 1250 Incidentally, using @code{or}, the situation with the usher would be written like this: @smallexample (or (holding-on-to-guest) (find-and-take-arm-of-guest)) @end smallexample @node Insert let, , Insert or, insert-buffer @comment node-name, next, previous, up @subsection The @code{let} Expression in @code{insert-buffer} After ensuring that the variable @code{buffer} refers to a buffer itself and not just to the name of a buffer, the @code{insert-buffer function} continues with a @code{let} expression. This specifies three local variables, @code{start}, @code{end}, and @code{newmark} and binds them to the initial value @code{nil}. These variables are used inside the remainder of the @code{let} and temporarily hide any other occurrence of variables of the same name in Emacs until the end of the @code{let}. @need 1200 The body of the @code{let} contains two @code{save-excursion} expressions. First, we will look at the inner @code{save-excursion} expression in detail. The expression looks like this: @smallexample @group (save-excursion (set-buffer buffer) (setq start (point-min) end (point-max))) @end group @end smallexample @noindent The expression @code{(set-buffer buffer)} changes Emacs' attention from the current buffer to the one from which the text will copied. In that buffer, the variables @code{start} and @code{end} are set to the beginning and end of the buffer, using the commands @code{point-min} and @code{point-max}. Note that we have here an illustration of how @code{setq} is able to set two variables in the same expression. The first argument of @code{setq} is set to the value of its second, and its third argument is set to the value of its fourth. After the body of the inner @code{save-excursion} is evaluated, the @code{save-excursion} restores the original buffer, but @code{start} and @code{end} remain set to the values of the beginning and end of the buffer from which the text will be copied. @need 1250 The outer @code{save-excursion} expression looks like this: @smallexample @group (save-excursion (@var{inner-}@code{save-excursion}@var{-expression} (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end}) (insert-buffer-substring buffer start end) (setq newmark (point))) @end group @end smallexample @noindent The @code{insert-buffer-substring} function copies the text @emph{into} the current buffer @emph{from} the region indicated by @code{start} and @code{end} in @code{buffer}. Since the whole of the second buffer lies between @code{start} and @code{end}, the whole of the second buffer is copied into the buffer you are editing. Next, the value of point, which will be at the end of the inserted text, is recorded in the variable @code{newmark}. After the body of the outer @code{save-excursion} is evaluated, point and mark are relocated to their original places. However, it is convenient to locate a mark at the end of the newly inserted text and locate point at its beginning. The @code{newmark} variable records the end of the inserted text. In the last line of the @code{let} expression, the @code{(push-mark newmark)} expression function sets a mark to this location. (The previous location of the mark is still accessible; it is recorded on the mark ring and you can go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is located at the beginning of the inserted text, which is where it was before you called the insert function. @need 1250 The whole @code{let} expression looks like this: @smallexample @group (let (start end newmark) (save-excursion (save-excursion (set-buffer buffer) (setq start (point-min) end (point-max))) (insert-buffer-substring buffer start end) (setq newmark (point))) (push-mark newmark)) @end group @end smallexample Like the @code{append-to-buffer} function, the @code{insert-buffer} function uses @code{let}, @code{save-excursion}, and @code{set-buffer}. In addition, the function illustrates one way to use @code{or}. All these functions are building blocks that we will find and use again and again. @node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex @comment node-name, next, previous, up @section Complete Definition of @code{beginning-of-buffer} @findex beginning-of-buffer The basic structure of the @code{beginning-of-buffer} function has already been discussed. (@xref{simplified-beginning-of-buffer, , A Simplified @code{beginning-of-buffer} Definition}.) This section describes the complex part of the definition. As previously described, when invoked without an argument, @code{beginning-of-buffer} moves the cursor to the beginning of the buffer, leaving the mark at the previous position. However, when the command is invoked with a number between one and ten, the function considers that number to be a fraction of the length of the buffer, measured in tenths, and Emacs moves the cursor that fraction of the way from the beginning of the buffer. Thus, you can either call this function with the key command @kbd{M-<}, which will move the cursor to the beginning of the buffer, or with a key command such as @kbd{C-u 7 M-<} which will move the cursor to a point 70% of the way through the buffer. If a number bigger than ten is used for the argument, it moves to the end of the buffer. The @code{beginning-of-buffer} function can be called with or without an argument. The use of the argument is optional. @menu * Optional Arguments:: * beginning-of-buffer opt arg:: Example with optional argument. * beginning-of-buffer complete:: @end menu @node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer @subsection Optional Arguments Unless told otherwise, Lisp expects that a function with an argument in its function definition will be called with a value for that argument. If that does not happen, you get an error and a message that says @samp{Wrong number of arguments}. @cindex Optional arguments @cindex Keyword @findex optional However, optional arguments are a feature of Lisp: a @dfn{keyword} may be used to tell the Lisp interpreter that an argument is optional. The keyword is @code{&optional}. (The @samp{&} in front of @samp{optional} is part of the keyword.) In a function definition, if an argument follows the keyword @code{&optional}, a value does not need to be passed to that argument when the function is called. @need 1200 The first line of the function definition of @code{beginning-of-buffer} therefore looks like this: @smallexample (defun beginning-of-buffer (&optional arg) @end smallexample @need 1250 In outline, the whole function looks like this: @smallexample @group (defun beginning-of-buffer (&optional arg) "@var{documentation}@dots{}" (interactive "P") (push-mark) (goto-char (@var{if-there-is-an-argument} @var{figure-out-where-to-go} @var{else-go-to} (point-min)))) @end group @end smallexample The function is similar to the @code{simplified-beginning-of-buffer} function except that the @code{interactive} expression has @code{"P"} as an argument and the @code{goto-char} function is followed by an if-then-else expression that figures out where to put the cursor if there is an argument. The @code{"P"} in the @code{interactive} expression tells Emacs to pass a prefix argument, if there is one, to the function. A prefix argument is made by typing the @key{META} key followed by a number, or by typing @kbd{C-u} and then a number (if you don't type a number, @kbd{C-u} defaults to 4). The true-or-false-test of the @code{if} expression is simple: it is simply the argument @code{arg}. If @code{arg} has a value that is not @code{nil}, which will be the case if @code{beginning-of-buffer} is called with an argument, then this true-or-false-test will return true and the then-part of the @code{if} expression will be evaluated. On the other hand, if @code{beginning-of-buffer} is not called with an argument, the value of @code{arg} will be @code{nil} and the else-part of the @code{if} expression will be evaluated. The else-part is simply @code{point-min}, and when this is the outcome, the whole @code{goto-char} expression is @code{(goto-char (point-min))}, which is how we saw the @code{beginning-of-buffer} function in its simplified form. @node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer @subsection @code{beginning-of-buffer} with an Argument When @code{beginning-of-buffer} is called with an argument, an expression is evaluated which calculates what value to pass to @code{goto-char}. This expression is rather complicated at first sight. It includes an inner @code{if} expression and much arithmetic. It looks like this: @smallexample @group (if (> (buffer-size) 10000) ;; @r{Avoid overflow for large buffer sizes!} (* (prefix-numeric-value arg) (/ (buffer-size) 10)) (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10)) @end group @end smallexample @menu * Disentangle beginning-of-buffer:: * Large buffer case:: * Small buffer case:: @end menu @node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg @ifnottex @unnumberedsubsubsec Disentangle @code{beginning-of-buffer} @end ifnottex Like other complex-looking expressions, the conditional expression within @code{beginning-of-buffer} can be disentangled by looking at it as parts of a template, in this case, the template for an if-then-else expression. In skeletal form, the expression looks like this: @smallexample @group (if (@var{buffer-is-large} @var{divide-buffer-size-by-10-and-multiply-by-arg} @var{else-use-alternate-calculation} @end group @end smallexample The true-or-false-test of this inner @code{if} expression checks the size of the buffer. The reason for this is that the old Version 18 Emacs used numbers that are no bigger than eight million or so and in the computation that followed, the programmer feared that Emacs might try to use over-large numbers if the buffer were large. The term `overflow', mentioned in the comment, means numbers that are over large. Version 21 Emacs uses larger numbers, but this code has not been touched, if only because people now look at buffers that are far, far larger than ever before. There are two cases: if the buffer is large and if it is not. @node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg @comment node-name, next, previous, up @unnumberedsubsubsec What happens in a large buffer In @code{beginning-of-buffer}, the inner @code{if} expression tests whether the size of the buffer is greater than 10,000 characters. To do this, it uses the @code{>} function and the @code{buffer-size} function. @need 800 The line looks like this: @smallexample (if (> (buffer-size) 10000) @end smallexample @need 1200 @noindent When the buffer is large, the then-part of the @code{if} expression is evaluated. It reads like this (after formatting for easy reading): @smallexample @group (* (prefix-numeric-value arg) (/ (buffer-size) 10)) @end group @end smallexample @noindent This expression is a multiplication, with two arguments to the function @code{*}. The first argument is @code{(prefix-numeric-value arg)}. When @code{"P"} is used as the argument for @code{interactive}, the value passed to the function as its argument is passed a ``raw prefix argument'', and not a number. (It is a number in a list.) To perform the arithmetic, a conversion is necessary, and @code{prefix-numeric-value} does the job. @findex / @r{(division)} @cindex Division The second argument is @code{(/ (buffer-size) 10)}. This expression divides the numeric value of the buffer by ten. This produces a number that tells how many characters make up one tenth of the buffer size. (In Lisp, @code{/} is used for division, just as @code{*} is used for multiplication.) @need 1200 In the multiplication expression as a whole, this amount is multiplied by the value of the prefix argument---the multiplication looks like this: @smallexample @group (* @var{numeric-value-of-prefix-arg} @var{number-of-characters-in-one-tenth-of-the-buffer}) @end group @end smallexample @noindent If, for example, the prefix argument is @samp{7}, the one-tenth value will be multiplied by 7 to give a position 70% of the way through the buffer. @need 1200 The result of all this is that if the buffer is large, the @code{goto-char} expression reads like this: @smallexample @group (goto-char (* (prefix-numeric-value arg) (/ (buffer-size) 10))) @end group @end smallexample This puts the cursor where we want it. @node Small buffer case, , Large buffer case, beginning-of-buffer opt arg @comment node-name, next, previous, up @unnumberedsubsubsec What happens in a small buffer If the buffer contains fewer than 10,000 characters, a slightly different computation is performed. You might think this is not necessary, since the first computation could do the job. However, in a small buffer, the first method may not put the cursor on exactly the desired line; the second method does a better job. @need 800 The code looks like this: @c Keep this on one line. @smallexample (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10)) @end smallexample @need 1200 @noindent This is code in which you figure out what happens by discovering how the functions are embedded in parentheses. It is easier to read if you reformat it with each expression indented more deeply than its enclosing expression: @smallexample @group (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10)) @end group @end smallexample @need 1200 @noindent Looking at parentheses, we see that the innermost operation is @code{(prefix-numeric-value arg)}, which converts the raw argument to a number. This number is multiplied by the buffer size in the following expression: @smallexample (* (buffer-size) (prefix-numeric-value arg) @end smallexample @noindent This multiplication creates a number that may be larger than the size of the buffer---seven times larger if the argument is 7, for example. Ten is then added to this number and finally the large number is divided by ten to provide a value that is one character larger than the percentage position in the buffer. The number that results from all this is passed to @code{goto-char} and the cursor is moved to that point. @node beginning-of-buffer complete, , beginning-of-buffer opt arg, beginning-of-buffer @comment node-name, next, previous, up @subsection The Complete @code{beginning-of-buffer} @need 800 Here is the complete text of the @code{beginning-of-buffer} function: @smallexample @group (defun beginning-of-buffer (&optional arg) "Move point to the beginning of the buffer; leave mark at previous position. With arg N, put point N/10 of the way from the true beginning. Don't use this in Lisp programs! \(goto-char (point-min)) is faster and does not set the mark." (interactive "P") (push-mark) @end group @group (goto-char (if arg (if (> (buffer-size) 10000) ;; @r{Avoid overflow for large buffer sizes!} (* (prefix-numeric-value arg) (/ (buffer-size) 10)) @end group @group (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10)) (point-min))) (if arg (forward-line 1))) @end group @end smallexample @noindent Except for two small points, the previous discussion shows how this function works. The first point deals with a detail in the documentation string, and the second point concerns the last line of the function. @need 800 In the documentation string, there is reference to an expression: @smallexample \(goto-char (point-min)) @end smallexample @noindent A @samp{\} is used before the first parenthesis of this expression. This @samp{\} tells the Lisp interpreter that the expression should be printed as shown in the documentation rather than evaluated as a symbolic expression, which is what it looks like. @need 1200 Finally, the last line of the @code{beginning-of-buffer} command says to move point to the beginning of the next line if the command is invoked with an argument: @smallexample (if arg (forward-line 1))) @end smallexample @noindent This puts the cursor at the beginning of the first line after the appropriate tenths position in the buffer. This is a flourish that means that the cursor is always located @emph{at least} the requested tenths of the way through the buffer, which is a nicety that is, perhaps, not necessary, but which, if it did not occur, would be sure to draw complaints. @node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex @comment node-name, next, previous, up @section Review Here is a brief summary of some of the topics covered in this chapter. @table @code @item or Evaluate each argument in sequence, and return the value of the first argument that is not @code{nil}; if none return a value that is not @code{nil}, return @code{nil}. In brief, return the first true value of the arguments; return a true value if one @emph{or} any of the other are true. @item and Evaluate each argument in sequence, and if any are @code{nil}, return @code{nil}; if none are @code{nil}, return the value of the last argument. In brief, return a true value only if all the arguments are true; return a true value if one @emph{and} each of the others is true. @item &optional A keyword used to indicate that an argument to a function definition is optional; this means that the function can be evaluated without the argument, if desired. @item prefix-numeric-value Convert the `raw prefix argument' produced by @code{(interactive "P")} to a numeric value. @item forward-line Move point forward to the beginning of the next line, or if the argument is greater than one, forward that many lines. If it can't move as far forward as it is supposed to, @code{forward-line} goes forward as far as it can and then returns a count of the number of additional lines it was supposed to move but couldn't. @item erase-buffer Delete the entire contents of the current buffer. @item bufferp Return @code{t} if its argument is a buffer; otherwise return @code{nil}. @end table @node optional Exercise, , Second Buffer Related Review, More Complex @section @code{optional} Argument Exercise Write an interactive function with an optional argument that tests whether its argument, a number, is greater or less than the value of @code{fill-column}, and tells you which, in a message. However, if you do not pass an argument to the function, use 56 as a default value. @node Narrowing & Widening, car cdr & cons, More Complex, Top @comment node-name, next, previous, up @chapter Narrowing and Widening @cindex Focusing attention (narrowing) @cindex Narrowing @cindex Widening Narrowing is a feature of Emacs that makes it possible for you to focus on a specific part of a buffer, and work without accidentally changing other parts. Narrowing is normally disabled since it can confuse novices. @menu * 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:: @end menu @node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening @ifnottex @unnumberedsec The Advantages of Narrowing @end ifnottex With narrowing, the rest of a buffer is made invisible, as if it weren't there. This is an advantage if, for example, you want to replace a word in one part of a buffer but not in another: you narrow to the part you want and the replacement is carried out only in that section, not in the rest of the buffer. Searches will only work within a narrowed region, not outside of one, so if you are fixing a part of a document, you can keep yourself from accidentally finding parts you do not need to fix by narrowing just to the region you want. (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.) However, narrowing does make the rest of the buffer invisible, which can scare people who inadvertently invoke narrowing and think they have deleted a part of their file. Moreover, the @code{undo} command (which is usually bound to @kbd{C-x u}) does not turn off narrowing (nor should it), so people can become quite desperate if they do not know that they can return the rest of a buffer to visibility with the @code{widen} command. (The key binding for @code{widen} is @kbd{C-x n w}.) Narrowing is just as useful to the Lisp interpreter as to a human. Often, an Emacs Lisp function is designed to work on just part of a buffer; or conversely, an Emacs Lisp function needs to work on all of a buffer that has been narrowed. The @code{what-line} function, for example, removes the narrowing from a buffer, if it has any narrowing and when it has finished its job, restores the narrowing to what it was. On the other hand, the @code{count-lines} function, which is called by @code{what-line}, uses narrowing to restrict itself to just that portion of the buffer in which it is interested and then restores the previous situation. @node save-restriction, what-line, Narrowing advantages, Narrowing & Widening @comment node-name, next, previous, up @section The @code{save-restriction} Special Form @findex save-restriction In Emacs Lisp, you can use the @code{save-restriction} special form to keep track of whatever narrowing is in effect, if any. When the Lisp interpreter meets with @code{save-restriction}, it executes the code in the body of the @code{save-restriction} expression, and then undoes any changes to narrowing that the code caused. If, for example, the buffer is narrowed and the code that follows @code{save-restriction} gets rid of the narrowing, @code{save-restriction} returns the buffer to its narrowed region afterwards. In the @code{what-line} command, any narrowing the buffer may have is undone by the @code{widen} command that immediately follows the @code{save-restriction} command. Any original narrowing is restored just before the completion of the function. @need 1250 The template for a @code{save-restriction} expression is simple: @smallexample @group (save-restriction @var{body}@dots{} ) @end group @end smallexample @noindent The body of the @code{save-restriction} is one or more expressions that will be evaluated in sequence by the Lisp interpreter. Finally, a point to note: when you use both @code{save-excursion} and @code{save-restriction}, one right after the other, you should use @code{save-excursion} outermost. If you write them in reverse order, you may fail to record narrowing in the buffer to which Emacs switches after calling @code{save-excursion}. Thus, when written together, @code{save-excursion} and @code{save-restriction} should be written like this: @smallexample @group (save-excursion (save-restriction @var{body}@dots{})) @end group @end smallexample In other circumstances, when not written together, the @code{save-excursion} and @code{save-restriction} special forms must be written in the order appropriate to the function. @need 1250 For example, @smallexample @group (save-restriction (widen) (save-excursion @var{body}@dots{})) @end group @end smallexample @node what-line, narrow Exercise, save-restriction, Narrowing & Widening @comment node-name, next, previous, up @section @code{what-line} @findex what-line @cindex Widening, example of The @code{what-line} command tells you the number of the line in which the cursor is located. The function illustrates the use of the @code{save-restriction} and @code{save-excursion} commands. Here is the text of the function in full: @smallexample @group (defun what-line () "Print the current line number (in the buffer) of point." (interactive) (save-restriction (widen) (save-excursion (beginning-of-line) (message "Line %d" (1+ (count-lines 1 (point))))))) @end group @end smallexample The function has a documentation line and is interactive, as you would expect. The next two lines use the functions @code{save-restriction} and @code{widen}. The @code{save-restriction} special form notes whatever narrowing is in effect, if any, in the current buffer and restores that narrowing after the code in the body of the @code{save-restriction} has been evaluated. The @code{save-restriction} special form is followed by @code{widen}. This function undoes any narrowing the current buffer may have had when @code{what-line} was called. (The narrowing that was there is the narrowing that @code{save-restriction} remembers.) This widening makes it possible for the line counting commands to count from the beginning of the buffer. Otherwise, they would have been limited to counting within the accessible region. Any original narrowing is restored just before the completion of the function by the @code{save-restriction} special form. The call to @code{widen} is followed by @code{save-excursion}, which saves the location of the cursor (i.e., of point) and of the mark, and restores them after the code in the body of the @code{save-excursion} uses the @code{beginning-of-line} function to move point. (Note that the @code{(widen)} expression comes between the @code{save-restriction} and @code{save-excursion} special forms. When you write the two @code{save- @dots{}} expressions in sequence, write @code{save-excursion} outermost.) @need 1200 The last two lines of the @code{what-line} function are functions to count the number of lines in the buffer and then print the number in the echo area. @smallexample @group (message "Line %d" (1+ (count-lines 1 (point))))))) @end group @end smallexample The @code{message} function prints a one-line message at the bottom of the Emacs screen. The first argument is inside of quotation marks and is printed as a string of characters. However, it may contain @samp{%d}, @samp{%s}, or @samp{%c} to print arguments that follow the string. @samp{%d} prints the argument as a decimal, so the message will say something such as @samp{Line 243}. @need 1200 The number that is printed in place of the @samp{%d} is computed by the last line of the function: @smallexample (1+ (count-lines 1 (point))) @end smallexample @noindent What this does is count the lines from the first position of the buffer, indicated by the @code{1}, up to @code{(point)}, and then add one to that number. (The @code{1+} function adds one to its argument.) We add one to it because line 2 has only one line before it, and @code{count-lines} counts only the lines @emph{before} the current line. After @code{count-lines} has done its job, and the message has been printed in the echo area, the @code{save-excursion} restores point and mark to their original positions; and @code{save-restriction} restores the original narrowing, if any. @node narrow Exercise, , what-line, Narrowing & Widening @section Exercise with Narrowing Write a function that will display the first 60 characters of the current buffer, even if you have narrowed the buffer to its latter half so that the first line is inaccessible. Restore point, mark, and narrowing. For this exercise, you need to use @code{save-restriction}, @code{widen}, @code{goto-char}, @code{point-min}, @code{buffer-substring}, @code{message}, and other functions, a whole potpourri. @node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top @comment node-name, next, previous, up @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions @findex car, @r{introduced} @findex cdr, @r{introduced} In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental functions. The @code{cons} function is used to construct lists, and the @code{car} and @code{cdr} functions are used to take them apart. In the walk through of the @code{copy-region-as-kill} function, we will see @code{cons} as well as two variants on @code{cdr}, namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.) @menu * 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:: @end menu @node Strange Names, car & cdr, car cdr & cons, car cdr & cons @ifnottex @unnumberedsec Strange Names @end ifnottex The name of the @code{cons} function is not unreasonable: it is an abbreviation of the word `construct'. The origins of the names for @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car} is an acronym from the phrase `Contents of the Address part of the Register'; and @code{cdr} (pronounced `could-er') is an acronym from the phrase `Contents of the Decrement part of the Register'. These phrases refer to specific pieces of hardware on the very early computer on which the original Lisp was developed. Besides being obsolete, the phrases have been completely irrelevant for more than 25 years to anyone thinking about Lisp. Nonetheless, although a few brave scholars have begun to use more reasonable names for these functions, the old terms are still in use. In particular, since the terms are used in the Emacs Lisp source code, we will use them in this introduction. @node car & cdr, cons, Strange Names, car cdr & cons @comment node-name, next, previous, up @section @code{car} and @code{cdr} The @sc{car} of a list is, quite simply, the first item in the list. Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is @code{rose}. @need 1200 If you are reading this in Info in GNU Emacs, you can see this by evaluating the following: @smallexample (car '(rose violet daisy buttercup)) @end smallexample @noindent After evaluating the expression, @code{rose} will appear in the echo area. Clearly, a more reasonable name for the @code{car} function would be @code{first} and this is often suggested. @code{car} does not remove the first item from the list; it only reports what it is. After @code{car} has been applied to a list, the list is still the same as it was. In the jargon, @code{car} is `non-destructive'. This feature turns out to be important. The @sc{cdr} of a list is the rest of the list, that is, the @code{cdr} function returns the part of the list that follows the first item. Thus, while the @sc{car} of the list @code{'(rose violet daisy buttercup)} is @code{rose}, the rest of the list, the value returned by the @code{cdr} function, is @code{(violet daisy buttercup)}. @need 1250 You can see this by evaluating the following in the usual way: @smallexample (cdr '(rose violet daisy buttercup)) @end smallexample @noindent When you evaluate this, @code{(violet daisy buttercup)} will appear in the echo area. Like @code{car}, @code{cdr} does not remove any elements from the list---it just returns a report of what the second and subsequent elements are. Incidentally, in the example, the list of flowers is quoted. If it were not, the Lisp interpreter would try to evaluate the list by calling @code{rose} as a function. In this example, we do not want to do that. Clearly, a more reasonable name for @code{cdr} would be @code{rest}. (There is a lesson here: when you name new functions, consider very carefully what you are doing, since you may be stuck with the names for far longer than you expect. The reason this document perpetuates these names is that the Emacs Lisp source code uses them, and if I did not use them, you would have a hard time reading the code; but do, please, try to avoid using these terms yourself. The people who come after you will be grateful to you.) When @code{car} and @code{cdr} are applied to a list made up of symbols, such as the list @code{(pine fir oak maple)}, the element of the list returned by the function @code{car} is the symbol @code{pine} without any parentheses around it. @code{pine} is the first element in the list. However, the @sc{cdr} of the list is a list itself, @code{(fir oak maple)}, as you can see by evaluating the following expressions in the usual way: @smallexample @group (car '(pine fir oak maple)) (cdr '(pine fir oak maple)) @end group @end smallexample On the other hand, in a list of lists, the first element is itself a list. @code{car} returns this first element as a list. For example, the following list contains three sub-lists, a list of carnivores, a list of herbivores and a list of sea mammals: @smallexample @group (car '((lion tiger cheetah) (gazelle antelope zebra) (whale dolphin seal))) @end group @end smallexample @noindent In this example, the first element or @sc{car} of the list is the list of carnivores, @code{(lion tiger cheetah)}, and the rest of the list is @code{((gazelle antelope zebra) (whale dolphin seal))}. @smallexample @group (cdr '((lion tiger cheetah) (gazelle antelope zebra) (whale dolphin seal))) @end group @end smallexample It is worth saying again that @code{car} and @code{cdr} are non-destructive---that is, they do not modify or change lists to which they are applied. This is very important for how they are used. Also, in the first chapter, in the discussion about atoms, I said that 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 Lisp is concerned, the atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The @code{car} and @code{cdr} functions are used for splitting lists and are considered fundamental to Lisp. Since they cannot split or gain access to the parts of an array, an array is considered an atom. Conversely, the other fundamental function, @code{cons}, can put together or construct a list, but not an array. (Arrays are handled by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU Emacs Lisp Reference Manual}.) @node cons, nthcdr, car & cdr, car cdr & cons @comment node-name, next, previous, up @section @code{cons} @findex cons, @r{introduced} The @code{cons} function constructs lists; it is the inverse of @code{car} and @code{cdr}. For example, @code{cons} can be used to make a four element list from the three element list, @code{(fir oak maple)}: @smallexample (cons 'pine '(fir oak maple)) @end smallexample @need 800 @noindent After evaluating this list, you will see @smallexample (pine fir oak maple) @end smallexample @noindent appear in the echo area. @code{cons} causes the creation of a new list in which the element is followed by the elements of the original list. We often say that `@code{cons} puts a new element at the beginning of a list; it attaches or pushes elements onto the list', but this phrasing can be misleading, since @code{cons} does not change an existing list, but creates a new one. Like @code{car} and @code{cdr}, @code{cons} is non-destructive. @menu * Build a list:: * length:: How to find the length of a list. @end menu @node Build a list, length, cons, cons @ifnottex @unnumberedsubsec Build a list @end ifnottex @code{cons} must have a list to attach to.@footnote{Actually, you can @code{cons} an element to an atom to produce a dotted pair. Dotted pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You cannot start from absolutely nothing. If you are building a list, you need to provide at least an empty list at the beginning. Here is a series of @code{cons} expressions that build up a list of flowers. If you are reading this in Info in GNU Emacs, you can evaluate each of the expressions in the usual way; the value is printed in this text after @samp{@result{}}, which you may read as `evaluates to'. @smallexample @group (cons 'buttercup ()) @result{} (buttercup) @end group @group (cons 'daisy '(buttercup)) @result{} (daisy buttercup) @end group @group (cons 'violet '(daisy buttercup)) @result{} (violet daisy buttercup) @end group @group (cons 'rose '(violet daisy buttercup)) @result{} (rose violet daisy buttercup) @end group @end smallexample @noindent In the first example, the empty list is shown as @code{()} and a list made up of @code{buttercup} followed by the empty list is constructed. As you can see, the empty list is not shown in the list that was constructed. All that you see is @code{(buttercup)}. The empty list is not counted as an element of a list because there is nothing in an empty list. Generally speaking, an empty list is invisible. The second example, @code{(cons 'daisy '(buttercup))} constructs a new, two element list by putting @code{daisy} in front of @code{buttercup}; and the third example constructs a three element list by putting @code{violet} in front of @code{daisy} and @code{buttercup}. @node length, , Build a list, cons @comment node-name, next, previous, up @subsection Find the Length of a List: @code{length} @findex length You can find out how many elements there are in a list by using the Lisp function @code{length}, as in the following examples: @smallexample @group (length '(buttercup)) @result{} 1 @end group @group (length '(daisy buttercup)) @result{} 2 @end group @group (length (cons 'violet '(daisy buttercup))) @result{} 3 @end group @end smallexample @noindent In the third example, the @code{cons} function is used to construct a three element list which is then passed to the @code{length} function as its argument. @need 1200 We can also use @code{length} to count the number of elements in an empty list: @smallexample @group (length ()) @result{} 0 @end group @end smallexample @noindent As you would expect, the number of elements in an empty list is zero. An interesting experiment is to find out what happens if you try to find the length of no list at all; that is, if you try to call @code{length} without giving it an argument, not even an empty list: @smallexample (length ) @end smallexample @need 800 @noindent What you see, if you evaluate this, is the error message @smallexample Wrong number of arguments: #, 0 @end smallexample @noindent This means that the function receives the wrong number of arguments, zero, when it expects some other number of arguments. In this case, one argument is expected, the argument being a list whose length the function is measuring. (Note that @emph{one} list is @emph{one} argument, even if the list has many elements inside it.) The part of the error message that says @samp{#} is the name of the function. This is written with a special notation, @samp{#