home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 2001 May / SGI Freeware 2001 May - Disc 3.iso / dist / fw_elisp-intro.idb / usr / freeware / info / emacs-lisp-intro.info-2.z / emacs-lisp-intro.info-2
Encoding:
GNU Info File  |  1998-10-28  |  47.9 KB  |  1,099 lines

  1. This is Info file emacs-lisp-intro.info, produced by Makeinfo version
  2. 1.67 from the input file emacs-lisp-intro.texi.
  3.  
  4.    This is an introduction to `Programming in Emacs Lisp', for people
  5. who are not programmers.
  6.  
  7.    Edition 1.05, 21 October 1997
  8.  
  9.    Copyright (C) 1990, '91, '92, '93, '94, '95, '97 Free Software
  10. Foundation, Inc.
  11.  
  12.    Permission is granted to make and distribute verbatim copies of this
  13. manual provided the copyright notice and this permission notice are
  14. preserved on all copies.
  15.  
  16.    Permission is granted to copy and distribute modified versions of
  17. this manual under the conditions for verbatim copying, provided also
  18. that the sections entitled "Copying" and "GNU General Public License"
  19. are included exactly as in the original, and provided that the entire
  20. resulting derived work is distributed under the terms of a permission
  21. notice identical to this one.
  22.  
  23.    Permission is granted to copy and distribute translations of this
  24. manual into another language, under the above conditions for modified
  25. versions, except that this permission notice may be stated in a
  26. translation approved by the Free Software Foundation.
  27.  
  28. 
  29. File: emacs-lisp-intro.info,  Node: Evaluating Inner Lists,  Prev: Evaluation,  Up: Evaluation
  30.  
  31. Evaluating Inner Lists
  32. ----------------------
  33.  
  34.    If evaluation applies to a list that is inside another list, the
  35. outer list may use the value returned by the first evaluation as
  36. information when the outer list is evaluated.  This explains why inner
  37. expressions are evaluated first: the values they return are used by the
  38. outer expressions.
  39.  
  40.    We can investigate this process by evaluating another addition
  41. example.  Place your cursor after the following expression and type
  42. `C-x C-e':
  43.  
  44.      (+ 2 (+ 3 3))
  45.  
  46. The number 8 will appear in the echo area.
  47.  
  48.    What happens is that the Lisp interpreter first evaluates the inner
  49. expression, `(+ 3 3)', for which the value 6 is returned; then it
  50. evaluates the outer expression as if it were written `(+ 2 6)', which
  51. returns the value 8.  Since there are no more enclosing expressions to
  52. evaluate, the interpreter prints that value in the echo area.
  53.  
  54.    Now it is easy to understand the name of the command invoked by the
  55. keystrokes `C-x C-e': the name is `eval-last-sexp'.  The letters `sexp'
  56. are an abbreviation for `symbolic expression', and `eval' is an
  57. abbreviation for `evaluate'.  The command means `evaluate last symbolic
  58. expression'.
  59.  
  60.    As an experiment, you can try evaluating the expression by putting
  61. the cursor at the beginning of the next line immediately following the
  62. expression, or inside the expression.
  63.  
  64.    Here is another copy of the expression:
  65.  
  66.      (+ 2 (+ 3 3))
  67.  
  68. If you place the cursor at the beginning of the blank line that
  69. immediately follows the expression and type `C-x C-e', you will still
  70. get the value 8 printed in the echo area.  Now try putting the cursor
  71. inside the expression.  If you put it right after the next to last
  72. parenthesis (so it appears to sit on top of the last parenthesis), you
  73. will get a 6 printed in the echo area!  This is because the command
  74. evaluates the expression `(+ 3 3)'.
  75.  
  76.    Now put the cursor immediately after a number.  Type `C-x C-e' and
  77. you will get the number itself.  In Lisp, if you evaluate a number, you
  78. get the number itself--this is how numbers differ from symbols.  If you
  79. evaluate a list starting with a symbol like `+', you will get a value
  80. returned that is the result of the computer carrying out the
  81. instructions in the function definition attached to that name.  If a
  82. symbol by itself is evaluated, something different happens, as we will
  83. see in the next section.
  84.  
  85. 
  86. File: emacs-lisp-intro.info,  Node: Variables,  Next: Arguments,  Prev: Evaluation,  Up: List Processing
  87.  
  88. Variables
  89. =========
  90.  
  91.    In Lisp, a symbol can have a value attached to it just as it can
  92. have a function definition attached to it.  The two are different.  The
  93. function definition is a set of instructions that a computer will obey.
  94. A value, on the other hand, is something, such as number or a name, that
  95. can vary (which is why such a symbol is called a variable).  The value
  96. of a symbol can be any expression in Lisp, such as a symbol, number,
  97. list, or string.  A symbol that has a value is often called a
  98. "variable".
  99.  
  100.    A symbol can have both a function definition and a value attached to
  101. it at the same time.  The two are separate.  This is somewhat similar
  102. to the way the name Cambridge can refer to the city in Massachusetts
  103. and have some information attached to the name as well, such as "great
  104. programming center".
  105.  
  106.    Another way of thinking of this is to imagine a symbol as being a
  107. chest of drawers.  The function definition is put in one drawer, the
  108. value in another, and so on.  What is put in the drawer holding the
  109. value can be changed without affecting the contents of the drawer
  110. holding the function definition, and vice-versa.
  111.  
  112.    The variable `fill-column' illustrates a symbol with a value
  113. attached to it: in every GNU Emacs buffer, this symbol is set to some
  114. value, usually 72 or 70, but sometimes to some other value.  To find the
  115. value of this symbol, evaluate it by itself.  If you are reading this in
  116. Info inside of GNU Emacs, you can do this by putting the cursor after
  117. the symbol and typing `C-x C-e':
  118.  
  119.      fill-column
  120.  
  121. After I typed `C-x C-e', Emacs printed the number 72 in my echo area.
  122. This is the value for which `fill-column' is set for me as I write
  123. this.  It may be different for you in your Info buffer.  Notice that
  124. the value returned as a variable is printed in exactly the same way as
  125. the value returned by a function carrying out its instructions.  From
  126. the point of view of the Lisp interpreter, a value returned is a value
  127. returned.  What kind of expression it came from ceases to matter once
  128. the value is known.
  129.  
  130.    A symbol can have any value attached to it or, to use the jargon, we
  131. can "bind" the variable to a value: to a number, such as 72; to a
  132. string, `"such as this"'; to a list, such as `(spruce pine oak)'; we
  133. can even bind a variable to a function definition.
  134.  
  135.    A symbol can be bound to a value in several ways.  *Note Setting the
  136. Value of a Variable: set & setq, for information about one way to do
  137. this.
  138.  
  139.    Notice that there were no parentheses around the word `fill-column'
  140. when we evaluated it to find its value.  This is because we did not
  141. intend to use it as a function name.  If `fill-column' were the first or
  142. only element of a list, the Lisp interpreter would attempt to find the
  143. function definition attached to it.  But `fill-column' has no function
  144. definition.  Try evaluating this:
  145.  
  146.      (fill-column)
  147.  
  148. You will produce an error message that says:
  149.  
  150.      Symbol's function definition is void: fill-column
  151.  
  152. * Menu:
  153.  
  154. * Void Variable::               The error message for a symbol without a value.
  155.  
  156. 
  157. File: emacs-lisp-intro.info,  Node: Void Variable,  Prev: Variables,  Up: Variables
  158.  
  159. Error Message for a Symbol Without a Value
  160. ------------------------------------------
  161.  
  162.    If you attempt to evaluate a symbol that does not have a value bound
  163. to it, you will receive an error message.  You can see this by
  164. experimenting with our 2 plus 2 addition.  In the following expression,
  165. put your cursor right after the `+', before the first number 2, type
  166. `C-x C-e':
  167.  
  168.      (+ 2 2)
  169.  
  170. You will get an error message that says:
  171.  
  172.      Symbol's value as variable is void: +
  173.  
  174. This is different from the first error message we saw, which said,
  175. `Symbol's function definition is void: this'.  In this case, the symbol
  176. does not have a value as a variable; in the other case, the symbol
  177. (which was the word `this') did not have a function definition.
  178.  
  179.    In this experiment with the `+', what we did was cause the Lisp
  180. interpreter to evaluate the `+' and look for the value of the variable
  181. instead of the function definition.  We did this by placing the cursor
  182. right after the symbol rather than after the parenthesis of the
  183. enclosing list as we did before.  As a consequence, the Lisp interpreter
  184. evaluated the preceding s-expression, which in this case was the `+' by
  185. itself.
  186.  
  187.    Since `+' does not have a value bound to it, just the function
  188. definition, the error message reported that the symbol's value as a
  189. variable was void.
  190.  
  191. 
  192. File: emacs-lisp-intro.info,  Node: Arguments,  Next: set & setq,  Prev: Variables,  Up: List Processing
  193.  
  194. Arguments
  195. =========
  196.  
  197.    To see how information is passed to functions, let's look again at
  198. our old standby, the addition of two plus two.  In Lisp, this is written
  199. as follows:
  200.  
  201.      (+ 2 2)
  202.  
  203.    If you evaluate this expression, the number 4 will appear in your
  204. echo area.  What the Lisp interpreter does is add the numbers that
  205. follow the `+'.
  206.  
  207.    The numbers added by `+' are called the "arguments" of the function
  208. `+'.  These numbers are the information that is given to or "passed" to
  209. the function.
  210.  
  211.    The word `argument' comes from the way it is used in mathematics and
  212. does not refer to a disputation between two people; instead it refers to
  213. the information presented to the function, in this case, to the `+'.
  214. In Lisp, the arguments to a function are the atoms or lists that follow
  215. the function.  The values returned by the evaluation of these atoms or
  216. lists are passed to the function.  Different functions require
  217. different numbers of arguments; some functions require none at all.(1)
  218.  
  219. * Menu:
  220.  
  221. * Data types::                  Types of data passed to a function.
  222. * Args as Variable or List::    An argument can be the value
  223.                                 of a variable or list.
  224. * Variable Number of Arguments::  Some functions may take a
  225.                                 variable number of arguments.
  226. * Wrong Type of Argument::      Passing an argument of the wrong type
  227.                                 to a function.
  228. * message::                     A useful function for sending messages.
  229.  
  230.    ---------- Footnotes ----------
  231.  
  232.    (1)  It is curious to track the path by which the word `argument'
  233. came to have two different meanings, one in mathematics and the other in
  234. everyday English.  According to the `Oxford English Dictionary', the
  235. word derives from the Latin for `to make clear, prove'; thus it came to
  236. mean, by one thread of derivation, `the evidence offered as proof',
  237. which is to say, `the information offered', which led to its meaning in
  238. Lisp.  But in the other thread of derivation, it came to mean `to
  239. assert in a manner against which others may make counter assertions',
  240. which led to the meaning of the word as a disputation.  (Note here that
  241. the English word has two different definitions attached to it at the
  242. same time.  By contrast, in Emacs Lisp, a symbol cannot have two
  243. different function definitions at the same time.)
  244.  
  245. 
  246. File: emacs-lisp-intro.info,  Node: Data types,  Next: Args as Variable or List,  Prev: Arguments,  Up: Arguments
  247.  
  248. Arguments' Data Types
  249. ---------------------
  250.  
  251.    The type of data that should be passed to a function depends on what
  252. kind of information it uses.  The arguments to a function such as `+'
  253. must have values that are numbers, since `+' adds numbers.  Other
  254. functions use different kinds of data for their arguments.
  255.  
  256.    For example, the `concat' function links together or unites two or
  257. more strings of text to produce a string.  The arguments are strings.
  258. Concatenating the two character strings `abc', `def' produces the
  259. single string `abcdef'.  This can be seen by evaluating the following:
  260.  
  261.      (concat "abc" "def")
  262.  
  263. The value produced by evaluating this expression is `"abcdef"'.
  264.  
  265.    A function such as `substring' uses both a string and numbers as
  266. arguments.  The function returns a part of the string, a substring of
  267. the first argument.  This function takes three arguments.  Its first
  268. argument is the string of characters, the second and third arguments are
  269. numbers that indicate the beginning and end of the substring.  The
  270. numbers are a count of the number of characters (including spaces and
  271. punctuations) from the beginning of the string.
  272.  
  273.    For example, if you evaluate the following:
  274.  
  275.      (substring "The quick brown fox jumped." 16 19)
  276.  
  277. you will see `"fox"' appear in the echo area.  The arguments are the
  278. string and the two numbers.
  279.  
  280.    Note that the string passed to `substring' is a single atom even
  281. though it is made up of several words separated by spaces.  Lisp counts
  282. everything between the two quotation marks as part of the string,
  283. including the spaces.  You can think of the `substring' function as a
  284. kind of `atom smasher' since it takes an otherwise indivisible atom and
  285. extracts a part.  However, `substring' is only able to extract a
  286. substring from an argument that is a string, not from another type of
  287. atom such as a number or symbol.
  288.  
  289. 
  290. File: emacs-lisp-intro.info,  Node: Args as Variable or List,  Next: Variable Number of Arguments,  Prev: Data types,  Up: Arguments
  291.  
  292. An Argument as the Value of a Variable or List
  293. ----------------------------------------------
  294.  
  295.    An argument can be a symbol that returns a value when it is
  296. evaluated.  For example, when the symbol `fill-column' by itself is
  297. evaluated, it returns a number.  This number can be used in an
  298. addition.  Position the cursor after the following expression and type
  299. `C-x C-e':
  300.  
  301.      (+ 2 fill-column)
  302.  
  303. The value will be a number two more than what you get by evaluating
  304. `fill-column' alone.  For me, this is 74, because the value of
  305. `fill-column' is 72.
  306.  
  307.    As we have just seen, an argument can be a symbol that returns a
  308. value when evaluated.  In addition, an argument can be a list that
  309. returns a value when it is evaluated.  For example, in the following
  310. expression, the arguments to the function `concat' are the strings
  311. `"The "' and `" red foxes."' and the list `(+ 2 fill-column)'.
  312.  
  313.      (concat "The " (+ 2 fill-column) " red foxes.")
  314.  
  315. If you evaluate this expression, `"The 74 red foxes."' will appear in
  316. the echo area.  (Note that you must put spaces after the word `The' and
  317. before the word `red' so they will appear in the final string.)
  318.  
  319. 
  320. File: emacs-lisp-intro.info,  Node: Variable Number of Arguments,  Next: Wrong Type of Argument,  Prev: Args as Variable or List,  Up: Arguments
  321.  
  322. Variable Number of Arguments
  323. ----------------------------
  324.  
  325.    Some functions, such as `concat', `+' or `*', take any number of
  326. arguments.  (The `*' is the symbol for multiplication.) This can be
  327. seen by evaluating each of the following expressions in the usual way.
  328. What you will see in the echo area is printed in this text after `=>',
  329. which you may read as `evaluates to'.
  330.  
  331.    In the first set, the functions have no arguments:
  332.  
  333.      (+)       => 0
  334.      
  335.      (*)       => 1
  336.  
  337.    In this set, the functions have one argument each:
  338.  
  339.      (+ 3)     => 3
  340.      
  341.      (* 3)     => 3
  342.  
  343.    In this set, the functions have three arguments each:
  344.  
  345.      (+ 3 4 5) => 12
  346.      
  347.      (* 3 4 5) => 60
  348.  
  349. 
  350. File: emacs-lisp-intro.info,  Node: Wrong Type of Argument,  Next: message,  Prev: Variable Number of Arguments,  Up: Arguments
  351.  
  352. Using the Wrong Type Object as an Argument
  353. ------------------------------------------
  354.  
  355.    When a function is passed an argument of the wrong type, the Lisp
  356. interpreter produces an error message.  For example, the `+' function
  357. expects the values of its arguments to be numbers.  As an experiment we
  358. can pass it the quoted symbol `hello' instead of a number.  Position
  359. the cursor after the following expression and type `C-x C-e':
  360.  
  361.      (+ 2 'hello)
  362.  
  363. When you do this you will generate an error message.  What has happened
  364. is that `+' has tried to add the 2 to the value returned by `'hello',
  365. but the value returned by `'hello' is the symbol `hello', not a number.
  366. Only numbers can be added.  So `+' could not carry out its addition.
  367.  
  368.    As usual, the error message tries to be helpful and makes sense
  369. after you learn how to read it.  What it says is this:
  370.  
  371.      Wrong type argument: integer-or-marker-p, hello
  372.  
  373.    The first part of the error message is straightforward; it says
  374. `Wrong type argument'.  Next comes the mysterious jargon word
  375. `integer-or-marker-p'.  This word is trying to tell you what kind of
  376. argument the `+' expected.
  377.  
  378.    The symbol `integer-or-marker-p' says that the Lisp interpreter is
  379. trying to determine whether the information presented it (the value of
  380. the argument) is an integer (that is, a whole number) or a marker (a
  381. special object representing a buffer position).  What it does is test to
  382. see whether the `+' is being given whole numbers to add.  It also tests
  383. to see whether the argument is something called a marker, which is a
  384. specific feature of Emacs Lisp.  (In Emacs, locations in a buffer are
  385. recorded as markers.  When the mark is set with the `C-@' or `C-<SPC>'
  386. command, its position is kept as a marker.  The mark can be considered
  387. a number--the number of characters the location is from the beginning
  388. of the buffer.)  In Emacs Lisp, `+' can be used to add the numeric
  389. value of marker positions as numbers.
  390.  
  391.    The `p' of `integer-or-marker-p' is the embodiment of a practice
  392. started in the early days of Lisp programming.  The `p' stands for
  393. `predicate'.  In the jargon used by the early Lisp researchers, a
  394. predicate refers to a function to determine whether some property is
  395. true or false.  So the `p' tells us that `integer-or-marker-p' is the
  396. name of a function that determines whether it is true or false that the
  397. argument supplied is an integer or a marker.  Other Lisp symbols that
  398. end in `p' include `zerop', a function that tests whether its argument
  399. has the value of zero, and `listp', a function that tests whether its
  400. argument is a list.
  401.  
  402.    Finally, the last part of the error message is the symbol `hello'.
  403. This is the value of the argument that was passed to `+'.  If the
  404. addition had been passed the correct type of object, the value passed
  405. would have been a number, such as 37, rather than a symbol like
  406. `hello'.  But then you would not have got the error message.
  407.  
  408. 
  409. File: emacs-lisp-intro.info,  Node: message,  Prev: Wrong Type of Argument,  Up: Arguments
  410.  
  411. The `message' Function
  412. ----------------------
  413.  
  414.    Like `+', the `message' function takes a variable number of
  415. arguments.  It is used to send messages to the user and is so useful
  416. that we will describe it here.
  417.  
  418.    A message is printed in the echo area.  For example, you can print a
  419. message in your echo area by evaluating the following list:
  420.  
  421.      (message "This message appears in the echo area!")
  422.  
  423.    The whole string between double quotation marks is a single argument
  424. and is printed in toto.  (Note that in this example, the message itself
  425. will appear in the echo area within double quotes; that is because you
  426. see the value returned by the `message' function.  In most uses of
  427. `message' in programs that you write, the text will be printed in the
  428. echo area as a side-effect, without the quotes.  *Note
  429. `multiply-by-seven' in detail: multiply-by-seven in detail, for an
  430. example of this.)
  431.  
  432.    However, if there is a `%s' in the quoted string of characters, the
  433. `message' function does not print the `%s' as such, but looks to the
  434. argument that follows the string.  It evaluates the second argument and
  435. prints the value in the location in the string where the `%s' is.
  436.  
  437.    You can see this by positioning the cursor after the following
  438. expression and typing `C-x C-e':
  439.  
  440.      (message "The name of this buffer is: %s." (buffer-name))
  441.  
  442. In Info, `"The name of this buffer is: *info*."' will appear in the
  443. echo area.  The function `buffer-name' returns the name of the buffer
  444. as a string, which the `message' function inserts in place of `%s'.
  445.  
  446.    To print a value as a decimal number, use `%d' in the same way as
  447. `%s'.  For example, to print a message in the echo area that states the
  448. value of the `fill-column', evaluate the following:
  449.  
  450.      (message "The value of fill-column is %d." fill-column)
  451.  
  452. On my system, when I evaluate this list, `"The value of fill-column is
  453. 72."' appears in my echo area.
  454.  
  455.    If there is more than one `%s' in the quoted string, the value of
  456. the first argument following the quoted string is printed at the
  457. location of the first `%s' and the value of the second argument is
  458. printed at the location of the second `%s', and so on.  For example, if
  459. you evaluate the following,
  460.  
  461.      (message "There are %d %s in the office!"
  462.               (- fill-column 14) "pink elephants")
  463.  
  464. a rather whimsical message will appear in your echo area.  On my system
  465. it says, `"There are 58 pink elephants in the office!"'.
  466.  
  467.    The expression `(- fill-column 14)' is evaluated and the resulting
  468. number is inserted in place of the `%d'; and the string in double
  469. quotes, `"pink elephants"', is treated as a single argument and
  470. inserted in place of the `%s'.  (That is to say, a string between
  471. double quotes evaluates to itself, like a number.)
  472.  
  473.    Finally, here is a somewhat complex example that not only illustrates
  474. the computation of a number, but also shows how you can use an
  475. expression within an expression to generate the text that is substituted
  476. for `%s':
  477.  
  478.      (message "He saw %d %s"
  479.               (- fill-column 34)
  480.               (concat "red "
  481.                       (substring
  482.                        "The quick brown foxes jumped." 16 21)
  483.                       " leaping."))
  484.  
  485.    In this example, `message' has three arguments: the string, `"He saw
  486. %d %s"', the expression, `(- fill-column 32)', and the expression
  487. beginning with the function `concat'.  The value resulting from the
  488. evaluation of `(- fill-column 32)' is inserted in place of the `%d';
  489. and the value returned by the expression beginning with `concat' is
  490. inserted in place of the `%s'.
  491.  
  492.    When I evaluate the expression, the message, `"He saw 38 red foxes
  493. leaping."', appears in my echo area.
  494.  
  495. 
  496. File: emacs-lisp-intro.info,  Node: set & setq,  Next: Summary,  Prev: Arguments,  Up: List Processing
  497.  
  498. Setting the Value of a Variable
  499. ===============================
  500.  
  501.    There are several ways by which a variable can be given a value.
  502. One of the ways is to use either the function `set' or the function
  503. `setq'.  Another way is to use `let' (*note let::.).  (The jargon for
  504. this process is to "bind" a variable to a value.)
  505.  
  506.    The following sections not only describe how `set' and `setq' work
  507. but also illustrate how arguments are passed.
  508.  
  509. * Menu:
  510.  
  511. * Using set::                   Setting values.
  512. * Using setq::                  Setting a quoted value.
  513. * Counting::                    Using `setq' to count.
  514.  
  515. 
  516. File: emacs-lisp-intro.info,  Node: Using set,  Next: Using setq,  Prev: set & setq,  Up: set & setq
  517.  
  518. Using `set'
  519. -----------
  520.  
  521.    To set the value of the symbol `flowers' to the list `'(rose violet
  522. daisy buttercup)', evaluate the following expression by positioning the
  523. cursor after the expression and typing `C-x C-e'.
  524.  
  525.      (set 'flowers '(rose violet daisy buttercup))
  526.  
  527. The list `(rose violet daisy buttercup)' will appear in the echo area.
  528. This is what is *returned* by the `set' function.  As a side effect,
  529. the symbol `flowers' is bound to the list ; that is, the symbol
  530. `flowers', which can be viewed as a variable, is given the list as its
  531. value.  (This process, by the way, illustrates how a side effect to the
  532. Lisp interpreter, setting the value, can be the primary effect that we
  533. humans are interested in.  This is because every Lisp function must
  534. return a value if it does not get an error, but it will only have a
  535. side effect if it is designed to have one.)
  536.  
  537.    After evaluating the `set' expression, you can evaluate the symbol
  538. `flowers' and it will return the value you just set.  Here is the
  539. symbol.  Place your cursor after it and type `C-x C-e'.
  540.  
  541.      flowers
  542.  
  543. When you evaluate `flowers', the list `(rose violet daisy buttercup)'
  544. appears in the echo area.
  545.  
  546.    Incidentally, if you evaluate `'flowers', the variable with a quote
  547. in front of it, what you will see in the echo area is the symbol itself,
  548. `flowers'.  Here is the quoted symbol, so you can try this:
  549.  
  550.      'flowers
  551.  
  552.    Note also, that when you use `set', you need to quote both arguments
  553. to `set', unless you want them evaluated.  In this case, we do not want
  554. either argument evaluated, neither the variable `flowers' nor the list
  555. `(rose violet daisy buttercup)', so both are quoted.  (When you use
  556. `set' without quoting its first argument, the first argument is
  557. evaluated before anything else is done.  If you did this and `flowers'
  558. did not have a value already, you would get an error message that the
  559. `Symbol's value as variable is void'; on the other hand, if `flowers'
  560. did return a value after it was evaluated, the `set' would attempt to
  561. set the value that was returned.  There are situations where this is
  562. the right thing for the function to do; but such situations are rare.)
  563.  
  564. 
  565. File: emacs-lisp-intro.info,  Node: Using setq,  Next: Counting,  Prev: Using set,  Up: set & setq
  566.  
  567. Using `setq'
  568. ------------
  569.  
  570.    As a practical matter, you almost always quote the first argument to
  571. `set'.  The combination of `set' and a quoted first argument is so
  572. common that it has its own name: the special form `setq'.  This special
  573. form is just like `set' except that the first argument is quoted
  574. automatically, so you don't need to type the quote mark yourself.
  575. Also, as an added convenience, `setq' permits you to set several
  576. different variables to different values, all in one expression.
  577.  
  578.    To set the value of the variable `carnivores' to the list `'(lion
  579. tiger leopard)' using `setq', the following expression is used:
  580.  
  581.      (setq carnivores '(lion tiger leopard))
  582.  
  583. This is exactly the same as using `set' except the first argument is
  584. automatically quoted by `setq'.  (The `q' in `setq' means `quote'.)
  585. With `set', the expression would look like this:
  586.  
  587.      (set 'carnivores '(lion tiger leopard))
  588.  
  589.    Also, `setq' can be used to assign different values to different
  590. variables.  The first argument is bound to the value of the second
  591. argument, the third argument is bound to the value of the fourth
  592. argument, and so on.  For example, you could use the following to
  593. assign a list of trees to the symbol `trees' and a list of herbivores
  594. to the symbol `herbivores':
  595.  
  596.      (setq trees '(pine fir oak maple)
  597.            herbivores '(gazelle antelope zebra))
  598.  
  599. (The expression could just as well have been on one line, but it might
  600. not have fit on a page; and humans find it easier to read nicely
  601. formatted lists.)
  602.  
  603.    Although I have been using the term `assign', there is another way of
  604. thinking about the workings of `set' and `setq'; and that is to say
  605. that `set' and `setq' make the symbol *point* to the list.  This latter
  606. way of thinking is very common and in forthcoming chapters we shall
  607. come upon at least one symbol that has `pointer' as part of its name.
  608. The name is chosen because the symbol has a value, specifically a list,
  609. attached to it; or, expressed in this other way, the symbol is set to
  610. "point" to the list.
  611.  
  612. 
  613. File: emacs-lisp-intro.info,  Node: Counting,  Prev: Using setq,  Up: set & setq
  614.  
  615. Counting
  616. --------
  617.  
  618.    Here is an example that shows how to use `setq' in a counter.  You
  619. might use this to count how many times a part of your program repeats
  620. itself.  First set a variable to zero; then add one to the number each
  621. time the program repeats itself.  To do this, you need a variable that
  622. serves as a counter, and two expressions: an initial `setq' expression
  623. that sets the counter variable to zero; and a second `setq' expression
  624. that increments the counter each time it is evaluated.
  625.  
  626.      (setq counter 0)                ; Let's call this the initializer.
  627.      
  628.      (setq counter (+ counter 1))    ; This is the incrementer.
  629.      
  630.      counter                         ; This is the counter.
  631.  
  632. (The text following the `;' are comments.  *Note Change a Function
  633. Definition: Change a defun.)
  634.  
  635.    If you evaluate the first of these expressions, the initializer,
  636. `(setq counter 0)', and then evaluate the third expression, `counter',
  637. the number `0' will appear in the echo area.  If you then evaluate the
  638. second expression, the incrementer, `(setq counter (+ counter 1))', the
  639. counter will get the value 1.  So if you again evaluate `counter', the
  640. number `1' will appear in the echo area.  Each time you evaluate the
  641. second expression, the value of the counter will be incremented.
  642.  
  643.    When you evaluate the incrementer, `(setq counter (+ counter 1))',
  644. the Lisp interpreter first evaluates the innermost list; this is the
  645. addition.  In order to evaluate this list, it must evaluate the variable
  646. `counter' and the number `1'.  When it evaluates the variable
  647. `counter', it receives its current value.  It passes this value and the
  648. number `1' to the `+' which adds them together.  The sum is then
  649. returned as the value of the inner list and passed to the `setq' which
  650. sets the variable `counter' to this new value.  Thus, the value of the
  651. variable, `counter', is changed.
  652.  
  653. 
  654. File: emacs-lisp-intro.info,  Node: Summary,  Next: Error Message Exercises,  Prev: set & setq,  Up: List Processing
  655.  
  656. Summary
  657. =======
  658.  
  659.    Learning Lisp is like climbing a hill in which the first part is the
  660. steepest.  You have now climbed the most difficult part; what remains
  661. becomes easier as you progress onwards.
  662.  
  663.    In summary,
  664.  
  665.    * Lisp programs are made up of expressions, which are lists or
  666.      single atoms.
  667.  
  668.    * Lists are made up of zero or more atoms or inner lists, separated
  669.      by whitespace and surrounded by parentheses.  A list can be empty.
  670.  
  671.    * Atoms are multi-character symbols, like `forward-paragraph', single
  672.      character symbols like `+', strings of characters between double
  673.      quotation marks, or numbers.
  674.  
  675.    * A number evaluates to itself.
  676.  
  677.    * A string between double quotes also evaluates to itself.
  678.  
  679.    * When you evaluate a symbol by itself, its value is returned.
  680.  
  681.    * When you evaluate a list, the Lisp interpreter looks at the first
  682.      symbol in the list and then at the function definition bound to
  683.      that symbol.  Then the instructions in the function definition are
  684.      carried out.
  685.  
  686.    * A single-quote, `'', tells the Lisp interpreter that it should
  687.      return the following expression as written, and not evaluate it as
  688.      it would if the quote were not there.
  689.  
  690.    * Arguments are the information passed to a function.  The arguments
  691.      to a function are computed by evaluating the rest of the elements
  692.      of the list of which the function is the first element.
  693.  
  694.    * A function always returns a value when it is evaluated (unless it
  695.      gets an error); in addition, it may also carry out some action
  696.      called a "side effect".  In many cases, a function's primary
  697.      purpose is to create a side effect.
  698.  
  699. 
  700. File: emacs-lisp-intro.info,  Node: Error Message Exercises,  Prev: Summary,  Up: List Processing
  701.  
  702. Exercises
  703. =========
  704.  
  705.    A few simple exercises:
  706.  
  707.    * Generate an error message by evaluating an appropriate symbol that
  708.      is not within parentheses.
  709.  
  710.    * Generate an error message by evaluating an appropriate symbol that
  711.      is between parentheses.
  712.  
  713.    * Create a counter that increments by two rather than one.
  714.  
  715.    * Write an expression that prints a message in the echo area when
  716.      evaluated.
  717.  
  718. 
  719. File: emacs-lisp-intro.info,  Node: Practicing Evaluation,  Next: Writing Defuns,  Prev: List Processing,  Up: Top
  720.  
  721. Practicing Evaluation
  722. *********************
  723.  
  724.    Before learning how to write a function definition in Emacs Lisp, it
  725. is useful to spend a little time evaluating various expressions that
  726. have already been written.  These expressions will be lists with the
  727. functions as their first (and often only) element.  Since some of the
  728. functions associated with buffers are both simple and interesting, we
  729. will start with those.  In this section, we will evaluate a few of
  730. these.  In another section, we will study the code of several other
  731. buffer-related functions, to see how they were written.
  732.  
  733. * Menu:
  734.  
  735. * How to Evaluate::             Typing editing commands or `C-x C-e'
  736.                                 causes evaluation.
  737. * Buffer Names::                Buffers and files are different.
  738. * Getting Buffers::             Getting a buffer itself, not merely its name.
  739. * Switching Buffers::           How to change to another buffer.
  740. * Buffer Size & Locations::     Where point is located and the size of
  741.                                 the buffer.
  742. * Evaluation Exercise::
  743.  
  744. 
  745. File: emacs-lisp-intro.info,  Node: How to Evaluate,  Next: Buffer Names,  Prev: Practicing Evaluation,  Up: Practicing Evaluation
  746.  
  747. How to Evaluate
  748. ===============
  749.  
  750.    Whenever you give an editing command to Emacs Lisp, such as the
  751. command to move the cursor or to scroll the screen, you are evaluating
  752. an expression, the first element of which is the function.  This is how
  753. Emacs works.
  754.  
  755.    When you type keys, you cause the Lisp interpreter to evaluate an
  756. expression and that is how you get your results.  Even typing plain text
  757. involves evaluating an Emacs Lisp function, in this case, one that uses
  758. `self-insert-command', which simply inserts the character you typed.
  759. The functions you evaluate by typing keystrokes are called
  760. "interactive" functions, or "commands"; how you make a function
  761. interactive will be illustrated in the chapter on how to write function
  762. definitions.  *Note Making a Function Interactive: Interactive.
  763.  
  764.    In addition to typing keyboard commands, we have seen a second way to
  765. evaluate an expression: by positioning the cursor after a list and
  766. typing `C-x C-e'.  This is what we will do in the rest of this section.
  767. There are other ways to evaluate an expression as well; these ways
  768. will be described in other sections as we come to them.
  769.  
  770.    Besides being used for practicing evaluation, the functions shown in
  771. the next few sections are important in their own right.  A study of
  772. these functions makes clear the distinction between buffers and files,
  773. how to switch to a buffer, and how to determine a location within it.
  774.  
  775. 
  776. File: emacs-lisp-intro.info,  Node: Buffer Names,  Next: Getting Buffers,  Prev: How to Evaluate,  Up: Practicing Evaluation
  777.  
  778. Buffer Names
  779. ============
  780.  
  781.    The two functions, `buffer-name' and `buffer-file-name', show the
  782. difference between a file and a buffer.  When you evaluate the
  783. following expression, `(buffer-name)', the name of the buffer appears
  784. in the echo area.  When you evaluate `(buffer-file-name)', the name of
  785. the file to which the buffer refers appears in the echo area.  Usually,
  786. the name returned by `(buffer-name)' is the same as the name of the
  787. file to which it refers, and the name returned by `(buffer-file-name)'
  788. is the full path-name of the file.
  789.  
  790.    A file and a buffer are two different entities.  A file is
  791. information recorded permanently in the computer (unless you delete
  792. it).  A buffer, on the other hand, is information inside of Emacs that
  793. will vanish at the end of the editing session (or when you kill the
  794. buffer).  Usually, a buffer contains information that you have copied
  795. from a file; we say the buffer is "visiting" that file.  This copy is
  796. what you work on and modify.  Changes to the buffer do not change the
  797. file, until you save the buffer.  When you save the buffer, the buffer
  798. is copied to the file and is thus saved permanently.
  799.  
  800.    If you are reading this in Info inside of GNU Emacs, you can evaluate
  801. each of the following expressions by positioning the cursor after it and
  802. typing `C-x C-e'.
  803.  
  804.      (buffer-name)
  805.      
  806.      (buffer-file-name)
  807.  
  808. When I do this, `"introduction.texinfo"' is the value returned by
  809. evaluating `(buffer-name)', and
  810. `"/gnu/work/intro/introduction.texinfo"' is the value returned by
  811. evaluating `(buffer-file-name)'.  The former is the name of the buffer
  812. and the latter is the name of the file.  (In the expressions, the
  813. parentheses tell the Lisp interpreter to treat `buffer-name' and
  814. `buffer-file-name' as functions; without the parentheses, the
  815. interpreter would attempt to evaluate the symbols as variables.  *Note
  816. Variables::.)
  817.  
  818.    In spite of the distinction between files and buffers, you will often
  819. find that people refer to a file when they mean a buffer and vice-versa.
  820. Indeed, most people say, "I am editing a file," rather than saying, "I
  821. am editing a buffer which I will soon save to a file."  It is almost
  822. always clear from context what people mean.  When dealing with computer
  823. programs, however, it is important to keep the distinction in mind,
  824. since the computer is not as smart as a person.
  825.  
  826.    The word `buffer', by the way, comes from the meaning of the word as
  827. a cushion that deadens the force of a collision.  In early computers, a
  828. buffer cushioned the interaction between files and the computer's
  829. central processing unit.  The drums or tapes that held a file and the
  830. central processing unit were pieces of equipment that were very
  831. different from each other, working at their own speeds, in spurts.  The
  832. buffer made it possible for them to work together effectively.
  833. Eventually, the buffer grew from being an intermediary, a temporary
  834. holding place, to being the place where work is done.  This
  835. transformation is rather like that of a small seaport that grew into a
  836. great city: once it was merely the place where cargo was warehoused
  837. temporarily before being loaded onto ships; then it became a business
  838. and cultural center in its own right.
  839.  
  840.    Not all buffers are associated with files.  For example, when you
  841. start an Emacs session by typing the command `emacs' alone, without
  842. naming any files, Emacs will start with the `*scratch*' buffer on the
  843. screen.  This buffer is not visiting any file.  Similarly, a `*Help*'
  844. buffer is not associated with any file.
  845.  
  846.    If you switch to the `*scratch*' buffer, type `(buffer-name)',
  847. position the cursor after it, and type `C-x C-e' to evaluate the
  848. expression, the name `"*scratch*"' is returned and will appear in the
  849. echo area.  `"*scratch*"' is the name of the buffer.  However, if you
  850. type `(buffer-file-name)' in the `*scratch*' buffer and evaluate that,
  851. `nil' will appear in the echo area.  `nil' is from the Latin word for
  852. `nothing'; in this case, it means that the `*scratch*' buffer is not
  853. associated with any file.  (In Lisp, `nil' is also used to mean `false'
  854. and is a synonym for the empty list, `()'.)
  855.  
  856.    Incidentally, if you are in the `*scratch*' buffer and want the
  857. value returned by an expression to appear in the `*scratch*' buffer
  858. itself rather than in the echo area, type `C-u C-x C-e' instead of `C-x
  859. C-e'.  This causes the value returned to appear after the expression.
  860. The buffer will look like this:
  861.  
  862.      (buffer-name)"*scratch*"
  863.  
  864. You cannot do this in Info since Info is read-only and it will not allow
  865. you to change the contents of the buffer.  But you can do this in any
  866. buffer you can edit; and when you write code or documentation (such as
  867. this manual), this feature is very useful.
  868.  
  869. 
  870. File: emacs-lisp-intro.info,  Node: Getting Buffers,  Next: Switching Buffers,  Prev: Buffer Names,  Up: Practicing Evaluation
  871.  
  872. Getting Buffers
  873. ===============
  874.  
  875.    The `buffer-name' function returns the *name* of the buffer; to get
  876. the buffer *itself*, a different function is needed: the
  877. `current-buffer' function.  If you use this function in code, what you
  878. get is the buffer itself.
  879.  
  880.    A name and the object or entity to which the name refers are
  881. different from each other.  You are not your name.  You are a person to
  882. whom others refer by name.  If you ask to speak to George and someone
  883. hands you a card with the letters `G', `e', `o', `r', `g', and `e'
  884. written on it, you might be amused, but you would not be satisfied.
  885. You do not want to speak to the name, but to the person to whom the
  886. name refers.  A buffer is similar: the name of the scratch buffer is
  887. `*scratch*', but the name is not the buffer.  To get a buffer itself,
  888. you need to use a function such as `current-buffer'.
  889.  
  890.    However, there is a slight complication: if you evaluate
  891. `current-buffer' in an expression on its own, as we will do here, what
  892. you see is a printed representation of the name of the buffer without
  893. the contents of the buffer.  Emacs works this way for two reasons: the
  894. buffer may be thousands of lines long--too long to be conveniently
  895. displayed; and, another buffer may have the same contents but a
  896. different name, and it is important to distinguish between them.
  897.  
  898.    Here is an expression containing the function:
  899.  
  900.      (current-buffer)
  901.  
  902. If you evaluate the expression in the usual way, `#<buffer *info*>'
  903. appears in the echo area.  The special format indicates that the buffer
  904. itself is being returned, rather than just its name.
  905.  
  906.    Incidentally, while you can type a number or symbol into a program,
  907. you cannot do that with the printed representation of a buffer: the
  908. only way to get a buffer itself is with a function such as
  909. `current-buffer'.
  910.  
  911.    A related function is `other-buffer'.  This returns the most
  912. recently selected buffer other than the one you are in currently.  If
  913. you have recently switched back and forth from the `*scratch*' buffer,
  914. `other-buffer' will return that buffer.
  915.  
  916.    You can see this by evaluating the expression:
  917.  
  918.      (other-buffer)
  919.  
  920. You should see `#<buffer *scratch*>' appear in the echo area, or the
  921. name of whatever other buffer you switched back from most recently.
  922.  
  923. 
  924. File: emacs-lisp-intro.info,  Node: Switching Buffers,  Next: Buffer Size & Locations,  Prev: Getting Buffers,  Up: Practicing Evaluation
  925.  
  926. Switching Buffers
  927. =================
  928.  
  929.    The `other-buffer' function actually provides a buffer when it is
  930. used as an argument to a function that requires one.  We can see this
  931. by using `other-buffer' and `switch-to-buffer' to switch to a different
  932. buffer.
  933.  
  934.    But first, a brief introduction to the `switch-to-buffer' function.
  935. When you switched back and forth from Info to the `*scratch*' buffer to
  936. evaluate `(buffer-name)', you most likely typed `C-x b' and then typed
  937. `*scratch*' when prompted in the minibuffer for the name of the buffer
  938. to which you wanted to switch.  The keystrokes, `C-x b', cause the Lisp
  939. interpreter to evaluate the interactive Emacs Lisp function
  940. `switch-to-buffer'.  As we said before, this is how Emacs works:
  941. different keystrokes call or run different functions.  For example,
  942. `C-f' calls `forward-char', `M-e' calls `forward-sentence', and so on.
  943.  
  944.    By writing `switch-to-buffer' in an expression, and giving it a
  945. buffer to switch to, we can switch buffers just the way `C-x b' does.
  946.  
  947.    Here is the Lisp expression:
  948.  
  949.      (switch-to-buffer (other-buffer))
  950.  
  951. The symbol `switch-to-buffer' is the first element of the list, so the
  952. Lisp interpreter will treat it as a function and carry out the
  953. instructions that are attached to it.  But before doing that, the
  954. interpreter will note that `other-buffer' is inside parentheses and
  955. work on that symbol first.  `other-buffer' is the first (and in this
  956. case, the only) element of this list, so the Lisp interpreter calls or
  957. runs the function.  It returns another buffer.  Next, the interpreter
  958. runs `switch-to-buffer', passing to it, as an argument, the other
  959. buffer, which is what Emacs will switch to.  If you are reading this in
  960. Info, try this now.  Evaluate the expression.  (To get back, type `C-x
  961. b <RET>'.)
  962.  
  963.    In the programming examples in later sections of this document, you
  964. will see the function `set-buffer' more often than `switch-to-buffer'.
  965. This is because of a difference between computer programs and humans:
  966. humans have eyes and expect to see the buffer on which they are working
  967. on their computer terminals.  This is so obvious, it almost goes
  968. without saying.  However, programs do not have eyes.  When a computer
  969. program works on a buffer, that buffer does not need to be visible on
  970. the screen.
  971.  
  972.    `switch-to-buffer' is designed for humans and does two different
  973. things: it switches the buffer to which Emacs attention is directed; and
  974. it switches the buffer displayed in the window to the new buffer.
  975. `set-buffer', on the other hand, does only one thing: it switches the
  976. attention of the computer program to a different buffer.  The buffer on
  977. the screen remains unchanged (of course, normally nothing happens there
  978. until the command finishes running).
  979.  
  980.    Also, we have just introduced another jargon term, the word "call".
  981. When you evaluate a list in which the first symbol is a function, you
  982. are calling that function.  The use of the term comes from the notion of
  983. the function as an entity that can do something for you if you `call'
  984. it--just as a plumber is an entity who can fix a leak if you call him
  985. or her.
  986.  
  987. 
  988. File: emacs-lisp-intro.info,  Node: Buffer Size & Locations,  Next: Evaluation Exercise,  Prev: Switching Buffers,  Up: Practicing Evaluation
  989.  
  990. Buffer Size and the Location of Point
  991. =====================================
  992.  
  993.    Finally, let's look at several rather simple functions,
  994. `buffer-size', `point', `point-min', and `point-max'.  These give
  995. information about the size of a buffer and the location of point within
  996. it.
  997.  
  998.    The function `buffer-size' tells you the size of the current buffer;
  999. that is, the function returns a count of the number of characters in
  1000. the buffer.
  1001.  
  1002.      (buffer-size)
  1003.  
  1004. You can evaluate this in the usual way, by positioning the cursor after
  1005. the expression and typing `C-x C-e'.
  1006.  
  1007.    In Emacs, the current  position of the cursor is called "point".
  1008. The expression `(point)' returns a number that tells you where the
  1009. cursor is located as a count of the number of characters from the
  1010. beginning of the buffer up to point.
  1011.  
  1012.    You can see the character count for point in this buffer by
  1013. evaluating the following expression in the usual way:
  1014.  
  1015.      (point)
  1016.  
  1017. As I write this, the value of `point' is 65724.  The `point' function
  1018. is frequently used in some of the examples later in this manual.
  1019.  
  1020.    The value of point depends, of course, on its location within the
  1021. buffer.  If you evaluate point in this spot, the number will be larger:
  1022.  
  1023.      (point)
  1024.  
  1025. For me, the value of point in this location is 66043, which means that
  1026. there are 319 characters (including spaces) between the two expressions.
  1027.  
  1028.    The function `point-min' is somewhat similar to `point', but it
  1029. returns the value of the minimum permissible value of point in the
  1030. current buffer.  This is the number 1 unless "narrowing" is in effect.
  1031. (Narrowing is a mechanism whereby you can restrict yourself, or a
  1032. program, to operations on just a part of a buffer.  *Note Narrowing and
  1033. Widening: Narrowing & Widening.)  Likewise, the function `point-max'
  1034. returns the value of the maximum permissible value of point in the
  1035. current buffer.
  1036.  
  1037. 
  1038. File: emacs-lisp-intro.info,  Node: Evaluation Exercise,  Prev: Buffer Size & Locations,  Up: Practicing Evaluation
  1039.  
  1040. Exercise
  1041. ========
  1042.  
  1043.    Find a file with which you are working and move towards its middle.
  1044. Find its buffer name, file name, length, and your position in the file.
  1045.  
  1046. 
  1047. File: emacs-lisp-intro.info,  Node: Writing Defuns,  Next: Buffer Walk Through,  Prev: Practicing Evaluation,  Up: Top
  1048.  
  1049. How To Write Function Definitions
  1050. *********************************
  1051.  
  1052.    When the Lisp interpreter evaluates a list, it looks to see whether
  1053. the first symbol on the list has a function definition attached to it;
  1054. or, put another way, whether the symbol points to a function
  1055. definition.  If it does, the computer carries out the instructions in
  1056. the definition.  A symbol that has a function definition is called,
  1057. simply, a function (although, properly speaking, the definition is the
  1058. function and the symbol refers to it.)
  1059.  
  1060. * Menu:
  1061.  
  1062. * Primitive Functions::         Some functions are written in C.
  1063. * defun::                       The `defun' special form.
  1064. * Install::                     Install a Function Definition.
  1065. * Interactive::                 Making a function interactive.
  1066. * Interactive Options::         Different options for `interactive'.
  1067. * Permanent Installation::      Installing code permanently.
  1068. * let::                         Creating and initializing local variables.
  1069. * if::                          What if?
  1070. * else::                        If-then-else expressions.
  1071. * Truth & Falsehood::           What Lisp considers false and true.
  1072. * save-excursion::              Keeping track of point, mark, and buffer.
  1073. * Review::
  1074. * defun Exercises::
  1075.  
  1076. 
  1077. File: emacs-lisp-intro.info,  Node: Primitive Functions,  Next: defun,  Prev: Writing Defuns,  Up: Writing Defuns
  1078.  
  1079. An Aside about Primitive Functions
  1080. ==================================
  1081.  
  1082.    All functions are defined in terms of other functions, except for a
  1083. few "primitive" functions that are written in the C programming
  1084. language.  When you write functions' definitions, you will write them in
  1085. Emacs Lisp and use other functions as your building blocks.  Some of the
  1086. functions you will use will themselves be written in Emacs Lisp (perhaps
  1087. by you) and some will be primitives written in C.  The primitive
  1088. functions are used exactly like those written in Emacs Lisp and behave
  1089. like them.  They are written in C so we can easily run GNU Emacs on any
  1090. computer that has sufficient power and can run C.
  1091.  
  1092.    Let me re-emphasize this: when you write code in Emacs Lisp, you do
  1093. not distinguish between the use of functions written in C and the use of
  1094. functions written in Emacs Lisp.  The difference is irrelevant.  I
  1095. mention the distinction only because it is interesting to know.  Indeed,
  1096. unless you investigate, you won't know whether an already-written
  1097. function is written in Emacs Lisp or C.
  1098.  
  1099.