control.texi 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. @c -*- mode: texinfo; coding: utf-8 -*-
  2. @c This is part of the GNU Emacs Lisp Reference Manual.
  3. @c Copyright (C) 1990-1995, 1998-1999, 2001-2016 Free Software
  4. @c Foundation, Inc.
  5. @c See the file elisp.texi for copying conditions.
  6. @node Control Structures
  7. @chapter Control Structures
  8. @cindex special forms for control structures
  9. @cindex control structures
  10. A Lisp program consists of a set of @dfn{expressions}, or
  11. @dfn{forms} (@pxref{Forms}). We control the order of execution of
  12. these forms by enclosing them in @dfn{control structures}. Control
  13. structures are special forms which control when, whether, or how many
  14. times to execute the forms they contain.
  15. @cindex textual order
  16. The simplest order of execution is sequential execution: first form
  17. @var{a}, then form @var{b}, and so on. This is what happens when you
  18. write several forms in succession in the body of a function, or at top
  19. level in a file of Lisp code---the forms are executed in the order
  20. written. We call this @dfn{textual order}. For example, if a function
  21. body consists of two forms @var{a} and @var{b}, evaluation of the
  22. function evaluates first @var{a} and then @var{b}. The result of
  23. evaluating @var{b} becomes the value of the function.
  24. Explicit control structures make possible an order of execution other
  25. than sequential.
  26. Emacs Lisp provides several kinds of control structure, including
  27. other varieties of sequencing, conditionals, iteration, and (controlled)
  28. jumps---all discussed below. The built-in control structures are
  29. special forms since their subforms are not necessarily evaluated or not
  30. evaluated sequentially. You can use macros to define your own control
  31. structure constructs (@pxref{Macros}).
  32. @menu
  33. * Sequencing:: Evaluation in textual order.
  34. * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}.
  35. * Combining Conditions:: @code{and}, @code{or}, @code{not}.
  36. * Iteration:: @code{while} loops.
  37. * Generators:: Generic sequences and coroutines.
  38. * Nonlocal Exits:: Jumping out of a sequence.
  39. @end menu
  40. @node Sequencing
  41. @section Sequencing
  42. @cindex sequencing
  43. @cindex sequential execution
  44. Evaluating forms in the order they appear is the most common way
  45. control passes from one form to another. In some contexts, such as in a
  46. function body, this happens automatically. Elsewhere you must use a
  47. control structure construct to do this: @code{progn}, the simplest
  48. control construct of Lisp.
  49. A @code{progn} special form looks like this:
  50. @example
  51. @group
  52. (progn @var{a} @var{b} @var{c} @dots{})
  53. @end group
  54. @end example
  55. @noindent
  56. and it says to execute the forms @var{a}, @var{b}, @var{c}, and so on, in
  57. that order. These forms are called the @dfn{body} of the @code{progn} form.
  58. The value of the last form in the body becomes the value of the entire
  59. @code{progn}. @code{(progn)} returns @code{nil}.
  60. @cindex implicit @code{progn}
  61. In the early days of Lisp, @code{progn} was the only way to execute
  62. two or more forms in succession and use the value of the last of them.
  63. But programmers found they often needed to use a @code{progn} in the
  64. body of a function, where (at that time) only one form was allowed. So
  65. the body of a function was made into an implicit @code{progn}:
  66. several forms are allowed just as in the body of an actual @code{progn}.
  67. Many other control structures likewise contain an implicit @code{progn}.
  68. As a result, @code{progn} is not used as much as it was many years ago.
  69. It is needed now most often inside an @code{unwind-protect}, @code{and},
  70. @code{or}, or in the @var{then}-part of an @code{if}.
  71. @defspec progn forms@dots{}
  72. This special form evaluates all of the @var{forms}, in textual
  73. order, returning the result of the final form.
  74. @example
  75. @group
  76. (progn (print "The first form")
  77. (print "The second form")
  78. (print "The third form"))
  79. @print{} "The first form"
  80. @print{} "The second form"
  81. @print{} "The third form"
  82. @result{} "The third form"
  83. @end group
  84. @end example
  85. @end defspec
  86. Two other constructs likewise evaluate a series of forms but return
  87. different values:
  88. @defspec prog1 form1 forms@dots{}
  89. This special form evaluates @var{form1} and all of the @var{forms}, in
  90. textual order, returning the result of @var{form1}.
  91. @example
  92. @group
  93. (prog1 (print "The first form")
  94. (print "The second form")
  95. (print "The third form"))
  96. @print{} "The first form"
  97. @print{} "The second form"
  98. @print{} "The third form"
  99. @result{} "The first form"
  100. @end group
  101. @end example
  102. Here is a way to remove the first element from a list in the variable
  103. @code{x}, then return the value of that former element:
  104. @example
  105. (prog1 (car x) (setq x (cdr x)))
  106. @end example
  107. @end defspec
  108. @defspec prog2 form1 form2 forms@dots{}
  109. This special form evaluates @var{form1}, @var{form2}, and all of the
  110. following @var{forms}, in textual order, returning the result of
  111. @var{form2}.
  112. @example
  113. @group
  114. (prog2 (print "The first form")
  115. (print "The second form")
  116. (print "The third form"))
  117. @print{} "The first form"
  118. @print{} "The second form"
  119. @print{} "The third form"
  120. @result{} "The second form"
  121. @end group
  122. @end example
  123. @end defspec
  124. @node Conditionals
  125. @section Conditionals
  126. @cindex conditional evaluation
  127. Conditional control structures choose among alternatives. Emacs Lisp
  128. has four conditional forms: @code{if}, which is much the same as in
  129. other languages; @code{when} and @code{unless}, which are variants of
  130. @code{if}; and @code{cond}, which is a generalized case statement.
  131. @defspec if condition then-form else-forms@dots{}
  132. @code{if} chooses between the @var{then-form} and the @var{else-forms}
  133. based on the value of @var{condition}. If the evaluated @var{condition} is
  134. non-@code{nil}, @var{then-form} is evaluated and the result returned.
  135. Otherwise, the @var{else-forms} are evaluated in textual order, and the
  136. value of the last one is returned. (The @var{else} part of @code{if} is
  137. an example of an implicit @code{progn}. @xref{Sequencing}.)
  138. If @var{condition} has the value @code{nil}, and no @var{else-forms} are
  139. given, @code{if} returns @code{nil}.
  140. @code{if} is a special form because the branch that is not selected is
  141. never evaluated---it is ignored. Thus, in this example,
  142. @code{true} is not printed because @code{print} is never called:
  143. @example
  144. @group
  145. (if nil
  146. (print 'true)
  147. 'very-false)
  148. @result{} very-false
  149. @end group
  150. @end example
  151. @end defspec
  152. @defmac when condition then-forms@dots{}
  153. This is a variant of @code{if} where there are no @var{else-forms},
  154. and possibly several @var{then-forms}. In particular,
  155. @example
  156. (when @var{condition} @var{a} @var{b} @var{c})
  157. @end example
  158. @noindent
  159. is entirely equivalent to
  160. @example
  161. (if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
  162. @end example
  163. @end defmac
  164. @defmac unless condition forms@dots{}
  165. This is a variant of @code{if} where there is no @var{then-form}:
  166. @example
  167. (unless @var{condition} @var{a} @var{b} @var{c})
  168. @end example
  169. @noindent
  170. is entirely equivalent to
  171. @example
  172. (if @var{condition} nil
  173. @var{a} @var{b} @var{c})
  174. @end example
  175. @end defmac
  176. @defspec cond clause@dots{}
  177. @code{cond} chooses among an arbitrary number of alternatives. Each
  178. @var{clause} in the @code{cond} must be a list. The @sc{car} of this
  179. list is the @var{condition}; the remaining elements, if any, the
  180. @var{body-forms}. Thus, a clause looks like this:
  181. @example
  182. (@var{condition} @var{body-forms}@dots{})
  183. @end example
  184. @code{cond} tries the clauses in textual order, by evaluating the
  185. @var{condition} of each clause. If the value of @var{condition} is
  186. non-@code{nil}, the clause succeeds; then @code{cond} evaluates its
  187. @var{body-forms}, and returns the value of the last of @var{body-forms}.
  188. Any remaining clauses are ignored.
  189. If the value of @var{condition} is @code{nil}, the clause fails, so
  190. the @code{cond} moves on to the following clause, trying its @var{condition}.
  191. A clause may also look like this:
  192. @example
  193. (@var{condition})
  194. @end example
  195. @noindent
  196. Then, if @var{condition} is non-@code{nil} when tested, the @code{cond}
  197. form returns the value of @var{condition}.
  198. If every @var{condition} evaluates to @code{nil}, so that every clause
  199. fails, @code{cond} returns @code{nil}.
  200. The following example has four clauses, which test for the cases where
  201. the value of @code{x} is a number, string, buffer and symbol,
  202. respectively:
  203. @example
  204. @group
  205. (cond ((numberp x) x)
  206. ((stringp x) x)
  207. ((bufferp x)
  208. (setq temporary-hack x) ; @r{multiple body-forms}
  209. (buffer-name x)) ; @r{in one clause}
  210. ((symbolp x) (symbol-value x)))
  211. @end group
  212. @end example
  213. Often we want to execute the last clause whenever none of the previous
  214. clauses was successful. To do this, we use @code{t} as the
  215. @var{condition} of the last clause, like this: @code{(t
  216. @var{body-forms})}. The form @code{t} evaluates to @code{t}, which is
  217. never @code{nil}, so this clause never fails, provided the @code{cond}
  218. gets to it at all. For example:
  219. @example
  220. @group
  221. (setq a 5)
  222. (cond ((eq a 'hack) 'foo)
  223. (t "default"))
  224. @result{} "default"
  225. @end group
  226. @end example
  227. @noindent
  228. This @code{cond} expression returns @code{foo} if the value of @code{a}
  229. is @code{hack}, and returns the string @code{"default"} otherwise.
  230. @end defspec
  231. Any conditional construct can be expressed with @code{cond} or with
  232. @code{if}. Therefore, the choice between them is a matter of style.
  233. For example:
  234. @example
  235. @group
  236. (if @var{a} @var{b} @var{c})
  237. @equiv{}
  238. (cond (@var{a} @var{b}) (t @var{c}))
  239. @end group
  240. @end example
  241. @menu
  242. * Pattern matching case statement::
  243. @end menu
  244. @node Pattern matching case statement
  245. @subsection Pattern matching case statement
  246. @cindex pcase
  247. @cindex pattern matching
  248. The @code{cond} form lets you choose between alternatives using
  249. predicate conditions that compare values of expressions against
  250. specific values known and written in advance. However, sometimes it
  251. is useful to select alternatives based on more general conditions that
  252. distinguish between broad classes of values. The @code{pcase} macro
  253. allows you to choose between alternatives based on matching the value
  254. of an expression against a series of patterns. A pattern can be a
  255. literal value (for comparisons to literal values you'd use
  256. @code{cond}), or it can be a more general description of the expected
  257. structure of the expression's value.
  258. @defmac pcase expression &rest clauses
  259. Evaluate @var{expression} and choose among an arbitrary number of
  260. alternatives based on the value of @var{expression}. The possible
  261. alternatives are specified by @var{clauses}, each of which must be a
  262. list of the form @code{(@var{pattern} @var{body-forms}@dots{})}.
  263. @code{pcase} tries to match the value of @var{expression} to the
  264. @var{pattern} of each clause, in textual order. If the value matches,
  265. the clause succeeds; @code{pcase} then evaluates its @var{body-forms},
  266. and returns the value of the last of @var{body-forms}. Any remaining
  267. @var{clauses} are ignored.
  268. The @var{pattern} part of a clause can be of one of two types:
  269. @dfn{QPattern}, a pattern quoted with a backquote; or a
  270. @dfn{UPattern}, which is not quoted. UPatterns are simpler, so we
  271. describe them first.
  272. Note: In the description of the patterns below, we use ``the value
  273. being matched'' to refer to the value of the @var{expression} that is
  274. the first argument of @code{pcase}.
  275. A UPattern can have the following forms:
  276. @table @code
  277. @item '@var{val}
  278. Matches if the value being matched is @code{equal} to @var{val}.
  279. @item @var{atom}
  280. Matches any @var{atom}, which can be a keyword, a number, or a string.
  281. (These are self-quoting, so this kind of UPattern is actually a
  282. shorthand for @code{'@var{atom}}.) Note that a string or a float
  283. matches any string or float with the same contents/value.
  284. @item _
  285. Matches any value. This is known as @dfn{don't care} or @dfn{wildcard}.
  286. @item @var{symbol}
  287. Matches any value, and additionally let-binds @var{symbol} to the
  288. value it matched, so that you can later refer to it, either in the
  289. @var{body-forms} or also later in the pattern.
  290. @item (pred @var{predfun})
  291. Matches if the predicate function @var{predfun} returns non-@code{nil}
  292. when called with the value being matched as its argument.
  293. @var{predfun} can be one of the possible forms described below.
  294. @item (guard @var{boolean-expression})
  295. Matches if @var{boolean-expression} evaluates to non-@code{nil}. This
  296. allows you to include in a UPattern boolean conditions that refer to
  297. symbols bound to values (including the value being matched) by
  298. previous UPatterns. Typically used inside an @code{and} UPattern, see
  299. below. For example, @w{@code{(and x (guard (< x 10)))}} is a pattern
  300. which matches any number smaller than 10 and let-binds the variable
  301. @code{x} to that number.
  302. @item (let @var{upattern} @var{expression})
  303. Matches if the specified @var{expression} matches the specified
  304. @var{upattern}. This allows matching a pattern against the value of
  305. an @emph{arbitrary} expression, not just the expression that is the
  306. first argument to @code{pcase}. (It is called @code{let} because
  307. @var{upattern} can bind symbols to values using the @var{symbol}
  308. UPattern. For example:
  309. @w{@code{((or `(key . ,val) (let val 5)) val)}}.)
  310. @item (app @var{function} @var{upattern})
  311. Matches if @var{function} applied to the value being matched returns a
  312. value that matches @var{upattern}. This is like the @code{pred}
  313. UPattern, except that it tests the result against @var{UPattern},
  314. rather than against a boolean truth value. The @var{function} call can
  315. use one of the forms described below.
  316. @item (or @var{upattern1} @var{upattern2}@dots{})
  317. Matches if one the argument UPatterns matches. As soon as the first
  318. matching UPattern is found, the rest are not tested. For this reason,
  319. if any of the UPatterns let-bind symbols to the matched value, they
  320. should all bind the same symbols.
  321. @item (and @var{upattern1} @var{upattern2}@dots{})
  322. Matches if all the argument UPatterns match.
  323. @end table
  324. The function calls used in the @code{pred} and @code{app} UPatterns
  325. can have one of the following forms:
  326. @table @asis
  327. @item function symbol, like @code{integerp}
  328. In this case, the named function is applied to the value being
  329. matched.
  330. @item lambda-function @code{(lambda (@var{arg}) @var{body})}
  331. In this case, the lambda-function is called with one argument, the
  332. value being matched.
  333. @item @code{(@var{func} @var{args}@dots{})}
  334. This is a function call with @var{n} specified arguments; the function
  335. is called with these @var{n} arguments and an additional @var{n}+1-th
  336. argument that is the value being matched.
  337. @end table
  338. Here's an illustrative example of using UPatterns:
  339. @c FIXME: This example should use every one of the UPatterns described
  340. @c above at least once.
  341. @example
  342. (pcase (get-return-code x)
  343. ('success (message "Done!"))
  344. ('would-block (message "Sorry, can't do it now"))
  345. ('read-only (message "The shmliblick is read-only"))
  346. ('access-denied (message "You do not have the needed rights"))
  347. (code (message "Unknown return code %S" code)))
  348. @end example
  349. In addition, you can use backquoted patterns that are more powerful.
  350. They allow matching the value of the @var{expression} that is the
  351. first argument of @code{pcase} against specifications of its
  352. @emph{structure}. For example, you can specify that the value must be
  353. a list of 2 elements whose first element is a specific string and the
  354. second element is any value with a backquoted pattern like
  355. @code{`("first" ,second-elem)}.
  356. Backquoted patterns have the form @code{`@var{qpattern}} where
  357. @var{qpattern} can have the following forms:
  358. @table @code
  359. @item (@var{qpattern1} . @var{qpattern2})
  360. Matches if the value being matched is a cons cell whose @code{car}
  361. matches @var{qpattern1} and whose @code{cdr} matches @var{qpattern2}.
  362. This readily generalizes to backquoted lists as in
  363. @w{@code{(@var{qpattern1} @var{qpattern2} @dots{})}}.
  364. @item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
  365. Matches if the value being matched is a vector of length @var{m} whose
  366. @code{0}..@code{(@var{m}-1)}th elements match @var{qpattern1},
  367. @var{qpattern2} @dots{} @var{qpatternm}, respectively.
  368. @item @var{atom}
  369. Matches if corresponding element of the value being matched is
  370. @code{equal} to the specified @var{atom}.
  371. @item ,@var{upattern}
  372. Matches if the corresponding element of the value being matched
  373. matches the specified @var{upattern}.
  374. @end table
  375. Note that uses of QPatterns can be expressed using only UPatterns, as
  376. QPatterns are implemented on top of UPatterns using
  377. @code{pcase-defmacro}, described below. However, using QPatterns will
  378. in many cases lead to a more readable code.
  379. @c FIXME: There should be an example here showing how a 'pcase' that
  380. @c uses QPatterns can be rewritten using UPatterns.
  381. @end defmac
  382. Here is an example of using @code{pcase} to implement a simple
  383. interpreter for a little expression language (note that this example
  384. requires lexical binding, @pxref{Lexical Binding}):
  385. @example
  386. (defun evaluate (exp env)
  387. (pcase exp
  388. (`(add ,x ,y) (+ (evaluate x env) (evaluate y env)))
  389. (`(call ,fun ,arg) (funcall (evaluate fun env) (evaluate arg env)))
  390. (`(fn ,arg ,body) (lambda (val)
  391. (evaluate body (cons (cons arg val) env))))
  392. ((pred numberp) exp)
  393. ((pred symbolp) (cdr (assq exp env)))
  394. (_ (error "Unknown expression %S" exp))))
  395. @end example
  396. Here @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a
  397. three-element list starting with the literal symbol @code{add}, then
  398. extracts the second and third elements and binds them to the variables
  399. @code{x} and @code{y}. Then it evaluates @code{x} and @code{y} and
  400. adds the results. The @code{call} and @code{fn} patterns similarly
  401. implement two flavors of function calls. @code{(pred numberp)} is a
  402. pattern that simply checks that @code{exp} is a number and if so,
  403. evaluates it. @code{(pred symbolp)} matches symbols, and returns
  404. their association. Finally, @code{_} is the catch-all pattern that
  405. matches anything, so it's suitable for reporting syntax errors.
  406. Here are some sample programs in this small language, including their
  407. evaluation results:
  408. @example
  409. (evaluate '(add 1 2) nil) ;=> 3
  410. (evaluate '(add x y) '((x . 1) (y . 2))) ;=> 3
  411. (evaluate '(call (fn x (add 1 x)) 2) nil) ;=> 3
  412. (evaluate '(sub 1 2) nil) ;=> error
  413. @end example
  414. Additional UPatterns can be defined using the @code{pcase-defmacro}
  415. macro.
  416. @defmac pcase-defmacro name args &rest body
  417. Define a new kind of UPattern for @code{pcase}. The new UPattern will
  418. be invoked as @code{(@var{name} @var{actual-args})}. The @var{body}
  419. should describe how to rewrite the UPattern @var{name} into some other
  420. UPattern. The rewriting will be the result of evaluating @var{body}
  421. in an environment where @var{args} are bound to @var{actual-args}.
  422. @end defmac
  423. @node Combining Conditions
  424. @section Constructs for Combining Conditions
  425. @cindex combining conditions
  426. This section describes three constructs that are often used together
  427. with @code{if} and @code{cond} to express complicated conditions. The
  428. constructs @code{and} and @code{or} can also be used individually as
  429. kinds of multiple conditional constructs.
  430. @defun not condition
  431. This function tests for the falsehood of @var{condition}. It returns
  432. @code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
  433. The function @code{not} is identical to @code{null}, and we recommend
  434. using the name @code{null} if you are testing for an empty list.
  435. @end defun
  436. @defspec and conditions@dots{}
  437. The @code{and} special form tests whether all the @var{conditions} are
  438. true. It works by evaluating the @var{conditions} one by one in the
  439. order written.
  440. If any of the @var{conditions} evaluates to @code{nil}, then the result
  441. of the @code{and} must be @code{nil} regardless of the remaining
  442. @var{conditions}; so @code{and} returns @code{nil} right away, ignoring
  443. the remaining @var{conditions}.
  444. If all the @var{conditions} turn out non-@code{nil}, then the value of
  445. the last of them becomes the value of the @code{and} form. Just
  446. @code{(and)}, with no @var{conditions}, returns @code{t}, appropriate
  447. because all the @var{conditions} turned out non-@code{nil}. (Think
  448. about it; which one did not?)
  449. Here is an example. The first condition returns the integer 1, which is
  450. not @code{nil}. Similarly, the second condition returns the integer 2,
  451. which is not @code{nil}. The third condition is @code{nil}, so the
  452. remaining condition is never evaluated.
  453. @example
  454. @group
  455. (and (print 1) (print 2) nil (print 3))
  456. @print{} 1
  457. @print{} 2
  458. @result{} nil
  459. @end group
  460. @end example
  461. Here is a more realistic example of using @code{and}:
  462. @example
  463. @group
  464. (if (and (consp foo) (eq (car foo) 'x))
  465. (message "foo is a list starting with x"))
  466. @end group
  467. @end example
  468. @noindent
  469. Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
  470. @code{nil}, thus avoiding an error.
  471. @code{and} expressions can also be written using either @code{if} or
  472. @code{cond}. Here's how:
  473. @example
  474. @group
  475. (and @var{arg1} @var{arg2} @var{arg3})
  476. @equiv{}
  477. (if @var{arg1} (if @var{arg2} @var{arg3}))
  478. @equiv{}
  479. (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
  480. @end group
  481. @end example
  482. @end defspec
  483. @defspec or conditions@dots{}
  484. The @code{or} special form tests whether at least one of the
  485. @var{conditions} is true. It works by evaluating all the
  486. @var{conditions} one by one in the order written.
  487. If any of the @var{conditions} evaluates to a non-@code{nil} value, then
  488. the result of the @code{or} must be non-@code{nil}; so @code{or} returns
  489. right away, ignoring the remaining @var{conditions}. The value it
  490. returns is the non-@code{nil} value of the condition just evaluated.
  491. If all the @var{conditions} turn out @code{nil}, then the @code{or}
  492. expression returns @code{nil}. Just @code{(or)}, with no
  493. @var{conditions}, returns @code{nil}, appropriate because all the
  494. @var{conditions} turned out @code{nil}. (Think about it; which one
  495. did not?)
  496. For example, this expression tests whether @code{x} is either
  497. @code{nil} or the integer zero:
  498. @example
  499. (or (eq x nil) (eq x 0))
  500. @end example
  501. Like the @code{and} construct, @code{or} can be written in terms of
  502. @code{cond}. For example:
  503. @example
  504. @group
  505. (or @var{arg1} @var{arg2} @var{arg3})
  506. @equiv{}
  507. (cond (@var{arg1})
  508. (@var{arg2})
  509. (@var{arg3}))
  510. @end group
  511. @end example
  512. You could almost write @code{or} in terms of @code{if}, but not quite:
  513. @example
  514. @group
  515. (if @var{arg1} @var{arg1}
  516. (if @var{arg2} @var{arg2}
  517. @var{arg3}))
  518. @end group
  519. @end example
  520. @noindent
  521. This is not completely equivalent because it can evaluate @var{arg1} or
  522. @var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
  523. @var{arg3})} never evaluates any argument more than once.
  524. @end defspec
  525. @node Iteration
  526. @section Iteration
  527. @cindex iteration
  528. @cindex recursion
  529. Iteration means executing part of a program repetitively. For
  530. example, you might want to repeat some computation once for each element
  531. of a list, or once for each integer from 0 to @var{n}. You can do this
  532. in Emacs Lisp with the special form @code{while}:
  533. @defspec while condition forms@dots{}
  534. @code{while} first evaluates @var{condition}. If the result is
  535. non-@code{nil}, it evaluates @var{forms} in textual order. Then it
  536. reevaluates @var{condition}, and if the result is non-@code{nil}, it
  537. evaluates @var{forms} again. This process repeats until @var{condition}
  538. evaluates to @code{nil}.
  539. There is no limit on the number of iterations that may occur. The loop
  540. will continue until either @var{condition} evaluates to @code{nil} or
  541. until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
  542. The value of a @code{while} form is always @code{nil}.
  543. @example
  544. @group
  545. (setq num 0)
  546. @result{} 0
  547. @end group
  548. @group
  549. (while (< num 4)
  550. (princ (format "Iteration %d." num))
  551. (setq num (1+ num)))
  552. @print{} Iteration 0.
  553. @print{} Iteration 1.
  554. @print{} Iteration 2.
  555. @print{} Iteration 3.
  556. @result{} nil
  557. @end group
  558. @end example
  559. To write a repeat-until loop, which will execute something on each
  560. iteration and then do the end-test, put the body followed by the
  561. end-test in a @code{progn} as the first argument of @code{while}, as
  562. shown here:
  563. @example
  564. @group
  565. (while (progn
  566. (forward-line 1)
  567. (not (looking-at "^$"))))
  568. @end group
  569. @end example
  570. @noindent
  571. This moves forward one line and continues moving by lines until it
  572. reaches an empty line. It is peculiar in that the @code{while} has no
  573. body, just the end test (which also does the real work of moving point).
  574. @end defspec
  575. The @code{dolist} and @code{dotimes} macros provide convenient ways to
  576. write two common kinds of loops.
  577. @defmac dolist (var list [result]) body@dots{}
  578. This construct executes @var{body} once for each element of
  579. @var{list}, binding the variable @var{var} locally to hold the current
  580. element. Then it returns the value of evaluating @var{result}, or
  581. @code{nil} if @var{result} is omitted. For example, here is how you
  582. could use @code{dolist} to define the @code{reverse} function:
  583. @example
  584. (defun reverse (list)
  585. (let (value)
  586. (dolist (elt list value)
  587. (setq value (cons elt value)))))
  588. @end example
  589. @end defmac
  590. @defmac dotimes (var count [result]) body@dots{}
  591. This construct executes @var{body} once for each integer from 0
  592. (inclusive) to @var{count} (exclusive), binding the variable @var{var}
  593. to the integer for the current iteration. Then it returns the value
  594. of evaluating @var{result}, or @code{nil} if @var{result} is omitted.
  595. Here is an example of using @code{dotimes} to do something 100 times:
  596. @example
  597. (dotimes (i 100)
  598. (insert "I will not obey absurd orders\n"))
  599. @end example
  600. @end defmac
  601. @node Generators
  602. @section Generators
  603. @cindex generators
  604. A @dfn{generator} is a function that produces a potentially-infinite
  605. stream of values. Each time the function produces a value, it
  606. suspends itself and waits for a caller to request the next value.
  607. @defmac iter-defun name args [doc] [declare] [interactive] body@dots{}
  608. @code{iter-defun} defines a generator function. A generator function
  609. has the same signature as a normal function, but works differently.
  610. Instead of executing @var{body} when called, a generator function
  611. returns an iterator object. That iterator runs @var{body} to generate
  612. values, emitting a value and pausing where @code{iter-yield} or
  613. @code{iter-yield-from} appears. When @var{body} returns normally,
  614. @code{iter-next} signals @code{iter-end-of-sequence} with @var{body}'s
  615. result as its condition data.
  616. Any kind of Lisp code is valid inside @var{body}, but
  617. @code{iter-yield} and @code{iter-yield-from} cannot appear inside
  618. @code{unwind-protect} forms.
  619. @end defmac
  620. @defmac iter-lambda args [doc] [interactive] body@dots{}
  621. @code{iter-lambda} produces an unnamed generator function that works
  622. just like a generator function produced with @code{iter-defun}.
  623. @end defmac
  624. @defmac iter-yield value
  625. When it appears inside a generator function, @code{iter-yield}
  626. indicates that the current iterator should pause and return
  627. @var{value} from @code{iter-next}. @code{iter-yield} evaluates to the
  628. @code{value} parameter of next call to @code{iter-next}.
  629. @end defmac
  630. @defmac iter-yield-from iterator
  631. @code{iter-yield-from} yields all the values that @var{iterator}
  632. produces and evaluates to the value that @var{iterator}'s generator
  633. function returns normally. While it has control, @var{iterator}
  634. receives values sent to the iterator using @code{iter-next}.
  635. @end defmac
  636. To use a generator function, first call it normally, producing a
  637. @dfn{iterator} object. An iterator is a specific instance of a
  638. generator. Then use @code{iter-next} to retrieve values from this
  639. iterator. When there are no more values to pull from an iterator,
  640. @code{iter-next} raises an @code{iter-end-of-sequence} condition with
  641. the iterator's final value.
  642. It's important to note that generator function bodies only execute
  643. inside calls to @code{iter-next}. A call to a function defined with
  644. @code{iter-defun} produces an iterator; you must drive this
  645. iterator with @code{iter-next} for anything interesting to happen.
  646. Each call to a generator function produces a @emph{different}
  647. iterator, each with its own state.
  648. @defun iter-next iterator value
  649. Retrieve the next value from @var{iterator}. If there are no more
  650. values to be generated (because @var{iterator}'s generator function
  651. returned), @code{iter-next} signals the @code{iter-end-of-sequence}
  652. condition; the data value associated with this condition is the value
  653. with which @var{iterator}'s generator function returned.
  654. @var{value} is sent into the iterator and becomes the value to which
  655. @code{iter-yield} evaluates. @var{value} is ignored for the first
  656. @code{iter-next} call to a given iterator, since at the start of
  657. @var{iterator}'s generator function, the generator function is not
  658. evaluating any @code{iter-yield} form.
  659. @end defun
  660. @defun iter-close iterator
  661. If @var{iterator} is suspended inside an @code{unwind-protect}'s
  662. @code{bodyform} and becomes unreachable, Emacs will eventually run
  663. unwind handlers after a garbage collection pass. (Note that
  664. @code{iter-yield} is illegal inside an @code{unwind-protect}'s
  665. @code{unwindforms}.) To ensure that these handlers are run before
  666. then, use @code{iter-close}.
  667. @end defun
  668. Some convenience functions are provided to make working with
  669. iterators easier:
  670. @defmac iter-do (var iterator) body @dots{}
  671. Run @var{body} with @var{var} bound to each value that
  672. @var{iterator} produces.
  673. @end defmac
  674. The Common Lisp loop facility also contains features for working with
  675. iterators. See @xref{Loop Facility,,,cl,Common Lisp Extensions}.
  676. The following piece of code demonstrates some important principles of
  677. working with iterators.
  678. @example
  679. (iter-defun my-iter (x)
  680. (iter-yield (1+ (iter-yield (1+ x))))
  681. ;; Return normally
  682. -1)
  683. (let* ((iter (my-iter 5))
  684. (iter2 (my-iter 0)))
  685. ;; Prints 6
  686. (print (iter-next iter))
  687. ;; Prints 9
  688. (print (iter-next iter 8))
  689. ;; Prints 1; iter and iter2 have distinct states
  690. (print (iter-next iter2 nil))
  691. ;; We expect the iter sequence to end now
  692. (condition-case x
  693. (iter-next iter)
  694. (iter-end-of-sequence
  695. ;; Prints -1, which my-iter returned normally
  696. (print (cdr x)))))
  697. @end example
  698. @node Nonlocal Exits
  699. @section Nonlocal Exits
  700. @cindex nonlocal exits
  701. A @dfn{nonlocal exit} is a transfer of control from one point in a
  702. program to another remote point. Nonlocal exits can occur in Emacs Lisp
  703. as a result of errors; you can also use them under explicit control.
  704. Nonlocal exits unbind all variable bindings made by the constructs being
  705. exited.
  706. @menu
  707. * Catch and Throw:: Nonlocal exits for the program's own purposes.
  708. * Examples of Catch:: Showing how such nonlocal exits can be written.
  709. * Errors:: How errors are signaled and handled.
  710. * Cleanups:: Arranging to run a cleanup form if an error happens.
  711. @end menu
  712. @node Catch and Throw
  713. @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
  714. Most control constructs affect only the flow of control within the
  715. construct itself. The function @code{throw} is the exception to this
  716. rule of normal program execution: it performs a nonlocal exit on
  717. request. (There are other exceptions, but they are for error handling
  718. only.) @code{throw} is used inside a @code{catch}, and jumps back to
  719. that @code{catch}. For example:
  720. @example
  721. @group
  722. (defun foo-outer ()
  723. (catch 'foo
  724. (foo-inner)))
  725. (defun foo-inner ()
  726. @dots{}
  727. (if x
  728. (throw 'foo t))
  729. @dots{})
  730. @end group
  731. @end example
  732. @noindent
  733. The @code{throw} form, if executed, transfers control straight back to
  734. the corresponding @code{catch}, which returns immediately. The code
  735. following the @code{throw} is not executed. The second argument of
  736. @code{throw} is used as the return value of the @code{catch}.
  737. The function @code{throw} finds the matching @code{catch} based on the
  738. first argument: it searches for a @code{catch} whose first argument is
  739. @code{eq} to the one specified in the @code{throw}. If there is more
  740. than one applicable @code{catch}, the innermost one takes precedence.
  741. Thus, in the above example, the @code{throw} specifies @code{foo}, and
  742. the @code{catch} in @code{foo-outer} specifies the same symbol, so that
  743. @code{catch} is the applicable one (assuming there is no other matching
  744. @code{catch} in between).
  745. Executing @code{throw} exits all Lisp constructs up to the matching
  746. @code{catch}, including function calls. When binding constructs such
  747. as @code{let} or function calls are exited in this way, the bindings
  748. are unbound, just as they are when these constructs exit normally
  749. (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
  750. and position saved by @code{save-excursion} (@pxref{Excursions}), and
  751. the narrowing status saved by @code{save-restriction}. It also runs
  752. any cleanups established with the @code{unwind-protect} special form
  753. when it exits that form (@pxref{Cleanups}).
  754. The @code{throw} need not appear lexically within the @code{catch}
  755. that it jumps to. It can equally well be called from another function
  756. called within the @code{catch}. As long as the @code{throw} takes place
  757. chronologically after entry to the @code{catch}, and chronologically
  758. before exit from it, it has access to that @code{catch}. This is why
  759. @code{throw} can be used in commands such as @code{exit-recursive-edit}
  760. that throw back to the editor command loop (@pxref{Recursive Editing}).
  761. @cindex CL note---only @code{throw} in Emacs
  762. @quotation
  763. @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
  764. have several ways of transferring control nonsequentially: @code{return},
  765. @code{return-from}, and @code{go}, for example. Emacs Lisp has only
  766. @code{throw}. The @file{cl-lib} library provides versions of some of
  767. these. @xref{Blocks and Exits,,,cl,Common Lisp Extensions}.
  768. @end quotation
  769. @defspec catch tag body@dots{}
  770. @cindex tag on run time stack
  771. @code{catch} establishes a return point for the @code{throw} function.
  772. The return point is distinguished from other such return points by
  773. @var{tag}, which may be any Lisp object except @code{nil}. The argument
  774. @var{tag} is evaluated normally before the return point is established.
  775. With the return point in effect, @code{catch} evaluates the forms of the
  776. @var{body} in textual order. If the forms execute normally (without
  777. error or nonlocal exit) the value of the last body form is returned from
  778. the @code{catch}.
  779. If a @code{throw} is executed during the execution of @var{body},
  780. specifying the same value @var{tag}, the @code{catch} form exits
  781. immediately; the value it returns is whatever was specified as the
  782. second argument of @code{throw}.
  783. @end defspec
  784. @defun throw tag value
  785. The purpose of @code{throw} is to return from a return point previously
  786. established with @code{catch}. The argument @var{tag} is used to choose
  787. among the various existing return points; it must be @code{eq} to the value
  788. specified in the @code{catch}. If multiple return points match @var{tag},
  789. the innermost one is used.
  790. The argument @var{value} is used as the value to return from that
  791. @code{catch}.
  792. @kindex no-catch
  793. If no return point is in effect with tag @var{tag}, then a @code{no-catch}
  794. error is signaled with data @code{(@var{tag} @var{value})}.
  795. @end defun
  796. @node Examples of Catch
  797. @subsection Examples of @code{catch} and @code{throw}
  798. One way to use @code{catch} and @code{throw} is to exit from a doubly
  799. nested loop. (In most languages, this would be done with a @code{goto}.)
  800. Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
  801. varying from 0 to 9:
  802. @example
  803. @group
  804. (defun search-foo ()
  805. (catch 'loop
  806. (let ((i 0))
  807. (while (< i 10)
  808. (let ((j 0))
  809. (while (< j 10)
  810. (if (foo i j)
  811. (throw 'loop (list i j)))
  812. (setq j (1+ j))))
  813. (setq i (1+ i))))))
  814. @end group
  815. @end example
  816. @noindent
  817. If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
  818. list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
  819. @code{catch} returns normally, and the value is @code{nil}, since that
  820. is the result of the @code{while}.
  821. Here are two tricky examples, slightly different, showing two
  822. return points at once. First, two return points with the same tag,
  823. @code{hack}:
  824. @example
  825. @group
  826. (defun catch2 (tag)
  827. (catch tag
  828. (throw 'hack 'yes)))
  829. @result{} catch2
  830. @end group
  831. @group
  832. (catch 'hack
  833. (print (catch2 'hack))
  834. 'no)
  835. @print{} yes
  836. @result{} no
  837. @end group
  838. @end example
  839. @noindent
  840. Since both return points have tags that match the @code{throw}, it goes to
  841. the inner one, the one established in @code{catch2}. Therefore,
  842. @code{catch2} returns normally with value @code{yes}, and this value is
  843. printed. Finally the second body form in the outer @code{catch}, which is
  844. @code{'no}, is evaluated and returned from the outer @code{catch}.
  845. Now let's change the argument given to @code{catch2}:
  846. @example
  847. @group
  848. (catch 'hack
  849. (print (catch2 'quux))
  850. 'no)
  851. @result{} yes
  852. @end group
  853. @end example
  854. @noindent
  855. We still have two return points, but this time only the outer one has
  856. the tag @code{hack}; the inner one has the tag @code{quux} instead.
  857. Therefore, @code{throw} makes the outer @code{catch} return the value
  858. @code{yes}. The function @code{print} is never called, and the
  859. body-form @code{'no} is never evaluated.
  860. @node Errors
  861. @subsection Errors
  862. @cindex errors
  863. When Emacs Lisp attempts to evaluate a form that, for some reason,
  864. cannot be evaluated, it @dfn{signals} an @dfn{error}.
  865. When an error is signaled, Emacs's default reaction is to print an
  866. error message and terminate execution of the current command. This is
  867. the right thing to do in most cases, such as if you type @kbd{C-f} at
  868. the end of the buffer.
  869. In complicated programs, simple termination may not be what you want.
  870. For example, the program may have made temporary changes in data
  871. structures, or created temporary buffers that should be deleted before
  872. the program is finished. In such cases, you would use
  873. @code{unwind-protect} to establish @dfn{cleanup expressions} to be
  874. evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
  875. wish the program to continue execution despite an error in a subroutine.
  876. In these cases, you would use @code{condition-case} to establish
  877. @dfn{error handlers} to recover control in case of error.
  878. Resist the temptation to use error handling to transfer control from
  879. one part of the program to another; use @code{catch} and @code{throw}
  880. instead. @xref{Catch and Throw}.
  881. @menu
  882. * Signaling Errors:: How to report an error.
  883. * Processing of Errors:: What Emacs does when you report an error.
  884. * Handling Errors:: How you can trap errors and continue execution.
  885. * Error Symbols:: How errors are classified for trapping them.
  886. @end menu
  887. @node Signaling Errors
  888. @subsubsection How to Signal an Error
  889. @cindex signaling errors
  890. @dfn{Signaling} an error means beginning error processing. Error
  891. processing normally aborts all or part of the running program and
  892. returns to a point that is set up to handle the error
  893. (@pxref{Processing of Errors}). Here we describe how to signal an
  894. error.
  895. Most errors are signaled automatically within Lisp primitives
  896. which you call for other purposes, such as if you try to take the
  897. @sc{car} of an integer or move forward a character at the end of the
  898. buffer. You can also signal errors explicitly with the functions
  899. @code{error} and @code{signal}.
  900. Quitting, which happens when the user types @kbd{C-g}, is not
  901. considered an error, but it is handled almost like an error.
  902. @xref{Quitting}.
  903. Every error specifies an error message, one way or another. The
  904. message should state what is wrong (``File does not exist''), not how
  905. things ought to be (``File must exist''). The convention in Emacs
  906. Lisp is that error messages should start with a capital letter, but
  907. should not end with any sort of punctuation.
  908. @defun error format-string &rest args
  909. This function signals an error with an error message constructed by
  910. applying @code{format-message} (@pxref{Formatting Strings}) to
  911. @var{format-string} and @var{args}.
  912. These examples show typical uses of @code{error}:
  913. @example
  914. @group
  915. (error "That is an error -- try something else")
  916. @error{} That is an error -- try something else
  917. @end group
  918. @group
  919. (error "Invalid name `%s'" "A%%B")
  920. @error{} Invalid name ‘A%%B’
  921. @end group
  922. @end example
  923. @code{error} works by calling @code{signal} with two arguments: the
  924. error symbol @code{error}, and a list containing the string returned by
  925. @code{format-message}.
  926. In a format string containing single quotes, curved quotes @t{‘like
  927. this’} and grave quotes @t{`like this'} work better than straight
  928. quotes @t{'like this'}, as @code{error} typically formats every
  929. straight quote as a curved closing quote.
  930. @strong{Warning:} If you want to use your own string as an error message
  931. verbatim, don't just write @code{(error @var{string})}. If @var{string}
  932. @var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
  933. reformatted, with undesirable results. Instead, use @code{(error "%s"
  934. @var{string})}.
  935. @end defun
  936. @defun signal error-symbol data
  937. @anchor{Definition of signal}
  938. This function signals an error named by @var{error-symbol}. The
  939. argument @var{data} is a list of additional Lisp objects relevant to
  940. the circumstances of the error.
  941. The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
  942. defined with @code{define-error}. This is how Emacs Lisp classifies different
  943. sorts of errors. @xref{Error Symbols}, for a description of error symbols,
  944. error conditions and condition names.
  945. If the error is not handled, the two arguments are used in printing
  946. the error message. Normally, this error message is provided by the
  947. @code{error-message} property of @var{error-symbol}. If @var{data} is
  948. non-@code{nil}, this is followed by a colon and a comma separated list
  949. of the unevaluated elements of @var{data}. For @code{error}, the
  950. error message is the @sc{car} of @var{data} (that must be a string).
  951. Subcategories of @code{file-error} are handled specially.
  952. The number and significance of the objects in @var{data} depends on
  953. @var{error-symbol}. For example, with a @code{wrong-type-argument} error,
  954. there should be two objects in the list: a predicate that describes the type
  955. that was expected, and the object that failed to fit that type.
  956. Both @var{error-symbol} and @var{data} are available to any error
  957. handlers that handle the error: @code{condition-case} binds a local
  958. variable to a list of the form @code{(@var{error-symbol} .@:
  959. @var{data})} (@pxref{Handling Errors}).
  960. The function @code{signal} never returns.
  961. @c (though in older Emacs versions it sometimes could).
  962. @example
  963. @group
  964. (signal 'wrong-number-of-arguments '(x y))
  965. @error{} Wrong number of arguments: x, y
  966. @end group
  967. @group
  968. (signal 'no-such-error '("My unknown error condition"))
  969. @error{} peculiar error: "My unknown error condition"
  970. @end group
  971. @end example
  972. @end defun
  973. @cindex user errors, signaling
  974. @defun user-error format-string &rest args
  975. This function behaves exactly like @code{error}, except that it uses
  976. the error symbol @code{user-error} rather than @code{error}. As the
  977. name suggests, this is intended to report errors on the part of the
  978. user, rather than errors in the code itself. For example,
  979. if you try to use the command @code{Info-history-back} (@kbd{l}) to
  980. move back beyond the start of your Info browsing history, Emacs
  981. signals a @code{user-error}. Such errors do not cause entry to the
  982. debugger, even when @code{debug-on-error} is non-@code{nil}.
  983. @xref{Error Debugging}.
  984. @end defun
  985. @cindex CL note---no continuable errors
  986. @quotation
  987. @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
  988. concept of continuable errors.
  989. @end quotation
  990. @node Processing of Errors
  991. @subsubsection How Emacs Processes Errors
  992. @cindex processing of errors
  993. When an error is signaled, @code{signal} searches for an active
  994. @dfn{handler} for the error. A handler is a sequence of Lisp
  995. expressions designated to be executed if an error happens in part of the
  996. Lisp program. If the error has an applicable handler, the handler is
  997. executed, and control resumes following the handler. The handler
  998. executes in the environment of the @code{condition-case} that
  999. established it; all functions called within that @code{condition-case}
  1000. have already been exited, and the handler cannot return to them.
  1001. If there is no applicable handler for the error, it terminates the
  1002. current command and returns control to the editor command loop. (The
  1003. command loop has an implicit handler for all kinds of errors.) The
  1004. command loop's handler uses the error symbol and associated data to
  1005. print an error message. You can use the variable
  1006. @code{command-error-function} to control how this is done:
  1007. @defvar command-error-function
  1008. This variable, if non-@code{nil}, specifies a function to use to
  1009. handle errors that return control to the Emacs command loop. The
  1010. function should take three arguments: @var{data}, a list of the same
  1011. form that @code{condition-case} would bind to its variable;
  1012. @var{context}, a string describing the situation in which the error
  1013. occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
  1014. function which called the primitive that signaled the error.
  1015. @end defvar
  1016. @cindex @code{debug-on-error} use
  1017. An error that has no explicit handler may call the Lisp debugger. The
  1018. debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
  1019. Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
  1020. in the environment of the error, so that you can examine values of
  1021. variables precisely as they were at the time of the error.
  1022. @node Handling Errors
  1023. @subsubsection Writing Code to Handle Errors
  1024. @cindex error handler
  1025. @cindex handling errors
  1026. The usual effect of signaling an error is to terminate the command
  1027. that is running and return immediately to the Emacs editor command loop.
  1028. You can arrange to trap errors occurring in a part of your program by
  1029. establishing an error handler, with the special form
  1030. @code{condition-case}. A simple example looks like this:
  1031. @example
  1032. @group
  1033. (condition-case nil
  1034. (delete-file filename)
  1035. (error nil))
  1036. @end group
  1037. @end example
  1038. @noindent
  1039. This deletes the file named @var{filename}, catching any error and
  1040. returning @code{nil} if an error occurs. (You can use the macro
  1041. @code{ignore-errors} for a simple case like this; see below.)
  1042. The @code{condition-case} construct is often used to trap errors that
  1043. are predictable, such as failure to open a file in a call to
  1044. @code{insert-file-contents}. It is also used to trap errors that are
  1045. totally unpredictable, such as when the program evaluates an expression
  1046. read from the user.
  1047. The second argument of @code{condition-case} is called the
  1048. @dfn{protected form}. (In the example above, the protected form is a
  1049. call to @code{delete-file}.) The error handlers go into effect when
  1050. this form begins execution and are deactivated when this form returns.
  1051. They remain in effect for all the intervening time. In particular, they
  1052. are in effect during the execution of functions called by this form, in
  1053. their subroutines, and so on. This is a good thing, since, strictly
  1054. speaking, errors can be signaled only by Lisp primitives (including
  1055. @code{signal} and @code{error}) called by the protected form, not by the
  1056. protected form itself.
  1057. The arguments after the protected form are handlers. Each handler
  1058. lists one or more @dfn{condition names} (which are symbols) to specify
  1059. which errors it will handle. The error symbol specified when an error
  1060. is signaled also defines a list of condition names. A handler applies
  1061. to an error if they have any condition names in common. In the example
  1062. above, there is one handler, and it specifies one condition name,
  1063. @code{error}, which covers all errors.
  1064. The search for an applicable handler checks all the established handlers
  1065. starting with the most recently established one. Thus, if two nested
  1066. @code{condition-case} forms offer to handle the same error, the inner of
  1067. the two gets to handle it.
  1068. If an error is handled by some @code{condition-case} form, this
  1069. ordinarily prevents the debugger from being run, even if
  1070. @code{debug-on-error} says this error should invoke the debugger.
  1071. If you want to be able to debug errors that are caught by a
  1072. @code{condition-case}, set the variable @code{debug-on-signal} to a
  1073. non-@code{nil} value. You can also specify that a particular handler
  1074. should let the debugger run first, by writing @code{debug} among the
  1075. conditions, like this:
  1076. @example
  1077. @group
  1078. (condition-case nil
  1079. (delete-file filename)
  1080. ((debug error) nil))
  1081. @end group
  1082. @end example
  1083. @noindent
  1084. The effect of @code{debug} here is only to prevent
  1085. @code{condition-case} from suppressing the call to the debugger. Any
  1086. given error will invoke the debugger only if @code{debug-on-error} and
  1087. the other usual filtering mechanisms say it should. @xref{Error Debugging}.
  1088. @defmac condition-case-unless-debug var protected-form handlers@dots{}
  1089. The macro @code{condition-case-unless-debug} provides another way to
  1090. handle debugging of such forms. It behaves exactly like
  1091. @code{condition-case}, unless the variable @code{debug-on-error} is
  1092. non-@code{nil}, in which case it does not handle any errors at all.
  1093. @end defmac
  1094. Once Emacs decides that a certain handler handles the error, it
  1095. returns control to that handler. To do so, Emacs unbinds all variable
  1096. bindings made by binding constructs that are being exited, and
  1097. executes the cleanups of all @code{unwind-protect} forms that are
  1098. being exited. Once control arrives at the handler, the body of the
  1099. handler executes normally.
  1100. After execution of the handler body, execution returns from the
  1101. @code{condition-case} form. Because the protected form is exited
  1102. completely before execution of the handler, the handler cannot resume
  1103. execution at the point of the error, nor can it examine variable
  1104. bindings that were made within the protected form. All it can do is
  1105. clean up and proceed.
  1106. Error signaling and handling have some resemblance to @code{throw} and
  1107. @code{catch} (@pxref{Catch and Throw}), but they are entirely separate
  1108. facilities. An error cannot be caught by a @code{catch}, and a
  1109. @code{throw} cannot be handled by an error handler (though using
  1110. @code{throw} when there is no suitable @code{catch} signals an error
  1111. that can be handled).
  1112. @defspec condition-case var protected-form handlers@dots{}
  1113. This special form establishes the error handlers @var{handlers} around
  1114. the execution of @var{protected-form}. If @var{protected-form} executes
  1115. without error, the value it returns becomes the value of the
  1116. @code{condition-case} form; in this case, the @code{condition-case} has
  1117. no effect. The @code{condition-case} form makes a difference when an
  1118. error occurs during @var{protected-form}.
  1119. Each of the @var{handlers} is a list of the form @code{(@var{conditions}
  1120. @var{body}@dots{})}. Here @var{conditions} is an error condition name
  1121. to be handled, or a list of condition names (which can include @code{debug}
  1122. to allow the debugger to run before the handler); @var{body} is one or more
  1123. Lisp expressions to be executed when this handler handles an error.
  1124. Here are examples of handlers:
  1125. @example
  1126. @group
  1127. (error nil)
  1128. (arith-error (message "Division by zero"))
  1129. ((arith-error file-error)
  1130. (message
  1131. "Either division by zero or failure to open a file"))
  1132. @end group
  1133. @end example
  1134. Each error that occurs has an @dfn{error symbol} that describes what
  1135. kind of error it is, and which describes also a list of condition names
  1136. (@pxref{Error Symbols}). Emacs
  1137. searches all the active @code{condition-case} forms for a handler that
  1138. specifies one or more of these condition names; the innermost matching
  1139. @code{condition-case} handles the error. Within this
  1140. @code{condition-case}, the first applicable handler handles the error.
  1141. After executing the body of the handler, the @code{condition-case}
  1142. returns normally, using the value of the last form in the handler body
  1143. as the overall value.
  1144. @cindex error description
  1145. The argument @var{var} is a variable. @code{condition-case} does not
  1146. bind this variable when executing the @var{protected-form}, only when it
  1147. handles an error. At that time, it binds @var{var} locally to an
  1148. @dfn{error description}, which is a list giving the particulars of the
  1149. error. The error description has the form @code{(@var{error-symbol}
  1150. . @var{data})}. The handler can refer to this list to decide what to
  1151. do. For example, if the error is for failure opening a file, the file
  1152. name is the second element of @var{data}---the third element of the
  1153. error description.
  1154. If @var{var} is @code{nil}, that means no variable is bound. Then the
  1155. error symbol and associated data are not available to the handler.
  1156. @cindex rethrow a signal
  1157. Sometimes it is necessary to re-throw a signal caught by
  1158. @code{condition-case}, for some outer-level handler to catch. Here's
  1159. how to do that:
  1160. @example
  1161. (signal (car err) (cdr err))
  1162. @end example
  1163. @noindent
  1164. where @code{err} is the error description variable, the first argument
  1165. to @code{condition-case} whose error condition you want to re-throw.
  1166. @xref{Definition of signal}.
  1167. @end defspec
  1168. @defun error-message-string error-descriptor
  1169. This function returns the error message string for a given error
  1170. descriptor. It is useful if you want to handle an error by printing the
  1171. usual error message for that error. @xref{Definition of signal}.
  1172. @end defun
  1173. @cindex @code{arith-error} example
  1174. Here is an example of using @code{condition-case} to handle the error
  1175. that results from dividing by zero. The handler displays the error
  1176. message (but without a beep), then returns a very large number.
  1177. @example
  1178. @group
  1179. (defun safe-divide (dividend divisor)
  1180. (condition-case err
  1181. ;; @r{Protected form.}
  1182. (/ dividend divisor)
  1183. @end group
  1184. @group
  1185. ;; @r{The handler.}
  1186. (arith-error ; @r{Condition.}
  1187. ;; @r{Display the usual message for this error.}
  1188. (message "%s" (error-message-string err))
  1189. 1000000)))
  1190. @result{} safe-divide
  1191. @end group
  1192. @group
  1193. (safe-divide 5 0)
  1194. @print{} Arithmetic error: (arith-error)
  1195. @result{} 1000000
  1196. @end group
  1197. @end example
  1198. @noindent
  1199. The handler specifies condition name @code{arith-error} so that it
  1200. will handle only division-by-zero errors. Other kinds of errors will
  1201. not be handled (by this @code{condition-case}). Thus:
  1202. @example
  1203. @group
  1204. (safe-divide nil 3)
  1205. @error{} Wrong type argument: number-or-marker-p, nil
  1206. @end group
  1207. @end example
  1208. Here is a @code{condition-case} that catches all kinds of errors,
  1209. including those from @code{error}:
  1210. @example
  1211. @group
  1212. (setq baz 34)
  1213. @result{} 34
  1214. @end group
  1215. @group
  1216. (condition-case err
  1217. (if (eq baz 35)
  1218. t
  1219. ;; @r{This is a call to the function @code{error}.}
  1220. (error "Rats! The variable %s was %s, not 35" 'baz baz))
  1221. ;; @r{This is the handler; it is not a form.}
  1222. (error (princ (format "The error was: %s" err))
  1223. 2))
  1224. @print{} The error was: (error "Rats! The variable baz was 34, not 35")
  1225. @result{} 2
  1226. @end group
  1227. @end example
  1228. @defmac ignore-errors body@dots{}
  1229. This construct executes @var{body}, ignoring any errors that occur
  1230. during its execution. If the execution is without error,
  1231. @code{ignore-errors} returns the value of the last form in @var{body};
  1232. otherwise, it returns @code{nil}.
  1233. Here's the example at the beginning of this subsection rewritten using
  1234. @code{ignore-errors}:
  1235. @example
  1236. @group
  1237. (ignore-errors
  1238. (delete-file filename))
  1239. @end group
  1240. @end example
  1241. @end defmac
  1242. @defmac with-demoted-errors format body@dots{}
  1243. This macro is like a milder version of @code{ignore-errors}. Rather
  1244. than suppressing errors altogether, it converts them into messages.
  1245. It uses the string @var{format} to format the message.
  1246. @var{format} should contain a single @samp{%}-sequence; e.g.,
  1247. @code{"Error: %S"}. Use @code{with-demoted-errors} around code
  1248. that is not expected to signal errors, but
  1249. should be robust if one does occur. Note that this macro uses
  1250. @code{condition-case-unless-debug} rather than @code{condition-case}.
  1251. @end defmac
  1252. @node Error Symbols
  1253. @subsubsection Error Symbols and Condition Names
  1254. @cindex error symbol
  1255. @cindex error name
  1256. @cindex condition name
  1257. @cindex user-defined error
  1258. @kindex error-conditions
  1259. @kindex define-error
  1260. When you signal an error, you specify an @dfn{error symbol} to specify
  1261. the kind of error you have in mind. Each error has one and only one
  1262. error symbol to categorize it. This is the finest classification of
  1263. errors defined by the Emacs Lisp language.
  1264. These narrow classifications are grouped into a hierarchy of wider
  1265. classes called @dfn{error conditions}, identified by @dfn{condition
  1266. names}. The narrowest such classes belong to the error symbols
  1267. themselves: each error symbol is also a condition name. There are also
  1268. condition names for more extensive classes, up to the condition name
  1269. @code{error} which takes in all kinds of errors (but not @code{quit}).
  1270. Thus, each error has one or more condition names: @code{error}, the
  1271. error symbol if that is distinct from @code{error}, and perhaps some
  1272. intermediate classifications.
  1273. @defun define-error name message &optional parent
  1274. In order for a symbol to be an error symbol, it must be defined with
  1275. @code{define-error} which takes a parent condition (defaults to @code{error}).
  1276. This parent defines the conditions that this kind of error belongs to.
  1277. The transitive set of parents always includes the error symbol itself, and the
  1278. symbol @code{error}. Because quitting is not considered an error, the set of
  1279. parents of @code{quit} is just @code{(quit)}.
  1280. @end defun
  1281. @cindex peculiar error
  1282. In addition to its parents, the error symbol has a @var{message} which
  1283. is a string to be printed when that error is signaled but not handled. If that
  1284. message is not valid, the error message @samp{peculiar error} is used.
  1285. @xref{Definition of signal}.
  1286. Internally, the set of parents is stored in the @code{error-conditions}
  1287. property of the error symbol and the message is stored in the
  1288. @code{error-message} property of the error symbol.
  1289. Here is how we define a new error symbol, @code{new-error}:
  1290. @example
  1291. @group
  1292. (define-error 'new-error "A new error" 'my-own-errors)
  1293. @end group
  1294. @end example
  1295. @noindent
  1296. This error has several condition names: @code{new-error}, the narrowest
  1297. classification; @code{my-own-errors}, which we imagine is a wider
  1298. classification; and all the conditions of @code{my-own-errors} which should
  1299. include @code{error}, which is the widest of all.
  1300. The error string should start with a capital letter but it should
  1301. not end with a period. This is for consistency with the rest of Emacs.
  1302. Naturally, Emacs will never signal @code{new-error} on its own; only
  1303. an explicit call to @code{signal} (@pxref{Definition of signal}) in
  1304. your code can do this:
  1305. @example
  1306. @group
  1307. (signal 'new-error '(x y))
  1308. @error{} A new error: x, y
  1309. @end group
  1310. @end example
  1311. This error can be handled through any of its condition names.
  1312. This example handles @code{new-error} and any other errors in the class
  1313. @code{my-own-errors}:
  1314. @example
  1315. @group
  1316. (condition-case foo
  1317. (bar nil t)
  1318. (my-own-errors nil))
  1319. @end group
  1320. @end example
  1321. The significant way that errors are classified is by their condition
  1322. names---the names used to match errors with handlers. An error symbol
  1323. serves only as a convenient way to specify the intended error message
  1324. and list of condition names. It would be cumbersome to give
  1325. @code{signal} a list of condition names rather than one error symbol.
  1326. By contrast, using only error symbols without condition names would
  1327. seriously decrease the power of @code{condition-case}. Condition names
  1328. make it possible to categorize errors at various levels of generality
  1329. when you write an error handler. Using error symbols alone would
  1330. eliminate all but the narrowest level of classification.
  1331. @xref{Standard Errors}, for a list of the main error symbols
  1332. and their conditions.
  1333. @node Cleanups
  1334. @subsection Cleaning Up from Nonlocal Exits
  1335. @cindex nonlocal exits, cleaning up
  1336. The @code{unwind-protect} construct is essential whenever you
  1337. temporarily put a data structure in an inconsistent state; it permits
  1338. you to make the data consistent again in the event of an error or
  1339. throw. (Another more specific cleanup construct that is used only for
  1340. changes in buffer contents is the atomic change group; @ref{Atomic
  1341. Changes}.)
  1342. @defspec unwind-protect body-form cleanup-forms@dots{}
  1343. @cindex cleanup forms
  1344. @cindex protected forms
  1345. @cindex error cleanup
  1346. @cindex unwinding
  1347. @code{unwind-protect} executes @var{body-form} with a guarantee that
  1348. the @var{cleanup-forms} will be evaluated if control leaves
  1349. @var{body-form}, no matter how that happens. @var{body-form} may
  1350. complete normally, or execute a @code{throw} out of the
  1351. @code{unwind-protect}, or cause an error; in all cases, the
  1352. @var{cleanup-forms} will be evaluated.
  1353. If @var{body-form} finishes normally, @code{unwind-protect} returns the
  1354. value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
  1355. If @var{body-form} does not finish, @code{unwind-protect} does not
  1356. return any value in the normal sense.
  1357. Only @var{body-form} is protected by the @code{unwind-protect}. If any
  1358. of the @var{cleanup-forms} themselves exits nonlocally (via a
  1359. @code{throw} or an error), @code{unwind-protect} is @emph{not}
  1360. guaranteed to evaluate the rest of them. If the failure of one of the
  1361. @var{cleanup-forms} has the potential to cause trouble, then protect
  1362. it with another @code{unwind-protect} around that form.
  1363. The number of currently active @code{unwind-protect} forms counts,
  1364. together with the number of local variable bindings, against the limit
  1365. @code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
  1366. Variables}).
  1367. @end defspec
  1368. For example, here we make an invisible buffer for temporary use, and
  1369. make sure to kill it before finishing:
  1370. @example
  1371. @group
  1372. (let ((buffer (get-buffer-create " *temp*")))
  1373. (with-current-buffer buffer
  1374. (unwind-protect
  1375. @var{body-form}
  1376. (kill-buffer buffer))))
  1377. @end group
  1378. @end example
  1379. @noindent
  1380. You might think that we could just as well write @code{(kill-buffer
  1381. (current-buffer))} and dispense with the variable @code{buffer}.
  1382. However, the way shown above is safer, if @var{body-form} happens to
  1383. get an error after switching to a different buffer! (Alternatively,
  1384. you could write a @code{save-current-buffer} around @var{body-form},
  1385. to ensure that the temporary buffer becomes current again in time to
  1386. kill it.)
  1387. Emacs includes a standard macro called @code{with-temp-buffer} which
  1388. expands into more or less the code shown above (@pxref{Definition of
  1389. with-temp-buffer,, Current Buffer}). Several of the macros defined in
  1390. this manual use @code{unwind-protect} in this way.
  1391. @findex ftp-login
  1392. Here is an actual example derived from an FTP package. It creates a
  1393. process (@pxref{Processes}) to try to establish a connection to a remote
  1394. machine. As the function @code{ftp-login} is highly susceptible to
  1395. numerous problems that the writer of the function cannot anticipate, it
  1396. is protected with a form that guarantees deletion of the process in the
  1397. event of failure. Otherwise, Emacs might fill up with useless
  1398. subprocesses.
  1399. @example
  1400. @group
  1401. (let ((win nil))
  1402. (unwind-protect
  1403. (progn
  1404. (setq process (ftp-setup-buffer host file))
  1405. (if (setq win (ftp-login process host user password))
  1406. (message "Logged in")
  1407. (error "Ftp login failed")))
  1408. (or win (and process (delete-process process)))))
  1409. @end group
  1410. @end example
  1411. This example has a small bug: if the user types @kbd{C-g} to
  1412. quit, and the quit happens immediately after the function
  1413. @code{ftp-setup-buffer} returns but before the variable @code{process} is
  1414. set, the process will not be killed. There is no easy way to fix this bug,
  1415. but at least it is very unlikely.