1 11/10/79 - Emacs extensions
   2 
   3 (Updates to this document are kept in
   4           >exl>emacs_dir>info>extensions.changes.info)
   5 
   6 **This file is intended to be perused via dprint, print, or via an**
   7 **editor.  It is not intended to be perused with the help command **
   8 
   9 
  10 
  11 
  12 ^L
  13      An editor _^He_^Hx_^Ht_^He_^Hn_^Hs_^Hi_^Ho_^Hn is a user-provided capability, added to the
  14 editor which augments its power and repertoire.  It is different from a
  15 macro, which is simply a collection of editor commands gathered up and
  16 (perhaps) given a name.  Extensions are _^Hp_^Hr_^Ho_^Hg_^Hr_^Ha_^Hm_^Hs; in Multics Emacs,
  17 they are written in the language of the Multics Emacs environment.  One good
  18 definition of an extension is a body of code which augments the editor's
  19 capability, but does not need to know how data in the editor is stored or
  20 manipulated.  In this sense, all of the word, sentence, paragraph,
  21 Lisp-list commands, and the various "modes" (e.g., PL/I mode) are extensions.
  22 
  23      The person who wishes to add to his Multics Emacs environment any
  24 powerful or sophisticated capability must learn to write extensions.  The
  25 keyboard macro facility (^X(, ^X)), is not intended for such usage.  In this
  26 document we explain how to write extensions.
  27 
  28      One of the guiding design principles in the Multics Emacs editor was
  29 that the creations of editor extensions, either by the editor implementors or
  30 end users, should be in a programming language of established elegance and
  31 power.  This primer will give you a starting point for writing Lisp code to
  32 run as editor extensions in the Multics Emacs environment.  If you have some
  33 knowledge of Lisp already, it will be of value.  However, I shall assume that
  34 the reader has no familiarity with Lisp, but perhaps with PL/I or BASIC.
  35 
  36      I will assume that the reader _^Hi_^Hs quite familiar with Multics Emacs as
  37 far as having used it, and acquired some proficiency and familiarity with its
  38 general usage and visible organization.
  39 
  40 
  41 
  42           An Introduction to Lisp for People Who Don't Want
  43           To Have to Know Lisp to Write Emacs extensions.
  44           -----------------------------------------------
  45 
  46      Lisp programs are built of _^Hf_^Hu_^Hn_^Hc_^Ht_^Hi_^Ho_^Hn_^Hs, which are vaguely like procedures
  47 or subroutines in other languages, although more akin to PL/I and ALGOL
  48 functions.  We write a Lisp program by creating a file full of function
  49 _^Hd_^He_^Hf_^Hi_^Hn_^Hi_^Ht_^Hi_^Ho_^Hn_^Hs.  A function definition specifies the name of a function, and
  50 what it does.  Here is a sample function definition:
  51 
  52 (defun addandmult (a b c)                         ;Here is a comment
  53        (* (- a b)
  54           (+ a b c)))
  55 
  56 This says, "Here is a function named addandmult.  It takes three arguments,
  57 which, as parameters, we will call a, b, and c.  Compute the result of
  58 multiplying the difference of a and b by the sum of a, b, and c.  Return that
  59 number as a _^Hr_^He_^Hs_^Hu_^Hl_^Ht, or _^Hv_^Ha_^Hl_^Hu_^He.
  60 
  61      Here is another function definition:
  62 
  63 (defun squareprint (arg)
  64        (print "The square of")
  65        (print arg)
  66        (print "is")
  67        (print (* arg arg))
  68        5)
  69 
  70      This function, when invoked, will print the message "The square of",
  71 print the value of its argument, print the word "is", and print the value of
  72 the square of its argument.  It _^Hr_^He_^Ht_^Hu_^Hr_^Hn_^Hs the value 5.  The function
  73 "squareprint" has side effects: it causes output on the console.  It also
  74 returns a value, the number 5.  Note that all Lisp functions produce a value;
  75 only some produce side effects.  The first function we defined returns the
  76 product of those numbers as a value; the second returns 5.
  77 
  78      If we look at squareprint, we see that it almost consists of
  79 "statements", the "print statements" that print things.  These statements
  80 are called _^Hf_^Ho_^Hr_^Hm_^Hs, and what they are in fact are calls to _^Ho_^Ht_^Hh_^He_^Hr functions, in
  81 this case the built-in _^Hp_^Hr_^Hi_^Hn_^Ht function.  In the form
  82 
  83           (print "The square of")
  84 
  85 the print function is being passed as an argument the string "The square of".
  86 Like all functions, _^Hp_^Hr_^Hi_^Hn_^Ht will return a value, in
  87 this case, something which we will not use.  The side-effect of
  88 printing something will occur.  In the form
  89 
  90           (+ a b c)
  91 
  92 we are asking to invoke the "+" function, which is also built-in, passing it
  93 as arguments the values of the parameter-variables a, b, and c.  It will
  94 return a value, which is the requested sum, and produce no side effects.
  95 
  96      There are five forms in the function-definition for _^Hs_^Hq_^Hu_^Ha_^Hr_^He_^Hp_^Hr_^Hi_^Hn_^Ht:
  97 
  98        (print "The square of")
  99        (print arg)
 100        (print "is")
 101        (print (* arg arg))
 102        5
 103 
 104       Forms immediately inside a function definition are executed
 105 sequentially, like statements in other programming languages.  The value
 106 produced by the last form is the one the function itself returns.  What does
 107 it mean to "execute" a 5? "Execute" is not exactly the right term, that is
 108 where the problem lies.  What really happens is that these forms are
 109 _^He_^Hv_^Ha_^Hl_^Hu_^Ha_^Ht_^He_^Hd.  This means that a value is produced from them.  Evaluating a 5
 110 produces the number 5; evaluating the form
 111 
 112       (+ a b c)
 113 
 114 calls the "+" function with the appropriate arguments, and produces whatever
 115 value the "+" function returns.  The value produced by the "print" function
 116 is something which is not interesting, but a value is produced.
 117 
 118      Numbers, like 5, and strings, like "The square of" are said to evaluate
 119 to themselves.  Things between parentheses, like
 120 
 121      (+ a b c)
 122      (print "The square of")
 123 
 124 are calls to functions, which are evaluated by calling the function
 125 indicated, and producing the value it returns.  Function calls have the syntax
 126 
 127     (FUNCTIONNAME ARGFORM1 ARGFORM2 ARGFORM3 ... ARGFORMn)
 128 
 129 FUNCTIONNAME is the name of the function to call; the ARGFORMs are themselves
 130 forms, which will be evaluated to produce the arguments to give to the
 131 function.  Thus, we see that to evaluate (i.e., "execute" and find the value
 132 returned by so executing) a form like
 133 
 134     (+    (*  a  b)
 135           15
 136           c)
 137 
 138      We evaluate the _^Hi_^Hn_^Hn_^He_^Hr _^Hf_^Ho_^Hr_^Hm (* a b) to produce a value,
 139      We evaluate the 15 to produce 15 (remember, numbers and strings evaluate
 140         to themselves)
 141      We evaluate the _^Hv_^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He c to produce its value,
 142 
 143        And pass these three values on to the "+" function, and return what
 144        it returns.
 145 
 146      Thus, forms are seen to be either numbers like 5, strings like "is",
 147 variables like b, or function calls like (* a b).
 148 
 149      Variables are much like variables in other languages. A variable has a
 150 value, which is called its _^Hb_^Hi_^Hn_^Hd_^Hi_^Hn_^Hg.  At this stage of the exposition, this
 151 value must be a string or a number.  When a function is invoked, the
 152 parameter variables (like a, b, and c above) of the function acquire the
 153 arguments of the function call as bindings.  Evaluating a variable produces
 154 its binding as a value.  For instance, if someplace in a function we cause
 155 the form
 156 
 157           (addandmult 2 (+ 3 2) 6)
 158 
 159 to be evaluated, a, b, and c will have the bindings 2, 5, and 6 while
 160 the forms in the definition of _^Ha_^Hd_^Hd_^Ha_^Hn_^Hd_^Hm_^Hu_^Hl_^Ht are being evaluated.  This is not
 161 unlike the subroutine parameter mechanism in other languages.  It is very
 162 different insofar that it specifies what _^Hv_^Ha_^Hl_^Hu_^He a variable has during
 163 "subroutine" execution.  In PL/I or FORTRAN, a parameter is associated with
 164 a variable in the calling program, not a value, during subroutine execution.
 165 
 166      There are parameter variables, as we have used above, temporary
 167 variables, which we will meet below, and global variables.  Regardless of
 168 what "kind" of variable we are dealing with, they all have bindings (values),
 169 and evaluation of the variable produces that value.
 170 
 171      Summarizing our naive introduction to dataless Lisp:
 172 
 173      1. Lisp programs are built of functions.
 174 
 175      2. Function definitions consist of the word "defun", the
 176         function's name, a "parameter list", and a number of forms, which
 177         are to be sequentially evaluated at function call time, with
 178         a pair or parentheses around the whole thing.
 179 
 180      3. The value of the last form in a function will be the value returned
 181         by that function.
 182 
 183      4. Forms can be either strings, numbers, variables or calls on functions.
 184         Forms are _^He_^Hv_^Ha_^Hl_^Hu_^Ha_^Ht_^He_^Hd to produce values,
 185         which are passed around between functions as arguments and results.
 186 
 187      5. Strings and numbers evaluate to themselves.
 188 
 189      6. Variables evaluate to the datum to which they are bound, which,
 190         for a parameter, is the corresponding argument to the containing
 191         function.
 192 
 193      7. Function calls contain the name of a function to call and
 194         forms which are evaluated to produce the arguments to the
 195         function.  Function calls may produce side-effects.  Like any form,
 196         when a function call is evaluated, it produces a value.
 197 
 198 
 199 
 200 
 201                                   P^H__^Hr_^He_^Hd_^Hi_^Hc_^Ha_^Ht_^He_^Hs
 202 
 203      Programming languages need conditional execution.  In order to control
 204 conditional execution, we need things upon which to base a decision.  There
 205 are two data objects in the Lisp world corresponding to truth and falsity,
 206 for the purposes of parts of the Lisp system that deal with conditions.
 207 There are a set of functions called _^Hp_^Hr_^He_^Hd_^Hi_^Hc_^Ha_^Ht_^He_^Hs which return these objects as
 208 values.  For instance, there is a function called ">" which, invoked as
 209 
 210     (> 4 6)
 211 
 212 will return the indicator of falsity, and when invoked as
 213 
 214     (> 4 1)
 215 
 216 will return the indicator of truth.   Predicates work just like other
 217 built-in and non built-in functions, like print, addandmult, squareprint,
 218 and +.  They take arguments, and produce a result.  In the case of
 219 predicates, however, the result is not a string or a number, but
 220 an indication of truth or falsity.  The result of a predicate can be used
 221 by the "_^Hi_^Hf special form" to control the execution of a function, and we
 222 will consider _^Hi_^Hf shortly.
 223 
 224      Here are some of the most useful Lisp predicates.  In all of these
 225 examples, A1, A2, S1, O1, etc., stand for _^Hf_^Ho_^Hr_^Hm_^Hs, which means they
 226 can be 12, (+ 6 q), (myfun 33 (- a b)), etc.  When we say below that
 227 "A1 is a number" below, what re really are trying to say is that A1
 228 is some form which _^He_^Hv_^Ha_^Hl_^Hu_^Ha_^Ht_^He_^Hs to a number, such as 3, (+ 6 2),
 229 or x49, if x49's value is indeed a number.
 230 
 231      Predicates for numbers:  A1 and A2 are numbers:
 232 
 233   Predicate   Example   Returns TRUTH if ..., otherwise falsity.
 234   _________   _______   ________________________________________
 235 
 236      =        (= A1 A2)     A1 and A2 are the same number.
 237      >        (> A1 A2)     A1 is a bigger number than A2.
 238      <        (< A1 A2)     A1 is a smaller number than A2.
 239 
 240      Predicates for strings: S1 and S2 are strings:
 241 
 242      samepnamep
 243               (samepnamep S1 S2)   S1 and S2 are strings of identical
 244                               content, i.e., the "same string".  This is
 245                               the standard way to see if two strings are
 246                               the same, as in (samepnamep test "-hold")
 247      alphalessp
 248               (alphalessp S1 S2)   S1 collates before S2 alphabetically, e.g.,
 249                               (alphalessp "Able" "Baker") returns truth, but
 250                               (alphalessp "Zeke" "Joe") does not.
 251 
 252      Predicate for symbols (including character objects), which we will
 253      learn more about later: SY1 and SY2 are symbols.
 254 
 255      eq       (eq SY1 SY2)    SY1 and SY2 are the same symbol.
 256 
 257      Predicates for any objects: O1 is some object, of perhaps unknown type:
 258 
 259      fixp     (fixp O1)       O1 is a number, as opposed to some other kind
 260                               of object.
 261      stringp  (stringp O1)    O1 is a string, as opposed to anything else.
 262      symbolp  (symbolp O1)    O1 is a symbol, as opposed to anything else.
 263      null     (null O1)       O1 is not only a symbol, but the very important
 264                               and critical symbol named "nil".
 265 
 266                               Lisp Special Forms
 267                           -------------------------
 268 
 269      Now there are a number of _^Hs_^Hp_^He_^Hc_^Hi_^Ha_^Hl _^Hf_^Ho_^Hr_^Hm_^Hs in Lisp, which do not go by the
 270 simple rules given above.  We have already seen one.  The function-defining
 271 form, which begins with the word "defun", is not simply a function call with
 272 forms to produce the function's arguments.  By all rights, a form like
 273 
 274    (defun square (x)
 275           (* x x))
 276 
 277 should, when evaluated, evaluate, in order, to produce arguments for "defun",
 278 
 279        1. A variable named "square".
 280        2. The form "(x)", calling a function named "x" with no arguments.
 281        3. The form "(* x x)", multiplying the value of a variable named "x"
 282           by itself,
 283 
 284 and then pass these three values onto the "defun" function.  This, however
 285 is not actually what happens.  Evaluating the "defun" form causes a function
 286 named "square" to be defined, whose parameter list and "body" are as given.
 287 Defun is a _^Hs_^Hp_^He_^Hc_^Hi_^Ha_^Hl _^Hf_^Ho_^Hr_^Hm, and when Lisp sees "defun" as the function-name in a
 288 form it has been asked to evaluate, it says "Stop everything, I'm going to
 289 do something special with this, in this case, define a _^Hf_^Hu_^Hn_^Hc_^Ht_^Hi_^Ho_^Hn built out of
 290 this _^Hf_^Ho_^Hr_^Hm _^Hi_^Ht_^Hs_^He_^Hl_^Hf."  It is _^Hn_^Ho_^Ht a call to "defun" with arguments.  Although
 291 this may seem kludgey at first, it can be shown that one must have at least
 292 one such special form in order to have an operative Lisp system of any kind.
 293 
 294      There is a special form in the Multics Emacs Lisp environment called _^Hi_^Hf,
 295 which is used to control conditional execution (conditional evaluation).
 296 Here is an example of its use:
 297 
 298 (defun which-is-greater (first second)
 299        (if (> first second)
 300            (print "The first one is the greater.")
 301          else
 302            (if (> second first)
 303                (print "The second one is greater")
 304              else
 305                (print "They are equal")))
 306 
 307 The syntax of _^Hi_^Hf is as follows:
 308 
 309      (if <PREDICATE>
 310          <THEN-FORM-1>
 311          <THEN-FORM-2>
 312              ...
 313          <THEN-FORM-m>
 314        else
 315          <ELSE-FORM-1>
 316          <ELSE-FORM-2>
 317              ...
 318          <ELSE-FORM-n>   )
 319 
 320      Any number, including none, "THEN-FORM"s may be supplied.  Similarly,
 321 any number, including none, of the "ELSE-FORM"s may be given.  If there are
 322 no "ELSE-FORM"s, then the keyword "else" may be omitted, too.
 323 
 324      Note that all the forms in the _^Hi_^Hf are _^Hn_^Ho_^Ht sequentially evaluated; the
 325 word _^He_^Hl_^Hs_^He is not even intended to be a form.  If all of the forms inside the
 326 _^Hi_^Hf were evaluated, it would be useless, for execution (evaluation) would not
 327 be conditional.   That is why _^Hi_^Hf is a special form; there are special rules
 328 about how forms inside it are to be evaluated.  The rule for all non-special
 329 forms is the same: you evaluate all the sub-forms sequentially to produce the
 330 arguments to the function.
 331 
 332      The _^Hi_^Hf special form evaluates the <PREDICATE>: if it results in truth,
 333 the <THEN-FORM>s are sequentially evaluated, and the value of the last one is
 334 returned as the value of the _^Hi_^Hf.  Otherwise, the <ELSE-FORM>s are evaluated
 335 sequentially, and the value of the last returned.  If there are none,
 336 something useless is returned (nil, to those knowledgeable in Lisp).
 337 
 338      There are two global variables in Lisp, called "t" and "nil", whose
 339 bindings are always the truth and falsity indicators respectively.  Thus,
 340 
 341    (if t
 342        (print "Truth")
 343      else
 344        (print "Not so truth"))
 345 
 346 when evaluated, will always print "Truth".
 347 
 348      There is a way to change the value of a variable.  The only way we have
 349 seen so far that variables acquire values is by being parameters, and
 350 acquiring values at function call time.  Values can be changed by the special
 351 form _^Hs_^He_^Ht_^Hq:
 352 
 353 (defun adder-of-one ()
 354        (print "The value of x is")
 355        (print x)
 356        ("And the value of x plus one is")
 357        (setq x (+ x 1))
 358        (print x))
 359 
 360 A _^Hs_^He_^Ht_^Hq form has the word _^Hs_^He_^Ht_^Hq, the name of a variable, and an inside form.
 361 The inside form is evaluated, and that value assigned to the variable.  It is
 362 like an assignment statement in other languages.
 363 
 364      There is a construct for looping in the Multics Emacs Lisp environment.
 365 It, too, is a special form.  It is called "do-forever":
 366 
 367 (do-forever
 368     (print "Yay Multics")
 369     (print "scitluM yaY"))
 370 
 371 will, when evaluated, print these two sayings forever.  The way you stop
 372 doing in a do-forever is to evaluate the form "(stop-doing)":
 373 
 374 (defun print-n-times (n)
 375        (do-forever
 376          (if (= n 0)(stop-doing))
 377          (print "foo")
 378          (setq n (- n 1))))
 379 
 380 This function, given a number as an argument, will print "foo" that many
 381 times. The "=" builtin function/predicate compares its two arguments, which
 382 must be numbers, and returns truth or falsity depending on whether or not they
 383 are numerically equal. Note that the arguments to "=" are _^Hn_^Ho_^Ht n and 0, but
 384 rather, the number which is the binding of n and 0.  The number which is the
 385 binding of n is different each time around the loop; that is the point of the
 386 program.  It is _^Hs_^He_^Ht_^Hq which changes the value of n each time around, as
 387 do-forever executes the loop.  A "do-forever" form generally returns something
 388 useless (nil), unless you exit by saying (return 5) or (return nil), or
 389 (return a), in which latter case the value of the variable a is returned.
 390 
 391      One can acquire temporary variables via the special form "let":
 392 
 393 (defun sumtimesdif (x y)
 394    (let ((sum (+ x y))
 395          (dif (- x y)))
 396         (print "Sum times difference is ")
 397         (print (* sum dif))
 398         (print "Sum squared is")
 399         (print (* sum sum))))
 400 
 401 This function has two temporary variables, sum and dif, which are
 402 initialized to the values of (+ x y) and (- x y).  The general syntax of
 403 "let" is:
 404 
 405      (let ((VAR1 VAL1)
 406            (VAR2 VAL2)
 407            ...........
 408            (VARn VALn))
 409           <FORM1>
 410           <FORM2>
 411           .......
 412           <FORMm>)
 413 
 414      The temporary variables VAR1...VARn exist only within the _^Hl_^He_^Ht.  They get
 415 the initial values of VAL1-VALn, which are forms that will be evaluated.
 416 Then, with all these temporary variables set up and initialized, the FORMi's
 417 are evaluated sequentially, and the value of the last FORMi is returned by _^Hl_^He_^Ht.
 418 
 419      Another, less useful way of acquiring temporary variables is via the
 420 special form _^Hp_^Hr_^Ho_^Hg.  Forms inside a _^Hp_^Hr_^Ho_^Hg are evaluated sequentially, like
 421 forms in a function definition.  However, the first "form" in a _^Hp_^Hr_^Ho_^Hg is not
 422 really a form at all, but rather a list of temporary variables used in the
 423 _^Hp_^Hr_^Ho_^Hg, such as "(a b c)".  That is why _^Hp_^Hr_^Ho_^Hg is a special form.  The value
 424 returned by _^Hp_^Hr_^Ho_^Hg is usually useless, unless (return...) is used to return
 425 something meaningful.
 426 
 427      Inside a _^Hp_^Hr_^Ho_^Hg, one can also put "labels", to use for
 428 go-to's:
 429 
 430 (defun bar2 (x y)
 431        (prog ()                         ;note the empty variable list
 432              (if (< x y)(go lab1))
 433              (print "X is not less than Y")
 434              (return nil)               ;return "false" indication
 435         lab1
 436              (print "so be it!")
 437              (return t)))               ;return "true" indication.
 438 
 439 Note the special form _^Hg_^Ho, whose _^Ho_^Hp_^He_^Hr_^Ha_^Hn_^Hd (_^Hn_^Ho_^Ht argument)
 440 is a _^Hl_^Ha_^Hb_^He_^Hl to which to "go", i.e., continue sequential evaluation of forms in
 441 the prog.  You wil find that labels are rarely needed, due to the powerful
 442 _^Hi_^Hf and _^Hd_^Ho-^H_^H__^Hf_^Ho_^Hr_^He_^Hv_^He_^Hr constructs.
 443 
 444      There are special forms for or-ing and and-ing predicate results: they
 445 are special because they stop evaluating their operands (from which arguments
 446 are produced) when they "know" their answer for certain:
 447 
 448     (if (and (not (= x 0))
 449              (> (// 10 x) 5))
 450         (print "Quotient too large."))
 451 
 452 The _^Hn_^Ho_^Ht function inverts truth and falsity.
 453 The double-slash indicates division, because slash is the escape character in
 454 Lisp.
 455 
 456      Note that the _^Ha_^Hn_^Hd will not attempt to evaluate the second form within it
 457 if the first produces falsity.  This prevents an error which would result if
 458 an attempt were made to divide by zero.   Sequential execution and stopping
 459 at an intermediate result are a defined and useful feature here, as opposed
 460 to the logical operators of, say, PL/I.
 461 
 462      There are two more special forms worth mentioning while we are on the
 463 topic, progn and prog2.  _^Hp_^Hr_^Ho_^Hg_^Hn is used to force sequential execution of forms
 464 and returning the value of the last.  For instance,
 465 
 466 (if (and (> x 3)
 467          (progn (print "Oh dear this is getting serious")
 468                 (> y 5))
 469          (print "Fatal difficulty")))
 470 
 471 _^Hp_^Hr_^Ho_^Hg_^Hn returns the value of its last form.  Thus, the _^Ha_^Hn_^Hd tests x being
 472 greater than 3, and y being greater than 5, before the "print" of "Fatal
 473 difficulty" is evaluated.  The printing of "Oh dear..." occurs as part of the
 474 evaluation of the _^Hp_^Hr_^Ho_^Hg_^Hn, it is only the second value in the progn which _^Ha_^Hn_^Hd
 475 gets to see.  The _^Hp_^Hr_^Ho_^Hg_^Hn is used to force evaluation of the _^Hp_^Hr_^Hi_^Hn_^Ht form.
 476 
 477      _^Hp_^Hr_^Ho_^Hg2^H_ is even a bit stranger, but often just the thing one needs.  _^Hp_^Hr_^Ho_^Hg2^H_
 478 is just like _^Hp_^Hr_^Ho_^Hg_^Hn, except that it returns its _^Hs_^He_^Hc_^Ho_^Hn_^Hd argument, evaluated,
 479 rather than its last.  It must have at least two arguments.  It is used for
 480 clever tricks that involve saving some value which is subsequently going to
 481 be destroyed.  The following form, when evaluated, interchanges the values of
 482 x and y:
 483 
 484 (setq x (prog2 0                        ; this zero is evaluated to 0, and
 485                                         ; its value thrown away.
 486                y                        ; the value of y is obtained here, and
 487                                         ; remembered as it is here.
 488                (setq y x)))             ; x is evaluated, and that value
 489                                         ; assigned  to y. The value of setq
 490                                         ; is that value.
 491           ; But the value of the _^Hp_^Hr_^Ho_^Hg2^H_ is that value of y as it was before we
 492           ; assigned into y, and now the outer setq assigns that to x.
 493 
 494 
 495                                    S^H__^Hy_^Hm_^Hb_^Ho_^Hl_^Hs
 496 
 497      There is one more type of data object in Lisp that will concern us at
 498 present.  It is called the _^Hs_^Hy_^Hm_^Hb_^Ho_^Hl.  Symbols are named data objects kept in a
 499 registry of symbols, by Lisp.  For current purposes, there is only one symbol
 500 of any name.  Symbols are used in Multics Emacs to represent buffer names,
 501 and various quantities associated with buffers.  Lisp uses symbols to keep
 502 track of functions, and internally to keep track of global variables.
 503 
 504      To use a symbol in a program, we give the name of the symbol preceded by
 505 the ASCII quote character, '.  For instance,  the form
 506 
 507 (setq x 'Brunhilde)
 508 
 509 assigns the symbol named Brunhilde to x.  Note that this is different
 510 from
 511 
 512 (setq x "Brunhilde")
 513 
 514 which assigns the _^Hs_^Ht_^Hr_^Hi_^Hn_^Hg Brunhilde to x, and from
 515 
 516 (setq x Brunhilde)
 517 
 518 which assigns the value of the variable Brunhilde to x.
 519 
 520                               L^H__^Hi_^Hs_^Hp L^H__^Hi_^Hs_^Ht_^Hs
 521 
 522      The final data-type of Lisp with which we will have reason to deal is the
 523 _^Hc_^Ho_^Hn_^Hs (for construct), and the larger data-type built out of it, the _^Hl_^Hi_^Hs_^Ht.
 524 Conses are blocks which relate to two (usually other) objects in the
 525 environment, which are known as its _^Hc_^Ha_^Hr and its _^Hc_^Hd_^Hr, for historical reasons.
 526 The function "cons", given two objects, produces a new cons, whose car and
 527 cdr, respectively, are the two objects given.  For instance, let's say
 528 that the variable "x" has a value of the string "Brunhilde", as above,
 529 then
 530 
 531           (cons 7 x)
 532 
 533 produces a cons whose car is the number 7 and whose cdr is the string
 534 "Brunhilde", returning it as a value.  The functions "car" and "cdr"
 535 may be used to obtain the car and cdr of a cons.  Let us say that we had
 536 set the variable "c" to the result of the form (cons 7 x) above, then
 537 
 538           (car c)
 539 
 540 produces the number 7 as a value.
 541 
 542      The usual thing to do with conses is to make larger and larger structures
 543 out of conses, by setting up conses whose car and cdr are more conses,
 544 and so forth, until we have a large enough structure to represent all the
 545 values we need.  The resulting construction serves the same purpose
 546 as a PL/I structure: its various parts have meaning assigned by the
 547 programmer.
 548 
 549      The most common construction of conses is the "list".  A list
 550 is defined as a chain of conses, each of which has the next one
 551 in the chain as its cdr, except the last one, which has the symbol "nil"
 552 as its cdr.  A list built in this way of n conses is called a list of n
 553 _^He_^Hl_^He_^Hm_^He_^Hn_^Ht_^Hs, the elements being the n objects which are the cars of the conses.
 554 The cons at the head of the list is identified as being "the list": its
 555 car is the first element in the list, its cdr is the cons whose
 556 car is the second element of the list, and so forth.  Let us
 557 construct a list of the numbers 2, 4, 5, and 7, in that order, and
 558 set the variable "b" to it:
 559 
 560           (setq b (cons 2 (cons 4 (cons 5 (cons 7 nil)))))
 561 
 562 (Note that the variable "nil" is peculiar insofar as its value is always
 563 the symbol "nil", thus we need not say 'nil.)
 564 
 565 There is a function that simplifies the writing of such forms, for
 566 constructing lists: it builds lists directly, and accepts any number
 567 of arguments.  It produces the same result as the type of construction
 568 shown above.  It is called "list":
 569 
 570           (setq b (list 2 4 5 7))
 571 
 572 To get the third element of the list, once this form were evaluated, we
 573 could evaluate the form
 574 
 575           (car (cdr (cdr b)))
 576 
 577 (ie.e, the car of the cons which is the cdr of the cons which is the
 578 cdr of the cons which is the value of b).  Again, there are
 579 Lisp functions to simplify such constructions.  The above form
 580 is equivalent to
 581 
 582           (caddr b)
 583 
 584 In general, for up to 4 car's and cdr's deep, total, functions
 585 like cadr, cdar, caddr, cadar and so forth, are provided (up through caaaar
 586 and cddddr).  The first four elements of a list are gotten by
 587 car, cadr, caddr, and cadddr (it is good exercise to work that
 588 through and verify why this is the case).
 589 
 590      When lists are printed out by Lisp, they are represented
 591 as a pair of parentheses around the printed representations of all
 592 of the elements, in sequence, separated by spaces.  Thus, if
 593 Lisp printed out the list which was b's value above, it would
 594 appear
 595 
 596           (2 4 5 7)
 597 
 598 Conses whose cdr is the symbol nil may always be viewed as lists
 599 of one item, and are so printed out by Lisp, unless it is in the
 600 process of printing a larger list of which the cons at issue is
 601 a chain-link.  Conses whose cdr is neither nil nor another cons
 602 are printed with a dot preceding the cdr. Thus:
 603 
 604           (cons 'a 'b)  =>  (a . b)
 605           (cons 'a nil) =>  (a)                   ;a list of one element
 606           (cons 'a (cons 'b 'c)) => (a b . c)
 607           (cons 'a (cons 'b nil)) => (a b)        ;list of two elements
 608           (cons 'a (cons (cons 'b 'c)(cons 'd nil))) ;list of three
 609                     => (a (b . c) d)
 610 
 611 Lists can be put into programs, by quoting them, as we quote symbols:
 612 
 613           (setq b1 '(this is (a list)(of lists)))
 614 
 615 Two functions are provided to redefine the car or cdr of an existing cons.
 616 They can be very dangerous if misused, especially if they alter a list as in
 617 the form above, which is written into a program as a constant.  rplaca
 618 (replace car) and rplacd (replace cdr) each take two arguments, the first is
 619 the cons which is to be altered, and the second is the new car or new cdr
 620 respectively.  the returned value is the cons itself.
 621 
 622                       A^H_C^H_T^H_U^H_A^H_L^H_L^H_Y^H_ W^H_R^H_I^H_T^H_I^H_N^H_G^H_ E^H_M^H_A^H_C^H_S^H_ E^H_X^H_T^H_E^H_N^H_S^H_I^H_O^H_N^H_S^H_
 623 
 624      The starting point for writing extensions is building functions out of
 625 provided functions in the Emacs Lisp environment, and hooking them
 626 up to keys.  The documented set-key and set-permanent-key commands can be
 627 used to connect keys to Lisp functions that you provide, as well as to
 628 provided commands and keyboard macros.
 629 
 630      Many simple and useful extensions are just groups of provided commands
 631 strung together.  For instance, suppose that we want to write a function that
 632 goes to the beginning of a line, deletes all whitespace there, goes to the end
 633 of the line, does the same, and then goes back to the beginning of the line.
 634 
 635      Interactively, we would type;
 636 
 637           ^A ESC-\ ^E ESC-\ ^A
 638 
 639 to do this.  To write such a function, called "shave-line", let us say, we
 640 would write this:
 641 
 642 (defun shave-line ()                    ;keystroke functions take no args.
 643        (go-to-beginning-of-line)
 644        (delete-white-sides)
 645        (go-to-end-of-line)
 646        (delete-white-sides)
 647        (go-to-beginning-of-line))
 648 
 649 Write this function in a file, with the editor of your choice.  When in
 650 Emacs, say ESC-X loadfile PATHNAME CR, to load it in as code.  Then hook it
 651 up, perhaps by saying
 652 
 653        ESC-X set-key ^XA shave-line CR
 654 
 655 Then, hitting ^XA will cause the chosen sequence of actions to happen.  In
 656 order to find out the names of the functions that we had to use to code shave-
 657 line, all we had to do is ask ESC-? what the names of the functions on ^A,
 658 ^E, and ESC-\ were.
 659 
 660      Now we want to be able to do more complex things, like use conditionals
 661 and variables.  Let us say that we wanted a function that went to the
 662 beginning of a line and deleted all words that started with "foo" from the
 663 beginning of the line.
 664 
 665 (%include e-macros)
 666 
 667 (defun foodeleter ()
 668        (go-to-beginning-of-line)
 669        (do-forever
 670           (if (looking-at "foo")
 671               (delete-word)
 672               (delete-white-sides)
 673             else (stop-doing))))
 674 
 675 The (%include e-macros) must be at the beginning of any file that uses the
 676 Emacs environment Lisp macros.   The file e-macros.incl.lisp is found in the
 677 same directory as the editor.  It should be in your "translator" search path
 678 in order to do any Emacs extension development work.
 679 
 680     What this function does in essence is type ^A, and as long as the first
 681 three characters on the line are "foo", does ESC-D's followed by ESC-\ to
 682 remove the whitespace after the word.  When the first three characters are no
 683 longer "foo", it will return.  "looking-at" is an Emacs predicate (to be
 684 described in detail below) which tests whether a given string is to the right
 685 of the current "cursor".  We will no longer discuss the issue of how to hook
 686 this or any other function up to a given key; we have already covered that
 687 adequately.  From this point on, we will only discuss coding functions.
 688 
 689      If you write the function foodeleter, hook it up to a key and use it,
 690 you will watch all foo-starting words magically disappear at once from the
 691 begninning of a line with foo-starting words at its front, when you strike
 692 this key.  Note that the code for foodeleter has no mention of printing,
 693 output, or displays.  It cares and or knows exactly as much about them as you
 694 do when typing Emacs keystroke commands.  It just manipulates the text in the
 695 buffer, and the screen or printing terminal is managed automatically by the
 696 magic of the Multics Emacs redisplay.  The display need never be thought
 697 about in coding Emacs extensions.
 698 
 699      It is a major intentional feature that many of the commands that are
 700 connected to keys can be, and should be used in coding extensions.
 701 go-to-end-of-line, go-to-beginning-of-buffer, skip-over-indentation,
 702 forward-char, and delete-word are typical of them.  There are some commands,
 703 however, that should not be used from extension code.  For example, if you
 704 wanted to search for some string, you do not want to invoke
 705 string-search, which is what ^S is connected to, for that will prompt
 706 the user in the minibuffer for what to search for.  Here is a table of
 707 some keystroke commands that you should not use in extensions, what you
 708 should use instead, and why:
 709 
 710 KEY       DONT USE            USE INSTEAD         WHY
 711 
 712 ^N        next-line-command   next-line           next-line command worries
 713                                                   about screen position,
 714                                                   which is expensive and
 715                                                   usually not needed.
 716                                                   Also worries about
 717                                                   numeric arguments.
 718 
 719 ^P        prev-line-command   prev-line           Same reasons as above.
 720 
 721 ^K        kill-lines          kill-to-end-of-line
 722                               delete-char (at eol)
 723                                                   ^K is very complex, has
 724                                                   many cases, worries about
 725                                                   numeric arguments.
 726 
 727 ^S        string-search       forward-search      forward-search takes string
 728                                                   as Lisp argument, does not
 729                                                   prompt.  Moves "cursor" if
 730                                                   search succeeds; returns
 731                                                   truth or falsity to indicate
 732                                                   result.
 733 
 734 ^R        reverse-string-search
 735                               reverse-search      Same as ^S.
 736 
 737 ^X^R      read-file           read-in-file        read-in-file takes Lisp
 738                                                   argument for pathname,
 739                                                   does not prompt.
 740 
 741 ^X^W      write-file          write-out-file      Same as ^X^R.
 742 
 743 ^W        wipe-region         wipe-point-mark     Use local marks, see below.
 744 
 745 ESC-/     regexp-search-command
 746                               regexp-search       Same arguments as ^S. Takes
 747                                                   Lisp argument, no slashes.
 748                                                   Returns falsity if not found
 749                                                   or moves cursor to after
 750                                                   and returns mark to before
 751                                                   matched string if found.
 752 
 753 ^XB       select-buffer       go-to-or-create-buffer  Takes arg, doesn't prompt
 754 
 755 ^X^F      find-file           find-file-subr      Ditto.
 756 
 757           This list is probably not complete, but these are the important
 758 ones to know.
 759 
 760           Commands whose behavior is indistinguishable between ESC-5-<FOO>
 761 and <FOO><FOO><FOO><FOO><FOO>, i.e., ^B, ^D, ^F, ESC-B, ESC-D, ESC-F,
 762 #, ESC-#, etc., are OK to use in extensions;  they do not inspect their
 763 arguments.  They are invoked multiple times by the Emacs listener if
 764 appropriate.   Commands whose names include the word "command" (other than
 765 ^G, command-quit) are usually not intended to be used in code.
 766 
 767      The value of the numeric command argument, i.e., "5" in ESC-5-<FOO>,
 768 is available as the binding of the global variable "numarg"; if there was no
 769 numeric argument given, this variable is set to the symbol "nil" (not to be
 770 confused with the global variable nil, whose binding is the symbol nil) which,
 771 we now disclose, is _^Ht_^Hh_^He representation of falsity.
 772 
 773      The normal printing characters are hooked up to the function
 774 self-insert, which inserts the last physical character typed at the current
 775 point in the buffer.  This is clearly unusable from code, if your desire is
 776 to insert text into the buffer.  For this purpose, the Emacs environment
 777 provides the function "insert-string", whose argument is a string to be
 778 inserted  into the buffer at the current cursor.  As in typing in text
 779 manually, the cursor is left after the inserted text:
 780 
 781 (defun make-a-point ()
 782        (go-to-beginning-of-line)
 783        (insert-string "CASE IN POINT:   "))
 784 
 785      make-a-point, when invoked, goes to the beginning of the line, and
 786 inserts the string "CASE IN POINT:   " in the buffer.  The cursor is left
 787 after the inserted string.
 788 
 789     When we say "the cursor is moved around" or "a string is inserted" in a
 790 function, we do not imply that the user watching the screen can see all these
 791 things happen.  No action on the screen occurs until the entire function has
 792 finished running, at which time, the screen is updated all at once, as
 793 appropriate, showing the total, cumulative effect of what has happened,
 794 regardless of how it happened.
 795 
 796                           M^H__^Ha_^Hr_^Hk_^Hs _^Ha_^Hn_^Hd _^Ht_^Hh_^He_^Hi_^Hr M^H__^Ha_^Hn_^Ha_^Hg_^He_^Hm_^He_^Hn_^Ht
 797 
 798      A concept of great value is that of the "mark", or, as it is called in
 799 other Emacs-like editors, the editor buffer pointer.  Like the cursor, a mark
 800 is a conceptual pointer to the position between two characters in the current
 801 buffer.  Marks, like the cursor, have the property that they remain between
 802 the two characters between which they were put regardless of other insertions
 803 or deletions in the same buffer, even on the same line as the mark.  Marks
 804 are valuable because regions of text in the buffer are specified as the
 805 extent between the current conceptual cursor, hereafter known as "point", and
 806 a given mark.  Marks are a type of data object in the Multics Emacs Lisp
 807 environment, like strings, numbers,and symbols.  The value of any variable
 808 may be made to be a mark.  The value of many variables might even be the same
 809 mark! The "the-mark" spoken of in the documentation is just one mark, that
 810 is the value of a global variable that many supplied functions know about.
 811 Emacs functions use many temporary marks.
 812 
 813      The function set-mark creates a new mark, which points to the current
 814 "point" in the current buffer.  It stays around, and is updated by the editor,
 815 any time text is inserted or deleted in this buffer.  Since this is
 816 expensive, we must take care to discard, or _^Hr_^He_^Hl_^He_^Ha_^Hs_^He marks when we are done
 817 using them.  This is done by giving them to the function release-mark.  Here
 818 is an example of a function which deletes three words and all between them:
 819 
 820 (defun delete-three-words ()
 821        (let ((temp-mark (set-mark)))     ;make a mark in a temp var.
 822              (do-times 3 (forward-word)) ;3 words forward
 823              (wipe-point-mark temp-mark) ;wipe out the stuff between point
 824                                         ;and where point was.
 825              (release-mark temp-mark)))
 826 
 827 The variable temp-mark is set to a mark representing the "point" at the time
 828 delete-three-words is entered. "do-times" is a very useful construct in the
 829 Multics Emacs Lisp environment, that repeats the evaluation of one or more
 830 forms a given number of times. Its syntax is:
 831 
 832     (do-times <HOWMANY> <FORM1> <FORM2> .. <FORMn>)
 833 
 834 wipe-point-mark is a function which, given a mark, takes all the text between
 835 "point" at the time it is invoked and that mark (i.e., "point" at the time
 836 that mark was created) and deletes it from the buffer.  It is, however,
 837 pushed on to the  kill ring, so that ^Y can be used to retrieve it.  If we
 838 did not want it pushed onto the kill ring, we could have said
 839 
 840     (without-saving (wipe-point-mark temp-mark))
 841 
 842 instead of
 843 
 844    (wipe-point-mark temp-mark)
 845 
 846 and no saving would have occured.  After we perform the computation, we free
 847 up the mark, to keep the performance of the editor up.
 848 
 849      The sequence of setting a mark, using it, and releasing it, is so common
 850 that a special construct in the Multics Emacs Lisp environment is provided
 851 which takes care of all of this, including the creation of a temporary
 852 variable, so no _^Hp_^Hr_^Ho_^Hg or _^Hl_^He_^Ht is needed.  It is called
 853 "with-mark".  The function delete-three-words, rewrtitten to use it, looks
 854 like this:
 855 
 856 (defun delete-three-words ()
 857        (with-mark m           ;m is usually used for the name of a mark.
 858                   (do-times 3 (forward-word))
 859                   (wipe-point-mark m)))
 860 
 861 The with-mark construct is very powerful and useful.  Its syntax is
 862 (the word "syntax" is a tip-off to a special form):
 863 
 864    (with-mark <MARKNAME>
 865       <FORM1>
 866       <FORM2>
 867         ...
 868       <FORMn> )
 869 
 870 It means:  "Where I am now, call that <MARKNAME>.  Evaluate (execute)
 871 the forms <FORM1> to <FORMN>, sequentially, returning the value of the last
 872 one as a value.  Before returning anything, however, free up the mark I made".
 873 
 874      A very common use of marks is to remember where you were at the time you
 875 started something, and after some traveling around, get back there when you
 876 are finished doing it. Here is an example of a function which truncates a
 877 line which is longer than 50 print positions, with backspaces and tabs all
 878 considered properly:
 879 
 880 (defun trunc-50 ()
 881      (with-mark m                       ;remember where we started
 882        (go-to-end-of-line)
 883        (if (> (cur-hpos) 50.)           ; dot is for decimal, default is octal
 884            (go-to-hpos 50.)
 885            (kill-to-end-of-line))       ;what ^K does not at e.o.l.
 886        (go-to-mark m)))                 ;return to where we were
 887 
 888      Several things are worth noting here.  "cur-hpos" is a very valuable
 889 function which tells you the horizontal position (on a dprint, not on the
 890 screen) of the current "point" (the left margin is considered to be 0).
 891 As can be seen from the from "(cur-hpos)", it takes no arguments.  The
 892 function go-to-hpos  moves point to a position on the current line whose
 893 horizontal position is its argument, or the end of the line, if the line is
 894 shorter than that.
 895 
 896      Now "(go-to-mark m)" is not some kind of a branch, but tells the editor
 897 to move the current point in this buffer to the point where it was at the time
 898 the mark, to which the variable m is bound, was created.
 899 
 900      Although moving the editor's point to previously saved marks is
 901 extremely common, just using the mark mechanism to remember where you were
 902 before some excursion and get back there is so common that a special
 903 mechanism is provided just for this: it is called save-excursion, and it deals
 904 with all the issues of temporary variables and releasing the mark when done.
 905 Our function trunc-50 recoded to use it looks like this:
 906 
 907 (defun trunc-50 ()
 908        (save-excursion
 909           (go-to-end-of-line)
 910           (if (> (cur-hpos) 50.)
 911               (go-to-hpos 50.)
 912               (kill-to-end-of-line))))
 913 
 914 The semantics of the save-excursion special form are as follows: Remember
 915 where I am, via a mark saved in a secret internal variable.  Evaluate all of
 916 the forms within the save-excursion, and return as a value the value of the
 917 last one.  Before returning anything however, move the editor point back to
 918 where it was when the save-excursion was first "entered", and release the
 919 mark used to remember this place.
 920 
 921 
 922      Note that if point were at print position 75. at the time trunc-50
 923 was called, it will wind up at position 50, even though the mark to which it
 924 wants to return points to what was at position 75.  No error is indicated, or
 925 has occured.  Marks live, even if characters to the right or left of them are
 926 deleted.
 927 
 928 
 929                               C^H__^Hl_^He_^Ha_^Hn_^Hu_^Hp H^H__^Ha_^Hn_^Hd_^Hl_^He_^Hr_^Hs
 930 
 931      You may have wondered, in the previous section, what happens if an
 932 extension encounters an error while executing, and never gets to release
 933 a mark it has set.   When errors occur (for example, forward-char (^F)'ing
 934 off the end of the buffer), Emacs aborts execution of command functions,
 935 returns to its listener, and beeps (as when a ^G is performed), as you
 936 know, if you have ever tried to ^V off the end of a buffer, or so forth.
 937 
 938      Since the releasing of marks has been pointed out as mildly critical,
 939 there is a need for a "cleanup-handler"-like facility to make sure that
 940 marks get release when code is aborted.  Indeed, there is such a facility
 941 in Lisp, and we will explain its use summarily.  This cleanup-handler
 942 facility is useful for many other things, too: "save-excursion" returns
 943 the cursor to the point at which it found it, if aborted through,
 944 save-excursion-buffer returns to the buffer where it found the editor
 945 if aborted through, all the mark-handling forms release their mark,
 946 and so forth.  These Emacs-environment primitives use the cleanup-handler
 947 facility internally, so we need not worry about cleanup-handlers if we
 948 use them.  However, occasionally, there are times (see the code
 949 for columnating the Emacs wall chart, for example) when we must use
 950 cleanup-handlers explicitly.  The Lisp form "unwind-protect"
 951 is the primitive cleanup-handler.  Here is its syntax:
 952 
 953      (unwind-protect
 954           <SUBJECTFORM>
 955           <CLEANUPFORM1>
 956           <CLEANUPFORM2>
 957           ...
 958           <CLEANUPFORMn>)
 959 
 960 The meaning of this is as follows: The <SUBJECTFORM> is evaluated, i.e.,
 961 executed,  and then <CLEANUPFORM1> to <CLEANUPFORMn> (any number of cleanup
 962 forms are permissible), and the value of the <SUBJECTFORM> returned.
 963 So far, unwind-protect is very much like _^Hp_^Hr_^Ho_^Hg2^H_ or _^Hp_^Hr_^Ho_^Hg_^Hn.  The difference,
 964 however, is that <CLEANUPFORM1> to <CLEANUPFORMn> will be executed even if the
 965 execution of <SUBJECTFORM> fails, and aborts!  Similarly, the cleanup forms
 966 will be executed even if diabolically tricky things like a _^Hr_^He_^Ht_^Hu_^Hr_^Hn from a _^Hp_^Hr_^Ho_^Hg
 967 inside the <SUBJECTFORM> causes its execution to terminate prematurely.
 968 
 969      Thus, the cleanup forms are executed after _^He_^Hv_^He_^Hr_^Hy termination of the
 970 <SUBJECTFORM>, whether normal or abnormal.  The following use of
 971 unwind-protect (which could clearly be done in simpler ways, but is here for
 972 illustrative purposes only) performs "complex-function", and returns the
 973 cursor to the beginning of the buffer, even if "complex-function"
 974 "explodes":
 975 
 976      (unwind-protect
 977           (complex-function)
 978           (go-to-beginning-of-buffer))
 979 
 980 Note that if you want more than one <SUBJECTFORM>, you had better use
 981 _^Hp_^Hr_^Ho_^Hg_^Hn to encompass them, and make your <SUBJECTFORM> this _^Hp_^Hr_^Ho_^Hg_^Hn.
 982 
 983      Unlike Multics/PL/I cleanup handlers, unwind-protect cleanup forms
 984 will be executed upon normal termination of the subject form, too.
 985 A close inspection of most PL/I programs using cleanup handlers shows
 986 that this may be the better idea after all.
 987 
 988 
 989                               U^H__^Hs_^He_^Hf_^Hu_^Hl P^H__^Hr_^He_^Hd_^Hi_^Hc_^Ha_^Ht_^He_^Hs
 990 
 991      The following predicates in the Multics Emacs environment are basic to
 992 all extension-writing; they are used to test various hypotheses about point,
 993 marks, and the buffer:
 994 
 995    (eolp)           ;End of line predicate. True if point is at end of a text
 996                     ;line, which is right before the newline character.
 997 
 998    (bolp)           ;Beginning of line predicate.  True if point is at the
 999                     ;start of a text ine, being either before the first
1000                     ;character of the buffer, or after a newline.
1001 
1002    (firstlinep)     ;First line predicate.  True if point is on the first
1003                     ;text line of the buffer.
1004 
1005    (lastlinep)      ;Last line predicate.  True if on last buffer line.
1006 
1007    (at-beginning-of-buffer)
1008                     ;True if point is right before the first character in the
1009                     ;buffer
1010 
1011    (at-end-of-buffer)
1012                     ;True if point is right before the newline on the last
1013                     ;line of the buffer. You can't go past it.
1014 
1015    (looking-at <STRING-VALUE>)
1016                     ;True if <STRING-VALUE> appears in the buffer
1017                     ;immediately to the right of point. Restriction:
1018                     ;<STRING-VALUE> may not contain a newline character,
1019                     ;except as its last character.
1020 
1021    (at-white-char)  ;True if the character to the right of point is
1022                     ;a space, newline, or tab.
1023 
1024    (point>markp <MARK>) ;True if the current point is _^Hf_^Hu_^Hr_^Ht_^Hh_^He_^Hr in the
1025                     ;buffer than the position defined by <MARK>.
1026                     ;This is expensive, and should not be used in loops.
1027 
1028    (mark-reached <MARK>)
1029                     ;True if the current point is up to or beyond <MARK>
1030                     ;in the buffer.  Intended for use in controlling
1031                     ;character-by character loops, expects that point
1032                     ;starts to the left of <MARK> and moves toward it.
1033                     ;The function (order-mark-last <MARK>) may be used
1034                     ;to switch point and mark if needed at the start of such
1035                     ;loops.  Will not terminate unless executed with mark
1036                     ;and point on same line.
1037 
1038    (mark-at-current-point-p <MARK>)
1039                     ;True if the mark <MARK> represents the exact same
1040                     ;position as the current point.
1041 
1042    (mark-on-current-line-p <MARK>)
1043                     ;True if the mark <MARK> represents a position on the
1044                     ;same line as the current point.
1045 
1046    (mark-same-line-p <MARK1> <MARK2>)
1047                     ;True if two marks which are arguments represent
1048                     ;positions on same line.
1049 
1050    (line-is-blank)  ;True if current line is all blanks or empty.
1051 
1052    (empty-buffer-p <BUFFER-SYMBOL>)
1053                     ;True if the buffer identified by <BUFFER-SYMBOL> is
1054                     ;empty, i.e., contains exactly one line with only a
1055                     ;newline character in it.  The form
1056                     ;(empty-buffer-p current-buffer) may be used to test
1057                     ;the emptiness of the current buffer.  See below
1058                     ;for a discussion of buffer symbols.
1059                         ------------------------------
1060 
1061    Now we use some of this. Here is a function that ltrims all the lines in
1062 the buffer.  There are easier ways, but we are using the primitives and
1063 constructs we do here for illustrative purposes:
1064 
1065 (defun ltrim-all-lines ()
1066        (save-excursion                            ;be polite, restore point.
1067           (go-to-beginning-of-buffer)
1068           (do-forever                             ;loop on lines thru buf
1069            (do-forever                            ;loop thru chars on line
1070             (if (eolp)(stop-doing))               ;stop at eol.
1071             (if (at-white-char)(delete-char)      ;do the work
1072               else (stop-doing)))                 ;non-white char, next line.
1073            (if (lastlinep)(stop-doing))           ;quit when did last line
1074            (next-line))))                         ;leaves you at b.o.l.
1075 
1076 
1077                             W^H_H^H_I^H_T^H_E^H_S^H_P^H_A^H_C^H_E^H_ M^H_A^H_N^H_A^H_G^H_E^H_M^H_E^H_N^H_T^H_
1078 
1079      Management of whitespace is very important. Neatly formatted editor
1080 output and displays, as well as program and document formatting require this.
1081 
1082      The following functions exist to deal with whitespace:
1083 
1084    skip-over-whitespace
1085           Takes no arguments.  Moves point forward over all tabs, blanks, and
1086           newlines until a non-white character or the end of the buffer is
1087           reached to the right of point.
1088 
1089    skip-back-whitespace
1090           Takes no arguments.  Moves point backward over all tabs, newlines,
1091           and blanks until the character to the left of point is not one of
1092           these, or the beginning of the buffer is reached.
1093 
1094    skip-to-whitespace
1095           Moves forward until character to right of point is one of tab,
1096           blank, or newline.  Since last character in buffer must be
1097           a newline, there is no special end condition.
1098 
1099    skip-back-to-whitespace
1100           Moves backward until the character to the right of point is
1101           one of tab, blank, or newline, or the beginning of the buffer is
1102           reached.
1103 
1104    delete-white-sides
1105           The old standby on ESC-\, this extremely valuable function may be
1106           used to advantage to delete leading or trailing blanks from
1107           anything, or delete space between words.
1108 
1109    skip-over-whitespace-in-line
1110           Same as skip-over-whitespace, but will stop before the newline
1111           character at the end of the line (i.e., stop at the end of the line)
1112           if it gets that far.
1113 
1114    skip-back-whitespace-in-line
1115           Same as skip-back-whitespace, but will not proceed backward
1116           beyond the beginning of the line.
1117 
1118      A very common need is to generate whitespace to reach a given horizontal
1119 position (column).  This is good for all kinds of tabbing and page layouts.
1120 The function whitespace-to-hpos performs this service; it generates tabs and
1121 spaces as appropriate, moving point along until the horizontal position which
1122 is its argument is reached.  The following toy function moves all lines in
1123 the buffer seven spaces over, regardless of their original indentation, with
1124 just the right amount of tabs and spaces when all is said and done:
1125 
1126 (defun move-over-7 ()
1127        (save-excursion
1128         (go-to-beginning-of-buffer)               ;all do-for-all-lines
1129         (do-forever                               ;start like this.
1130                 (skip-over-indentation)           ;This is ESC-M, which is
1131                                                   ;often useful. Look it up.
1132                 (let ((hpos (cur-hpos)))          ;let hpos be the curr. pos.
1133                      (delete-white-sides)         ;close up all original space
1134                      (whitespace-to-hpos (+ hpos 7))) ;make just enough
1135                 (if (lastlinep)(stop-doing))
1136                 (next-line))))
1137 
1138      A related need is that to space out to a given position with whitespace,
1139 but leaving a single space if you are already there or beyond.  This is
1140 useful for producing columnar output where overlength fields must be
1141 separated (like what ^X^B does).  whitespace-to-hpos will not do this; it
1142 stops if it is far enough.  This need is fulfilled by format-to-col, which
1143 takes a single argument, a horizontal position to be spaced out to.  If the
1144 current point is already that far, it inserts a space.
1145 
1146                        E^H__^Hx_^Ht_^Hr_^Ha_^Hc_^Ht_^Hi_^Hn_^Hg T^H__^He_^Hx_^Ht F^H__^Hr_^Ho_^Hm _^Ht_^Hh_^He B^H__^Hu_^Hf_^Hf_^He_^Hr
1147 
1148     The function point-mark-to-string is used to get a Lisp string whose
1149 value is the string of characters between point and the mark which is its
1150 argument.  Let us demonstrate with a function that finds a vertical bar  (|)
1151 on a line, deletes it, and swaps the two line-halves around it.  For instance,
1152 the line
1153 
1154           An Indian with a zebra | never trips in the snow
1155 
1156 will come out
1157 
1158           never trips in the snowAn Indian with a zebra
1159 
1160 Here is this extremely utilitarian construction:
1161 
1162 (defun swap-around-bar ()
1163        (go-to-beginning-of-line)
1164        (if (not (forward-search-in-line "|"))     ;check for one at all.
1165            (display-error "Hey, there is no ""|""!"))
1166        (rubout-char)                              ;what # does
1167        (with-mark m                               ;m in middle of line
1168                (go-to-end-of-line)
1169                (let ((temp (point-mark-to-string m))) ;get middle to end
1170                     (without-saving (wipe-point-mark m))
1171                     (go-to-beginning-of-line)
1172                     (insert-string temp))))                 ;put in text
1173 
1174      forward-search-in-line is just like forward-search, except that it
1175 indicates failure if it cannot find its search string in the current line.
1176 If we cannot find the vertical bar, we complain and do command-quit, a "^G",
1177 which stops the execution of this function at once and returns to
1178 command level.  It is often needed, however, to search for some string
1179 only in a given line, and thus, it is useful in its own right.  There is also
1180 a reverse-search-in-line, and a regexp-search-in-line, which are similar in
1181 their relation to ^R and ESC-/.
1182 
1183                              T^H__^Ha_^Hl_^Hk_^Hi_^Hn_^Hg _^Ht_^Ho _^Ht_^Hh_^He U^H__^Hs_^He_^Hr
1184 
1185 
1186      We may not use the Lisp I/O system to print out messages and/or query
1187 the user.  The Multics Emacs redisplay must manage the screen itself,
1188 entirely.  Thus, you may not use "print", or "read", or other Lisp functions
1189 that you may be familiar with.
1190 
1191      A function called minibuffer-print is provided, which prints all the
1192 little messages that Emacs outputs in the minibuffer screen area.  It takes
1193 any number of arguments, which must be strings.  The useful function
1194 decimal-rep is provided to convert numbers into strings for purposes of
1195 inserting them in the buffer or handing them to display-error.  The following
1196 function counts the number of a's in the current line:
1197 
1198 (defun a-counter ()
1199     (let ((n 0))                                  ;initial count
1200          (save-excursion                          ;why not.
1201           (go-to-beginning-of-line)
1202           (do-forever
1203            (if (not (forward-search-in-line "a"))
1204                (minibuffer-print "I found " (decimal-rep n) " a's.")
1205                (stop-doing))
1206            (setq n (+ 1 n)))))          ;count 'em.
1207 
1208      Note how we take advantage of the fact that forward-search-in-line
1209 moves to the right of what it finds (like ^S, its patron), so that it will not
1210 find it the next time.
1211 
1212      To prompt the user for input, which is always done via the minibuffer
1213 (other than for ESC-?, which is highly special), the function
1214 minibuf-response is used. It takes two arguments.  The first is the prompting
1215 string.  The second should be specified by the value of one of the global
1216 variables ESC or NL, which are bound to magic symbols that minibuf-response
1217 knows about.  If the value of ESC is used, minibuffer input will terminate
1218 on an ESC.  If the value of NL is used, (NL, _^Hn_^Ho_^Ht CR), minibuffer input will
1219 terminate on a carriage return.  There are no other choices. Thus,
1220 
1221       (minibuf-response "Type new division name: " NL)
1222 
1223 will return the user's response to this question.  S/he is expected to
1224 terminate it with a carriage return.  The value of minibuf-response is a Lisp
1225 string.  The carriage return will not appear in it, nor will the prompt.
1226 
1227      Often one wants to display an error message in the minibuffer, and then
1228 abort execution of an extension, i.e., execute a command-quit (^G).  For
1229 example, in checking the arguments to an extended command, checking that a
1230 necessary sequence of previous commands were issued before a certain command,
1231 etc.  For this, display-error is provided.  display-error is like
1232 minibuffer-print, except that it does NOT return, but aborts to emacs top
1233 level immediately after printing its error message in the minibuffer.  Like
1234 minibuffer-print, it takes any number of string arguments.
1235 
1236      Messages printed by minibuffer-print are suppressed during keyboard macro
1237 ( ^X(, ^X)) execution, just as search strings are not displayed, and other
1238 gratuitous messages are suppressed.   The following set of functions describes
1239 the repertoire of message-printing:
1240 
1241 
1242      display-error
1243           Prints a message in the minibuffer and aborts to editor top
1244           level.  It is intended for use in error message pritning.
1245 
1246      display-error-noabort
1247           Prints a message in the minibufer and continues execution.  This
1248           function is intended for reporting non-fatal errors such
1249           as "User not accepting messages...".
1250 
1251 
1252      minibuffer-print
1253           Prints a message in the minibuffer.  The message is NOT printed
1254           during macro execution.  This function is intended for
1255           use by extensions which print messages in the normal process
1256           of their execution such as the line-count from ^X=.  For
1257           this function, as well as the others below, in multi-line
1258           minibuffer situations, an appropriate line is chosen based
1259           upon availability of empty lines and several other criteria.
1260 
1261      minibuffer-print-noclear
1262           Prints a message in the minibuffer but does not erase the
1263           previous contents.  The message is NOT printed during macro
1264           execution.  Output is appended to the last minibuffer line used.
1265 
1266      display-com-error
1267           Prints a message in the minibuffer and aborts to editor top
1268           level.  Its first argument is a Multics standard error code.
1269           It remaining arguments are character strings or symbols.
1270           See the section "Multics Error Table" below for the technique
1271           used to get error_table_ values into your program.
1272 
1273      display-com-error-noabort
1274           Prints a message in the minibuffer and continues execution.
1275           Its first argument is a Multics standard error code.
1276 
1277      minibuffer-clear
1278           Clears out the last minibuffer line that was written in, except
1279           during macro execution.  This function should be used to clear
1280           out minibuffers written in by minibuffer-print and
1281           minibuffer-print-noclear at the end of subsystem invocation.
1282 
1283      display-error-remark
1284           Identical to display-error-noabort, except that the particular
1285           minibuffer line on which this remark will be printed will be
1286           "targeted" to be the next ine overwritten for any minibuffer
1287           remark or output at all.  This function should be used for
1288           "transient" remarks (such as "Writing", "Modified", etc., which
1289           are desired to get off the screen as soon as possible.
1290 
1291                                   V^H__^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He_^Hs
1292 
1293      Many groups of Emacs commands need global variables to communicate
1294 amongst themselves and the functions they call.  A global variable is a Lisp
1295 variable which is not the parameter of any particular function; its value may
1296 be accessed or set by any function.  Some of the global variables in Multics
1297 Emacs are highly user-visible, for example, "fill-column", which contains the
1298 column number of the fill column as set by ^XF, and used by the filling
1299 commands and fill mode.   Similarly, the character string which is the
1300 comment prefix is the binding of the global variable "comment-prefix".
1301 Extensions will often need global variables to communicate among their parts.
1302 
1303      Normally, global variables in Lisp are accessed just line other
1304 variables, i.e., those which are parameters of functions or _^Hp_^Hr_^Ho_^Hg or _^Hl_^He_^Ht
1305 variables (_^Hl_^He_^Ht will be discussed later.).  For instance, a function which
1306 wanted to set the fill column to 30. if it was over 40. now might contain
1307 the code:
1308 
1309           (if (> fill-column 40.)(setq fill-column 30.))
1310 
1311      When a global variable is used in your program, say one named
1312 "my-global", the "declaration"
1313 
1314           (declare (special my-global))
1315 
1316 must appear in the program before its first use, to tell the compiler about
1317 this "special" variable (which is the Lisp term for a global variable,
1318 incidentally).  The e-macros include file declares many of the provided
1319 global variables, you need not declare them.
1320 
1321      The global variable situation in Multics Emacs is complicated by the
1322 fact that editing activity is usually local to each buffer.
1323 That is to say, if a set of global variables contains a set of values about
1324 what is being edited, it usually pertains to what is going on in only one
1325 editor buffer. If the user switches to a different buffer, and uses the same
1326 editor facility, we do not want to use or change the values of those global
1327 variables which pertained to activity in the other buffer.  At first, this
1328 would seem to make global variables unusable, because all functions would
1329 have to keep track of what buffer they are talking about before using any
1330 global variables, and maintaining several sets of them thereby.
1331 Fortunately, it is a lot easier than that.  The buffer-switcher in Multics
1332 Emacs is willing to save and restore values of global variables as buffers
1333 are switched if you tell it what variables you want so saved and restored, when
1334 the buffer you are operating in is exited and re-entered, respectively.  Such
1335 a variable is called a _^Hp_^He_^Hr-_^Hb_^Hu_^Hf_^Hf_^He_^Hr _^Hv_^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He, and the act of telling the
1336 buffer-switcher about it, thereby associating its current value with this
1337 buffer, is called _^Hr_^He_^Hg_^Hi_^Hs_^Ht_^He_^Hr_^Hi_^Hn_^Hg it.  Once a variable has been registered in a
1338 given buffer, the functions which use it can assume that its value will be
1339 what it last was in that buffer whenever the editor enters that buffer.
1340 Another term for a per-buffer variable is a _^Hl_^Ho_^Hc_^Ha_^Hl _^Hv_^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He.
1341 The following two primitives exist for registering local variables; there are
1342 no primitives for setting or retrieving their values, because the whole point
1343 of this mechanism is to allow them to be accessed as normal Lisp variables.
1344 
1345      register-local-variable
1346           Called with one argument, the symbol whose name is the name of the
1347           local variable we wish to register.  Registers it in the current
1348           buffer, if not already registered here.  If not already registered
1349           here, the variable initially inherits its "global value";  if
1350           registered, its value is left alone.  If it has no global value,
1351           it acquires the symbol "nil" as its value if this is its first
1352           registration in this buffer.
1353 
1354      establish-local-var
1355           Just like register-local-variable, but takes a second argument,
1356           a default value to be initially assigned to the variable the first
1357           time it is registered in this buffer, if it has no global value.
1358 
1359      The global value of a per-buffer-variable is the value it has in buffers
1360 in which it is not registered.  It is this value which is set if you set this
1361 variable while in a buffer in which it is not registered.  A local variable
1362 "inherits" its global value when it is first registered in a given buffer.
1363 For variables that have no global value (i.e., were never assigned one),
1364 establish-local-var can be used to good effect to provide default
1365 initialization.
1366 
1367      Here are three function which maintain a "problem count" in this buffer.
1368 The user says ESC-Xmonitor-problemsCR to start it up in a given buffer,
1369 and then can say ^X-P to count a problem, and ^X-R to report how many
1370 "problems" he has so noted:
1371 
1372 (defun monitor-problems ()                        ;command-level function
1373        (set-key '^XP 'note-a-problem)             ;set the keys needed, only
1374        (set-key '^XR 'report-problems)            ;in this buffer
1375        (establish-local-var 'problem-count 0))    ;register the local var,
1376                                                   ;initial value 0 here.
1377 
1378 (defun note-a-problem ()                          ;executed on ^XP
1379       (setq problem-count (+ 1 problem-count)))   ;Increment the variable.
1380 
1381 (defun report-problems ()                         ;on ^XR
1382        (minibuffer-print "There have been " (decimal-rep problem-count)
1383                          " problems in this buffer."))
1384 
1385      By calling establish-local-var on the symbol "problem-count", the
1386 programmer here has ensured that the problem-count's in each buffer
1387 in which he counts problems will be maintained separately.
1388 
1389                               P^H__^Hr_^Ho_^Hv_^Hi_^Hd_^He_^Hd V^H__^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He_^Hs
1390 
1391      The following per-buffer variables are automatically registered by the
1392 editor.  Their values may be inspected or set in extension code.  The following
1393 table gives their names and meanings:
1394 
1395 buffer-modified-flag
1396      Contains t or nil, indicating that this buffer has or has not been
1397      modified since last read in or written.  Set automatically by the
1398      editor.  Modification of a buffer executed within the special form
1399 
1400           (without-modifying <form1><form2>...<formn>)
1401 
1402      will not set this flag.
1403 
1404 read-only-flag
1405      Contains t or nil indicating whether or not this is read-only buffer.
1406      The editor does not set this flag, it is set only by extensions.
1407      An attempt to modify the text in this buffer will produce an error
1408      and a quit to editor command level if this flag is on, and the
1409      buffer-modified-flag flag is off (nil).  The buffer may be modified,
1410      however, successfully, by functions executed from within extension code
1411      within a "(without-modifying ...)".
1412 
1413 fpathname
1414      The full Multics pathname associated with this buffer by the last file
1415      read or written into/out of it, or by find-file. It is nil if there is
1416      none.  Changing it from extension code will modify or "forget" the
1417      pathname as you set it.
1418 
1419 der-wahrer-mark   (name subject to change, use macros instead)
1420      The mark associated with the user-visible mark that ^X^X etc. see.
1421      Will be nil if no mark ever set by the user in this buffer.  Do not set
1422      this variable, call set-the-mark (the ^@ function) to do so.
1423 
1424 current-buffer-mode
1425      The major mode in effect in this buffer.  The value is a symbol.  To
1426      claim that a major mode of your construction is in effect in a buffer,
1427      simply set this variable.
1428 
1429 comment-column
1430      The comment column, as always, measured from 0.
1431 
1432 comment-prefix
1433      The string, which may be a null string, which is the comment prefix.
1434 
1435 tab-equivalent
1436      The amount of spaces that a tab is worth.  Initialized to 10., the Multics
1437      standard, this can be set either in code or by ESC-ESC to edit code
1438      from other operating systems.  The redisplay will obey this variable too,
1439      but not in two-window mode.
1440 
1441 buffer-minor-modes
1442      A Lisp list (to be explained) of symbols representing the minor modes
1443      in effect in this buffer.
1444 
1445                               L^H__^Ha_^Hr_^Hg_^He S^H__^Hc_^Ha_^Hl_^He O^H__^Hu_^Ht_^Hp_^Hu_^Ht
1446 
1447     Output of multi-line information, or information longer than about 60
1448 characters, should not be done via display-error, which prints in the
1449 minibuffer area, but via the _^Hl_^Ho_^Hc_^Ha_^Hl-_^Hd_^Hi_^Hs_^Hp_^Hl_^Ha_^Hy, or _^Hp_^Hr_^Hi_^Hn_^Ht_^Ho_^Hu_^Ht facility. This is the
1450 facility with which buffer listings, global searches, apropos, and other
1451 familiar commands display their output.  On display terminals, it displays
1452 lines at the top of the screen, asking for "MORE?" as each screen fills up,
1453 and pausing for the next Emacs command at the end of the display, and
1454 restoring the screen.  On printing terminals, the data is simply printed
1455 line by line, with no "MORE?" processing or pausing at the end.
1456 The local display facility is an integral part of the Multics Emacs
1457 redisplay.
1458 
1459      There are three common functions used in generating local displays:
1460 
1461 init-local-displays
1462      is called with no arguments to start a local display.  It basically
1463      sets up the necessary redisplay mechanism, initializing it to the top
1464      of the screen.
1465 
1466 local-display-generator
1467      This function is called with a string, whose last character must be a
1468      newline, and displays it as the next line (or lines, if continuation lines
1469      are required) of local output.  If you do not have a newline at the end
1470      of your string, calling local-display-generator-nnl instead will provide
1471      one automatically.  There must be no embedded newlines in strings for
1472      local output.  A null string causes an empty line.
1473 
1474 end-local-displays
1475      Finishes a local display, restoring the screen.  Causes
1476      the next redisplay to be suppressed, so the local display remains visible
1477      on the screen.
1478 
1479      The sequence of calls
1480 
1481           (init-local-displays)
1482           (local-display-generator(-nnl) ...)    ;perhaps many times
1483           (end-local-displays)
1484 
1485      correctly produces a local display.
1486 
1487      Often, the best way to generate a well-formatted local display is to set
1488 up a temporary buffer (see "Manipulating Buffers" below), build some text in
1489 it, and display its content, in part or in whole, as a local display.  Three
1490 functions are provided to facilitate this:
1491 
1492 local-display-current-line
1493      Does a local-display-generator on the current editor line in this buffer.
1494 
1495 display-buffer-as-printout
1496      Does an init-local-displays, and displays all lines of the current
1497      buffer as local output.  It does NOT do an end-local-displays; you have to
1498      do that yourself, hopefully _^Ha_^Hf_^Ht_^He_^Hr you have gotten out of your
1499      temporary buffer and cleaned up whatever else you had to.
1500 
1501 view-region-as-lines
1502      Displays the entire point-to-user-visible-mark as local display,
1503      making all the necessary calls including end-local-displays.
1504 
1505      While in a function which has a local display in progress, you must never
1506 call the redisplay (see "Calling the Redisplay" below), or call
1507 minibuf-response or any other function which will cause redisplay, for that
1508 will instantaneously restore the screen contents to the windows on display,
1509 obliterating the local display in progress.
1510 
1511      The following function locally displays all lines in the buffer
1512 that contain the string "defun":
1513 
1514 (defun look-for-defuns ()                         ;use ESC-x look-for-defunsCR
1515        (save-excursion                            ;remember where we are.
1516           (go-to-beginning-of-buffer)
1517           (init-local-displays)                   ;set up for printout.
1518           (do-forever                             ;loop the buffer
1519             (if (forward-search-in-line "defun")  ;look for "defun"
1520                 (local-display-current-line))     ;cause printout of it
1521             (if (lastlinep)(stop-doing))          ;check for EOB.
1522             (next-line)))                         ;Go to start of next line.
1523        (end-local-displays))                      ;wait for user, and next
1524                                                   ;command.
1525 
1526                              M^H__^Ha_^Hn_^Hi_^Hp_^Hu_^Hl_^Ha_^Ht_^Hi_^Hn_^Hg B^H__^Hu_^Hf_^Hf_^He_^Hr_^Hs
1527 
1528      The easiest way to do string processing in the editor environment, i.e.,
1529 monkeying around with strings, catenating, searching, etc., is often to use
1530 the primitives of the editor itself, which is, after all, a string-processing
1531 language.  To do this, temporary buffers are necessary.  To create a buffer,
1532 you should use the primitive "go-to-or-create-buffer", which is what
1533 ^XB uses, which goes to a buffer associated with the symbol you give it
1534 as an argument.  We will discuss how to make it temporary shortly.
1535 
1536      Lisp symbols are funny things;  it was stated before that symbols are
1537 kept in a registry.  This is true for most symbols: this registry is called
1538 the _^Ho_^Hb_^Ha_^Hr_^Hr_^Ha_^Hy, and there is only one symbol of any given name in it.
1539 A symbol registered in the obarray is said to be _^Hi_^Hn_^Ht_^He_^Hr_^Hn_^He_^Hd.  There can
1540 only be one interned symbol named "joe", but it is possible to create
1541 many uninterned symbols named "joe".  If you refer to a symbol named "joe"
1542 in a program, however, by saying "'joe", you will always be getting the
1543 interned one.
1544 
1545      A major feature of symbols in Lisp is that they can be given _^Hp_^Hr_^Ho_^Hp_^He_^Hr_^Ht_^Hi_^He_^Hs,
1546 arbitrary user-defined attributes.  These attributes are catalogued "in" the
1547 symbol via _^Hi_^Hn_^Hd_^Hi_^Hc_^Ha_^Ht_^Ho_^Hr_^Hs, symbols which indicate what property we want.
1548 The Lisp functions "putprop" and "get" store and retrieve properties.
1549 
1550           (putprop 'Fred 'blue 'eyes)   ;Gives the interned symbol named "Fred"
1551                                         ;an "eyes" property of "blue".
1552 
1553           (get 'Fred 'eyes)             ;retrieves the property under the
1554                                         ;indicator "eyes", and thus returns
1555                                         ;the interned symbol "blue".
1556 
1557      In Multics Emacs, symbols are used (among other things) to represent
1558 buffers.  All of the information associated with a buffer is catalogued as
1559 properties of some symbol whose name is the name of the buffer.
1560 Thus, it is possible to have two buffers of the same name, which would imply
1561 that the of the symbols representing them, only one is interned. ^XB
1562 always uses the interned symbol of the name given; that is why you can ^XB back
1563 to an existent buffer instead of creating a new one each time.
1564 
1565      To create a temporary buffer, we must first create an uninterned symbol,
1566 to make sure that we are not going to switch to a buffer that is already real.
1567 To do this, we give a string to be used in naming the symbol to the
1568 Lisp cliche
1569 
1570           (maknam (explodec  "A string"))
1571 
1572 The explodec blows the string apart into a Lisp list of characters, the
1573 maknam builds a symbol out of it.  The value of this form is the new symbol.
1574 We can then go to a (guaranteed) new buffer of that name, i.e.,
1575 
1576           (go-to-or-create-buffer (maknam (explodec "A string")))
1577 
1578 and the global variable "current-buffer" will have that symbol as its value.
1579 A _^Ht_^He_^Hm_^Hp_^Ho_^Hr_^Ha_^Hr_^Hy _^Hb_^Hu_^Hf_^Hf_^He_^Hr is one that is destroyed automatically by the editor upon
1580 switching out of it.  To  make a buffer temporary, all we have to do is give
1581 the symbol which represents it (the "buffer symbol") a "temporary-buffer"
1582 property of the symbol "t".  This can be done by the Lisp form
1583 
1584           (putprop current-buffer t 'temporary-buffer)
1585 
1586 (The variable "t" is always bound to the symbol "t").  Once this has been
1587 done, we must be careful not to switch out of this buffer until we are done
1588 with it.  If our code involves manipulating many buffers, some of them
1589 temporary, we must give the temporary buffers their temporary-buffer
1590 properties at the end of our manipulations.
1591 
1592      When a new buffer is created, it contains one line, which consists of
1593 only a linefeed.  There are no "truly empty" buffers in Multics Emacs.
1594 The predicate empty-buffer-p may be applied to a buffer symbol to
1595 determine if that buffer is in this state.
1596 When buffers are switched, all information related to the old buffer is stored
1597 as properties of the buffer symbol: this includes not only the local
1598 variables registered in that buffer, but the location of "point", the
1599 user-visible (and all other) marks, etc.  Thus, when buffers are switched
1600 back and forth (as can be seen while editing), the cursor retains its
1601 position in each buffer, although the redisplay might choose to display a
1602 screen differently after visiting another buffer and coming back.
1603 
1604      There are some applications which require making a non-temporary
1605 buffer, putting some text in it, and going back there on occasion.  For this
1606 reason, we might want to go into a non-temporary buffer of an interned buffer
1607 symbol, as such:
1608 
1609           (go-to-or-create-buffer 'name-and-address-buffer)
1610 
1611 or perhaps keep a global (_^Hn_^Ho_^Ht per-buffer) variable which we set once to an
1612 uninterned symbol as such:
1613 
1614           (setq name-and-address-keep-track
1615                       (maknam (explodec "Name and Address Buffer")))
1616 
1617 and switch into it by saying
1618 
1619           (go-to-or-create-buffer name-and-address-keep-track)
1620 
1621 
1622      The function "buffer-kill" may be called with a buffer symbol to destroy
1623 a buffer.  The function "destroy-contents-of-buffer" (no arguments) may be
1624 called to reduce the current buffer to a single "empty" line.
1625 
1626      The following two variables are relevant to buffer manipulation:
1627 
1628 current-buffer
1629      The value of this variable is the buffer symbol of the current buffer.
1630      Do not change it, or incorrect operation will result.  Use
1631      go-to-or-create-buffer.
1632 
1633 previous-buffer
1634      The value of this variable is the buffer symbol of the last buffer,
1635      which will be returned to when ^XB-CR is typed.  It is acceptable to setq
1636      this variable.
1637 
1638 
1639      go-to-or-create-buffer will accept a buffer-name of "" as meaning
1640 go to that previous buffer.
1641 
1642      The special form save-excursion-buffer is invaluable when writing
1643 functions that switch buffers.  It provides for remembering which buffer you
1644 were in, and switching back to it when you are done.  It also saves and
1645 restores the state of "previous-buffer".  save-excursion-buffer is like
1646 save-excursion, it executes its contained forms while pushing the
1647 buffer-state of the editor  on an internal stack, and returns the value of
1648 the last form within it.
1649 
1650      The following program when invoked after typing somebody's name (say we
1651 hook it up to a key) and follows it with his title in parentheses.  We assume
1652 the file >udd>Washington>States>personnel_data looks like this:
1653 
1654 Rasputin, G. E. =Chief Lecher
1655 Nietzsche, F. =Antichrist
1656 Mouse, M. =Optimist
1657 Eisenhower, D. D. =Golfer
1658 
1659 (defun insert-person-title ()
1660        (let ((name (save-excursion                          ;save guy's point
1661                     (skip-back-whitespace)                  ;get to end of word
1662                     (with-mark m                            ;m = end of word
1663                        (backward-word)                      ;go to beg. of wd.
1664                        (catenate (point-mark-to-string m) ",")))))
1665                                         ;return the word with a "," after it.
1666             (insert-string                                  ;insert
1667              (catenate " ("                                 ;open paren and sp
1668                (save-excursion-buffer                       ;save the old buff
1669                 (go-to-or-create-buffer 'name-position-records)
1670                                                             ;go to stuff
1671                 (if (empty-buffer-p current-buffer)         ;read it once
1672                     (read-in-file ">udd>Washington>States>personnel_data"))
1673                 (go-to-beginning-of-buffer)                 ;set up for search
1674                 (do-forever                                 ;scan lines
1675                  (if (looking-at name)                      ;Are we at "name,"?
1676                      (forward-search "=")                   ;look for the =.
1677                      (return (with-mark n                   ;get to the end.
1678                                 (go-to-end-of-line)
1679                                 (point-mark-to-string n))))
1680                  (if (lastlinep)(return "???"))             ;couldn't find him
1681                  (next-line))                               ;move on
1682                 ") ")))))
1683 
1684      This function operates by picking out the name you just typed by skipping
1685 back over whitespace, and picking up all between there and the start of the
1686 previous (current) word.  It then inserts, between parentheses, the portion of
1687 that line of the data file which contains the sought name at its front after
1688 the equals sign.  The buffer name-position-records is read into once, and
1689 contains the data file thereafter.
1690 
1691      The initial save-excursion remembers the user's point location while the
1692 word is collected:  The save-excursion-buffer remembers what buffer and where
1693 in it, all its modes, local variables, etc., while we operate in the data
1694 file buffer.
1695 
1696      The function _^Hc_^Ha_^Ht_^He_^Hn_^Ha_^Ht_^He is an extremely valuable one in the context of
1697 Multics Emacs; it takes any number of strings (or symbols, whose print-name
1698 will be used), builds a string out of catenating them first-to-last, and
1699 returns it.
1700 
1701 
1702                             C^H__^Ha_^Hl_^Hl_^Hi_^Hn_^Hg _^Ht_^Hh_^He R^H_e^H__^Hd_^Hi_^Hs_^Hp_^Hl_^Ha_^Hy
1703 
1704      The Multics Emacs redisplay is a large and powerful screen-management
1705 system which functions completely automatically.  Its function, in simple
1706 terms, is to decide what lines of the current buffer should be shown on the
1707 screen, determine how to modify the current screen to show the contents of
1708 those lines, and update the screen in an optimal manner.  It is called
1709 by the editor whenever there is no more input available.  It is very simple
1710 to call.  It takes no arguments, i.e., one just says
1711 
1712           (redisplay)
1713 
1714      The redisplay does not know or care by what means the buffer was
1715 modified;  if you delete several words with ESC-D, ^D, or ^W, it is all the
1716 same to the redisplay, and it will act similarly in updating the screen.
1717 
1718      Normally, the extension writer need not be concerned at all about the
1719 redisplay.  It is a major feature of Multics Emacs that only the total effect
1720 of a complex manipulation is displayed, not every small operation that the
1721 manipulation used to achieve its effect.
1722 
1723      There are some situations, however, where it is advantageous to call the
1724 redisplay explicitly from extension code.  One example might be a function
1725 which takes a tremendous amount of compute time and might wish to update the
1726 screen every-so-often as it finishes some major section.  Note that you do not
1727 tell the redisplay what do display or how to display it; it will display some
1728 excerpt of the current buffer which is guaranteed to contain the current line,
1729 and show the cursor where the current point is.  If you call it during a
1730 buffer excursion, i.e., while in some special buffer in a function, it will
1731 thus display that buffer about its "point", and as soon as that function
1732 returns to editor command level, the screen will be overwritten with the
1733 original buffer's lines.  Thus, calling redisplay is _^Hn_^Ho_^Ht to be considered a
1734 substitute for local displays (see above).
1735 
1736      The most common need for calling redisplay is in functions that add
1737 text (or change text) on a line, and move to another line.  For example, the
1738 "electric semicolon" of electric PL/I mode, which adds a semicolon to the
1739 current line and moves to the next.  On a printing terminal, the user would
1740 never see the semicolon unless special action were taken.  The text in the
1741 buffer would indeed be right, but by time the next redisplay occurred (the
1742 electric semicolon command returned) the editor would be off that line, and
1743 thus would display the next line, where the electric semicolon command left
1744 it.  While this is correct, the user looking at his type-in would, with some
1745 validity, complain that "all the semicolons seem to be missing".  Thus, the
1746 electric PL/I semicolon command calls the redisplay immediately after it
1747 executes "(insert-string ";")".
1748 
1749      The following divertissement is a function for a "card-numbering FORTRAN
1750 mode", which when invoked (perhaps hook it up to CR) puts a sequence number
1751 in column 72 (71 from 0) and goes to column 7 of the next line.
1752 
1753      It must call the redisplay, such that on a printing terminal, the card
1754 numbers get shown.
1755 
1756 (defun fortran-next-line ()
1757        (whitespace-to-hpos 71.)                   ;go to col 72.
1758        (insert-string (decimal-rep cardno))       ;cardno is a local buffer var
1759        (setq cardno (+ 1 cardno))                 ;up the next card number
1760        (redisplay)                                ;let printing user see.
1761        (new-line)                                 ;get to next line
1762        (whitespace-to-hpos 6.))                   ;6 rel = card col 7.
1763 
1764 
1765                                   E^H_I^H_S^H_ T^H__^Ha_^Hb_^Hl_^He_^Hs
1766 
1767 
1768      The Multics Emacs environment provides a powerful facility for utilizing
1769 the sophisticated 68/80 processor instructions for scanning for characters in
1770 or not in a particular set of characters.  These operations correspond to the
1771 PL/I "search" and "verify" builtins.  It is using these facilities that the
1772 word commands operate.
1773 
1774      A set of characters is represented by a "charscan table", a compound
1775 Lisp object occupying about 200 words of storage (i.e., they are not for
1776 free).   One can get a charscan table by giving a set of characters, as a
1777 string, to the function charscan-table.  It returns a charscan table
1778 representing that set of characters:
1779 
1780           (setq number-verify-table (charscan-table "0123456789+-"))
1781 
1782      Given such a table, there are  a set of functions which can be called to
1783 utilize it to search for characters in or out of that set, backward, forward,
1784 whole buffer or only one line.  All the following functions take one argument,
1785 a charscan table representing a set of characters we will call S.  They
1786 return nil (falsity) if they hit the end of the buffer or line (as
1787 appropriate) without finding what they are looking for.  If they succeed, they
1788 move point.  If they fail, they don't move point:
1789 
1790 search-for-first-charset-line
1791      Scans current line forward from point.  Success is stopping to the
1792      left of a character in S.
1793 
1794 search-for-first-not-charset-line
1795      Same as above, but success is stopping to the left of a character _^Hn_^Ho_^Ht
1796      in S.
1797 
1798 search-back-first-charset-line
1799      Scans current line backward from point.  Success is stopping to the right
1800      of a character in S.
1801 
1802 search-back-first-not-charset-line
1803      Same as search-back-first-charset-line, but success is stopping to the
1804      right of  a character _^Hn_^Ho_^Ht in S.
1805 
1806 search-charset-forward
1807      Scans the buffer from point to the end of the buffer.  Success is
1808      stopping to the left of a character in S.
1809 
1810 search-charset-backward
1811      Scans the buffer backward from point to the beginning of the buffer.
1812      Success is stopping to the right of a character in S.
1813 
1814 search-not-charset-forward
1815      Scans the buffer forward from point to the end.  Success is stopping
1816      to the left of a character not in S.
1817 
1818 search-not-charset-backward
1819      Scans the buffer backward from point to the beginning of the buffer.
1820      Success is stopping to the right of a character not in S.
1821 
1822 
1823 
1824      The following function finds the first non-numeric character on the line
1825 it is invoked on:
1826 
1827 (defun find-first-non-numeric ()
1828        (establish-local-var numscan-table nil)    ;make sure var exists
1829        (if (not numscan-table)                    ;if nil, i.e., not init yet,
1830            (setq numscan-table (charscan-table "0123456789")))
1831        (go-to-beginning-of-line)
1832        (if (not (search-for-first-not-charset-line numscan-table))
1833            (minibuffer-print "Line is O.K.!")))   ;failure is all is in charset
1834 
1835 
1836                                    O^H__^Hp_^Ht_^Hi_^Ho_^Hn_^Hs
1837 
1838      The Multics Emacs option mechanism provides for user-settable variables
1839 in the Lisp environment.  The only difference between an "option" and any
1840 other global Lisp variable in the editor (basic or extended) is that the
1841 options are listed at the user-visible level by ESC-Xopt listCR, and can be
1842 set or interrogated via the "opt" command.  The option mechanism also
1843 provides for checking that numeric variables stay numeric, and those variables
1844 that are restricted to "t" or "nil" as values stay restricted to those values.
1845 
1846      Thus, options may control per-buffer or truly global variables; the
1847 option mechanism does not care about or impose restraints upon the dynamic
1848 scope of the variables managed by it.  The option mechanism also provides for
1849 a default global value of variables it manages.
1850 
1851      A global variable is "registered" with the option mechanism by invoking
1852 the function "register-option" upon the Lisp symbol which represents (has the
1853 name of) that variable, and its default global value.  If that value is a
1854 number, the option mechanism will restrict the variable's value to numbers;
1855 if it is one of t or nil, the option mechanism  will restrict its values to t
1856 or nil (which the user indicates as "on" or "off").
1857 
1858      The choice of whether a variable should be made an official "option" or
1859 not depends upon whether or not you want the user to see it when an "opt
1860 list" is done, and whether finer control than that provided by the option
1861 mechanism over the values assigned to it is necessary.  It is acceptable to
1862 register an option the first time some code is executed; only then will it
1863 appear in the option list.  It is usual to have forms invoking
1864 "register-option" at "top-level" in a file full of code, i.e., outside of any
1865 function.  Such code is executed when the code is brought into the editor
1866 environment.
1867 
1868      The following code registers an option describing default paragraph
1869 indentation, and shows a function that creates a new paragraph (which should
1870 probably be hooked up to a key).  Note that like all Lisp global variables,
1871 options must be declared "special" for the Lisp  compiler (see "compilation"
1872 below):
1873 
1874 (declare (special paragraph-indentation))                   ;for compiler.
1875 
1876 (register-option 'paragraph-indentation 10.)                ;default is ten.
1877 
1878 (defun new-paragraph ()
1879        (new-line)                                           ;two new-lines
1880        (new-line)
1881        (whitespace-to-hpos paragraph-indentation))          ;tab out.
1882 
1883      By issuing the command
1884 
1885      ESC-X opt paragraph-indentation 5 CR
1886 
1887 the user can set the amount of indentation inserted by "new-paragraph" to 5.
1888 
1889 
1890 
1891                               N^H__^Ha_^Hm_^He S^H__^Hc_^Ho_^Hp_^He I^H__^Hs_^Hs_^Hu_^He_^Hs
1892 
1893       One of the large benefits of Lisp is that all of the functions and
1894 variables in the environment are accessible to all functions running in it.
1895 At times, this can be a problem, as well.   When adding your own extensions
1896 to the editor environment, there is nothing to prevent you from choosing a
1897 name for one of your functions which happens to be the name of some internal
1898 (or user-visible) function in Multics Emacs.  Occasionally, there may be reason
1899 to do this deliberately , e.g., write your own version of "next-line" that
1900 did something highly special.  This is dangerous, and not recommended.
1901 
1902      In the general case, you want to make sure that none of your functions
1903 or variables will conflict with those of the editor.  The best way to do this
1904 is to choose some set of names that cannot possibly conflict.  Two sure-fire
1905 ways to achieve this are to use capital letters anywhere (such as initial
1906 capitals) or using underscores in your names.  No  Emacs or Lisp system
1907 functions have leading capitals or trailing underscores.  There are a few
1908 Lisp system functions with embedded underscores, but other than make_atom, it
1909 will not hurt you if you accidentally redefine them.  The Lisp compiler will
1910 also warn you if you attempt to redefine a system function.  No functions in
1911 Multics Emacs contain underscores in their names.
1912 
1913      Another more reasonable way to avoid name scope conflicts is to prefix all
1914 of your names in a given package with some prefix indicative of the facility
1915 that you are trying to implement.  For instance, if you are implementing a
1916 SNOBOL edit mode, you might name your functions
1917 "snobol-mode-find-match-string", "snobol-mode-get-branch-target", etc.  The
1918 same holds true for global variable names.
1919 
1920      You can also be reasonably certain that names constructed on the fly
1921 (see "Program Development" below) with some degree of ludicrosity in their
1922 names (e.g., "find-third-foo", "Johns-special-tsplp-hack", etc.) will not
1923 conflict.
1924 
1925      One can test for a name being known in the Emacs environment via the
1926 predicate "internedp" (not installed as of 8/16), which tests whether or not
1927 a symbol with the given name is interned on the obarray.  You must give it a
1928 string.  It will return t or nil for interned or not.  From Emacs command
1929 level,
1930 
1931           ESC-ESC internedp "test-string"CR
1932 
1933 will print out
1934 
1935           Value: t
1936 
1937 or
1938 
1939           Value: nil
1940 
1941 as appropriate.  This test is not a foolproof method, though, because some
1942 name which is not used now may be used later, as new versions of Multics
1943 Emacs are developed.  The rules given above will remain valid for all time.
1944 
1945 
1946                                     M^H__^Ho_^Hd_^He_^Hs
1947 
1948      The major and minor mode mechanism of Multics Emacs, as it exists today,
1949 is little more than a way for the user to switch in and out large sets of
1950 key-bindings and column settings, and know about it via the mode line.
1951 
1952      The differentiation between major modes and minor modes is vague.  The
1953 current convention holds that a major mode involves a large body of optional
1954 code (e.g., PL/I mode), sets up for a editing code written in a particular
1955 language, or sets up a buffer for some highly specialized task where very
1956 common keys (e.g., CR) do non-obvious things (e.g., the Message mode buffers
1957 of the Emacs message facility).  Minor modes generally involve the say that
1958 whitespace or delimiters are interpreted, e.g., fill mode and speedtype mode.
1959 
1960      The current convention on major modes is that the major mode is set up by
1961 a user-visible function called "XXX-mode", where XXX is the name of the mode.
1962 This "mode function"  establishes key-bindings (using set-key) as necessary,
1963 and sets columns (e.g., fill-column, comment-column) and prefixes as
1964 necessary.   The mode function establishes the mode by setting the
1965 per-buffer-variable "current-buffer-mode" to a _^Hs_^Hy_^Hm_^Hb_^Ho_^Hl whose name is
1966 indicative of the mode.  The name of the symbol will appear in the mode line
1967 when the redisplay is invoked while in this buffer.  The following function
1968 sets up a major mode for editing FORTRAN programs:
1969 
1970 (defun fortran-mode ()                                      ;the mode function
1971        (setq current-buffer-mode 'FORTRAN)                  ;symbol for mode
1972        (setq fill-column 70.)                               ;set columns
1973        (setq fill-prefix "      ")                          ;six spaces on CR
1974        (set-key 'CR 'fortran-new-line)                      ;set up CR key
1975        (setq comment-column 1)
1976        (setq comment-prefix "C "))                          ;that begins cmts.
1977 
1978 The function fortran-new-line is assumed to be one which does something
1979 appropriate, such as numbering cards.  Note that the use of the function
1980 set-key implies that this key binding (of the carriage-return key) is
1981 local to this buffer, and will be reverted when this buffer is exited.
1982 
1983      Minor modes are less straightforward.  Minor modes such as speedtype
1984 and fill mode have different actions associated with the keys they affect
1985 (for instance, all the "punctuation" keys), and the minor modes have to have
1986 detailed and specialized interaction between themselves.  There is no way to
1987 generalize the interactions between the minor modes; no completely adequate
1988 solution to this problem has been developed.
1989 
1990      Minor modes are asserted and turned off in a given buffer by calling the
1991 functions "assert-minor-mode" and "negate-minor-mode" while in that buffer,
1992 with an interned symbol which identifies that mode (and appears in the mode
1993 line).  There is a per-buffer variable called buffer-minor-modes which has a
1994 value a Lisp list of all the symbols identifying the   minor modes in effect
1995 in this buffer.  The Lisp predicate "memq" can be used to test whether a given
1996 interned symbol is a member of a list, and thus, whether a given minor mode
1997 is in effect n the current buffer:
1998 
1999      (memq 'fill buffer-minor-modes)
2000 
2001 will return the symbol "t" (truth to _^Hi_^Hf) if fill mode is in effect in this
2002 buffer, otherwise it will return "nil" (false).  Functions implementing the
2003 actions of keys in minor modes should check in this way to see what other
2004 minor modes are in effect, and what they ought do in that case.  This is
2005 admittedly not an easy design problem.
2006 
2007      The global variable fill-mode-delimiters is bound to a Lisp list of keys
2008 that act as punctuation in many minor modes.  By use of the Lisp function
2009 "mapc", all punctuation can be set to trigger a given action.  "mapc" takes
2010 two arguments, a function, and a Lisp list: the function will be called upon
2011 each element of the list:
2012 
2013 (defun no-punc-mode-word-on-a-line-mode-on ()               ;mode function
2014      (mapc 'word-on-a-line-setter fill-mode-delimiters)     ;set up keys
2015      (assert-minor-mode 'word-on-a-line))                   ;get in mode line
2016 
2017 (defun word-on-a-line-setter (key)                          ;key is the key
2018        (set-key key 'word-on-a-line-responder))             ;set these keys
2019 
2020 (defun word-on-a-line-responder ()                          ;key function
2021        (delete-white-sides)                                 ;get rid of whitesp
2022        (self-insert)                              ;insert the typed character
2023        (new-line))                                ;start a new line.
2024 
2025 This set of functions (very crudely) establishes a minor mode in which
2026 each word goes on a separate line as it is typed.
2027 
2028                             C^H__^Hh_^Ha_^Hr_^Ha_^Hc_^Ht_^He_^Hr D^H__^Hi_^Hs_^Hp_^Ha_^Ht_^Hc_^Hh_^Hi_^Hn_^Hg
2029 
2030 
2031      It is often very useful to make decisions based upon the
2032 identity of the character to the right (or left) of the current point.  The
2033 Multics Emacs environment provides several special forms and functions for
2034 facilitating this efficiently.  All of these functions and forms accept
2035 either of two ways of describing characters: either a single-character string
2036 (e.g., "."), or a symbol whose name is that character (e.g., 'a, as it would
2037 appear in a program).  We will call the first kind the "string form", and the
2038 second kind "character objects".
2039 
2040      The function "curchar", of no arguments, returns the character to the
2041 right of the current point as a character object (this is done for reasons of
2042 storage efficiency: character objects are unique, while strings require
2043 allocation).  You can test for two character objects being the same unique
2044 object (or any two objects, in general) via the Lisp predicate "eq":
2045 
2046 (if (eq (curchar) 'a)
2047     (display-error "We are looking at an ""a""."))
2048 
2049 Note that we could have also done this with the "looking-at" predicate
2050 described above, but for single characters, looking-at is a lot less efficent,
2051 in both time and storage.
2052 
2053      Please note very carefully that you cannot use _^He_^Hq to test if two strings
2054 have the same characters in them;  Lisp strings are _^Hn_^Ho_^Ht uniquized in the same
2055 way that symbols are uniquized via the obarray.
2056 
2057      In order to facilitate the use of "messy" characters (tabs, linefeeds,
2058 spaces, quotes, etc.) in this way, the Emacs environment provides several
2059 global variables with values of the character objects for these "messy"
2060 characters:
2061 
2062 ESC                 ASCII ESC, Ascii 033.
2063 CRET                ASCII Carriage return (Ascii 015)
2064 NL                  ASCII Newline (linefeed), Ascii 012.
2065 SPACE               ASCII blank, Ascii 040.
2066 TAB                 ASCII tab, Ascii 011.
2067 BACKSPACE           ASCII backspace, Ascii 010.
2068 DOUBLEQUOTE         ", Ascii 042.
2069 SLASH               /, Ascii 057, hard to type in Lisp code.
2070 
2071 Note that (eq (curchar) NL) is equivalent to (eolp).
2072 
2073      There is a special form to test if the current (to the right of point)
2074 character is a given character: it is called if-at:
2075 
2076 (if-at "&" (display-error "You can't have an ampersand here!"))
2077 
2078 Its syntax is the same as _^Hi_^Hf, i.e., it has one or none or many "then" clauses
2079 and "else" clauses, separated by the keyword "else" if there are any "else"
2080 clauses.  However, instead of a predicate, _^Hi_^Hf-^H__^Ha_^Ht takes either a
2081 single-character string or a character object to be compared against the
2082 current character.  If the current (to right of point) character is that
2083 character, the _^Ht_^Hh_^He_^Hn forms are evaluated, etc.  _^Hi_^Hf-^H__^Ha_^Ht will convert the
2084 character string to a character object at Lisp compile time, if necessary.
2085 The specification of the character must be a form which evaluates to
2086 the character of interest (e.g., "a", 'a, variable-bound-to-an-a):
2087 
2088 (if-at TAB (delete-char)
2089            (whitespace-to-hpos next-field))       ;tab to next field.
2090 
2091      The exact effect (and actual implementation) of _^Hi_^Hf-^H__^Ha_^Ht is as though
2092 it were a shorthand for
2093 
2094           (if (eq (curchar) ....) ..... ..... ..... )
2095 
2096      There is similarly a function called "lefthand-char", which is like
2097 _^Hc_^Hu_^Hr_^Hc_^Hh_^Ha_^Hr except that it returns the character to the _^Hl_^He_^Hf_^Ht of the current
2098 point; if the current point is at the beginning of the buffer, it returns
2099 a character object for a newline (which is almost always what you want).
2100 Similarly, there is an "if-back-at" special form, whose syntax and semantics
2101 are identical to "if-at", except that it deals with the character to the
2102 _^Hl_^He_^Hf_^Ht of the current point.
2103 
2104      Ther are two special forms for dispatching on the current (lefthand or
2105 righthand) character.  They are called dispatch-on-current-char
2106 and dispatch-on-lefthand-char, and dispatch upon the character to the
2107 _^Hr_^Hi_^Hg_^Hh_^Ht and the _^Hl_^He_^Hf_^Ht of the current point respectively:
2108 
2109 (declare (special parentable))                              ;global var.
2110 (setq parentable nil)                   ;done when code is loaded into editor
2111 
2112 (defun count-parens-in-buffer ()
2113        (if (not parentable)                                 ;if not initialized
2114            (setq parentable (charscan-table "()")))         ;init it.
2115        (let ((leftcount 0)(rightcount 0))                   ;init the counts.
2116             (save-excursion                                 ;be nice
2117              (go-to-beginning-of-buffer)
2118              (do-forever
2119               (if (not (search-charset-forward parentable)) ; look for ( or ).
2120                   (stop-doing))                             ;exit the do.
2121               (dispatch-on-current-char                     ;see which.
2122                ( "("          (setq leftcount (+ 1 leftcount)))
2123                ( ")"          (setq rightcount (+ 1 rightcount))))))
2124            (minibuffer-print (decimal-rep leftcount) " opens, "
2125                              (decimal-rep rightcount) "closes.")))
2126 
2127 The general syntax of dispatch-on-current-char and dispatch-on-lefthand-char
2128 is as follows:
2129 
2130 (dispatch-on-current-char
2131   (CH1              <CH1-form1>
2132                     <CH1-form2>
2133                     ...........
2134                     <CH1-formn>)
2135   (CH2              <CH2-form1>
2136                     <CH2-form2>
2137                     ...........
2138                     <CH2-formn2>)
2139 ...............................
2140   (CHk              <CHk-form1>
2141                     <CHk-form2>
2142                     ...........
2143                     <CHk-formnk>)
2144   (else             <else-form1>
2145                     <else-form2>
2146                     ............
2147                     <else-formn>))
2148 
2149      The CHi's can be any form which evaluates to a single-character string
2150 or to a character object. When the current character (left or right as
2151 appropriate) matches a CHi, all of the <CHi-form>'s in that clause are
2152 evaluated sequentially, and the value of the last returned as the value
2153 of the dispatch-on-current-char (nil is returned if there are no
2154 <CHi-form>'s).  If no CHi's match, the else clause is evaluated as though it
2155 were a matching clause.  The else clause is optional; if omitted, and no
2156 CHi matches, nil is returned.
2157 
2158 
2159                              P^H__^Hr_^Ho_^Hg_^Hr_^Ha_^Hm D^H__^He_^Hv_^He_^Hl_^Ho_^Hp_^Hm_^He_^Hn_^Ht
2160 
2161      The editor itself provides many powerful tools for developing extension
2162 code and testing it while editing it.  The following is a typical scenario
2163 in the development of an extension:
2164 
2165      The user decides to write an extension.  He sits down and thinks about
2166 it, and decides to code it.  He enters Multics Emacs.  He does a
2167 ^X^Fshaver.lispCR, to go into a new buffer with a proper file name
2168 and select Lisp major mode (assuming that he has, as all sophisticated users
2169 should, opt for find-file-set-modes "on").  He should then type the form
2170 
2171           (%include e-macros)
2172 
2173 at the top of his file; this will be necessary to compile it (see
2174 "Compilation" below), or to use the "loadit" command, as we will describe.
2175 The file e-macros.incl.lisp should be in the translator search rules for
2176 your process.  A good way to to do this is put a link to it in the directory
2177 in which you do Emacs extension development; the file is found in the same
2178 directory as the editor.  Now we begin to type in a function:
2179 
2180 (%include e-macros)
2181 
2182 (defun shave-line ()
2183       (go-to-beginning-of-line)
2184 
2185 At this point, to type the next line, lining it up with the last
2186 Lisp form, we use the indent-to-lisp command, which is on ESC-CR
2187 on Lisp mode, and the next form will automatically indent properly:
2188 
2189       (delete-white-space)
2190 
2191 (We deliberately gave the wrong name here).  When typing in Lisp in general,
2192 ESC-CR (in Lisp mode) will indent you on the next line the right amount.
2193 
2194       (go-to-end-of-line)
2195       (delete-white-space)
2196 
2197 Now we are looking at the buffer with the code for "shave-line" in front of
2198 us.  We wish to try it.  The best way to do this is to load the code in the
2199 buffer into the editor.  ESC-^Z in Lisp mode does this.  No sooner do we do
2200 this then we get the message:
2201 
2202           Unbalanced parentheses.
2203 
2204 What this means is that there were not enough close parentheses somewhere:
2205 Emacs could not find the boundaries of the Lisp form.  Now we fix the program
2206 problem.  We are on the last line, so we just type the close paren:
2207 
2208       (delete-white-space))
2209 
2210 Now we do the ESC-^Z again.  It works, the cursor returns to the function we
2211 are trying to edit.  Now to see if it works, we invoke it from Lisp:
2212 
2213           ESC-ESC shave-line CR
2214 
2215 ESC-ESC puts parens around what you type, evaluates it, and types out the
2216 Lisp value so returned.  However, we find the message
2217 
2218        lisp: undefined function: delete-white-space
2219 
2220 printed in the minibuffer, with the terminal bell rung.  In fact, this is the
2221 case.  So we realize, that we must have the wrong function name.  We know it's
2222 on a key, so we
2223 
2224      ESC-X apropos white CR
2225 
2226 and learn about delete-white-sides.  Now we go to the first line that
2227 has the bad function name, with ^P's, do an @ to clear the line out,
2228 ESC-^I to line up to re-type the form, and
2229 
2230      (delete-white-sides)
2231 
2232 We fix the other bad line, too.  Now again we type
2233 
2234      ESC-ESC shave-line CR
2235 
2236 and to our surprise it says
2237 
2238      lisp: undefined function: delete-white-space
2239 
2240 as though we hadn't changed anything.  Indeed, fixing it in the buffer is not
2241 good enough.  We must reload it into the editor environment, so we use
2242 ESC-^Z again, after fixing the screen.  Now we try it again:
2243 
2244      ESC-ESC shave-line CR
2245 
2246 and immediately our function on the screen changes appearance, all the
2247 whitespace on the ends of the last line of the function we edited disappears.
2248 Indeed it works, but it has messed up its own face!  This is a problem with
2249 editing what you are testing:  It must either be innocuous, i.e., do
2250 something harmless, or you must be prepared to reconstruct damage your
2251 nascient function perpetrates, or switch to a test buffer before running it.
2252 
2253      So we fix our function, and we are done.  Wrong! It exists in an editor
2254 buffer, and in the editor Lisp environment, but we must remember to write it
2255 out:
2256 
2257      ^X^S
2258 
2259 will indeed write it out to shaver.lisp as we had set up for initially.  Now
2260 we have an operative Lisp program that we can use again.  If in a future
2261 invocation of the editor, we need to use it, we can type
2262 
2263      ESC-X loadfile <path>shaver.lisp CR
2264 
2265 and get it into the environment.  There are two problems with this, however:
2266 
2267      1) Whoever loadfile's it will have to have e-macros.incl.lisp in his
2268           translator search rules
2269 
2270      2) The code will be executed interpretively by the Lisp interpreter in
2271           the Lisp subsystem;  Multics Emacs is compiled Lisp, and compiled
2272           Lisp runs up to 100 times fster than interpreted Lisp and has fewer
2273           problems.
2274 
2275 The file shaver.lisp should be compiled.  Then, the compiled object segment
2276 can be loaded into the editor with
2277 
2278      ESC-Xloadfile <path>shaver
2279 
2280      Some other problems are of immediate interest to the extension writer.
2281 It is possible to write loops that do not terminate, or that generate infinite
2282 garbage.  This is par for the course.  If you invoke your command, and the
2283 cursor never leaves the minibuffer, and ^G seems to have no effect, you are
2284 in a loop.  Hit QUIT, and use the "pi" Multics command to reenter Emacs.
2285 If you are really unfortunate, you will get
2286 
2287      lisp: (nointerrupt t) mode, cannot accept interrupt
2288 
2289 in which case you were stuck in the process of generating infinite garbage.
2290 In this case, you must release, and your editing session is lost.  If you are
2291 more fortunate, you will get your screen back, with the cursor at the place
2292 your buggy function left it.  Often, by looking at exactly where it left it,
2293 you can get a good idea of what kind of thing was giving your program a hard
2294 time.
2295 
2296      If you get messages from Multics which tend to indicate that there is no
2297 more room in your process directory, you are probably generating an infinite
2298 number of lines, i.e., an infinite buffer.  Again, if you are up to this, you
2299 must be aware of this.
2300 
2301      Another thing that can happen is you might expose some bug, or what you
2302 believe to be bug, in Multics Emacs, or worse yet, Multics Lisp.  If this
2303 happens, please let us know via the trouble-report forwarding mechanism
2304 described in emacs.info, describing what you encountered and why you think
2305 it's a bug.
2306 
2307      It is also possible to destroy the editor environment by bad coding.
2308 This is particularly true in running compiled code which was not checked out
2309 interpretively (i.e., via ESC-^Z).  Storing into "nil" is one common way to do
2310 this.  If the entire editor seems broken, and the redisplay won't even show the
2311 screen, this is what you have done. Quit and release and start all over again.
2312 
2313      There is a function called debug-e, callable as
2314 
2315      ESC-X debug-e CR
2316 
2317 which will set "(*rset t)" mode and other  Lisp debugging aids, and unsnap all
2318 "lisp links".  IT will also revert to native Maclisp QUIT/pi handling.  To use
2319 this, however, you must be familiar with the debugging features of Multics
2320 Maclisp.
2321 
2322      To get the value of a global variable to be printed out, say,
2323 fill-column, fool ESC-ESC into doing it by saying
2324 
2325      ESC-ESC progn fill-column CR
2326 
2327 Be careful, for values typed out are in octal.
2328 
2329      Now there exists an entire Lisp code debugging facility within
2330 Emacs over and above this; it is called LDEBUG, or Lisp Debug
2331 mode.  It allows for the setting of breakpoints, dialogue with Lisp
2332 within Emacs, tracing, and so forth.  See ldebug-mode.info,
2333 or the appropriate part of CJ52, Emacs Extension Writer's Guide.
2334 
2335                                  C^H__^Ho_^Hm_^Hp_^Hi_^Hl_^Ha_^Ht_^Hi_^Ho_^Hn
2336 
2337      All production Multics Lisp programs are compiled.  This results in a
2338 tremendous performance improvement, both for the user and the system.  Compiled
2339 Lisp programs are executed directly by the Multics processor; interpreted
2340 programs are interpreted by the Lisp interpreter.  Multics Emacs is compiled
2341 Lisp.
2342 
2343     The Lisp compiler is a Multics program that can be invoked from command
2344 level.  It has the names lcp and lisp_compiler on it.  To compile a program
2345 named myfuns.lisp, you say
2346 
2347      lcp myfuns
2348 
2349 to Multics, and you will get, if all goes well, an object program named
2350 "myfuns", which can be loadfile'd, in the working directory.
2351 
2352      The compiler diagnoses Lisp syntax errors.  It warns you of implied
2353 special variables (if you did not declare a variable special, and it is not
2354 a local variable in the function in which it was referenced, there is a good
2355 chance you either made  mistake or a typo.  All global variables should be
2356 declared for this reason: e-macros declares the provided ones.)
2357 
2358      At the end of compilation, the compiler prints out the names of functions
2359 referenced in the code but not defined in the file.  This is normal; however,
2360 you should scan the list it prints out to see if any are ones that you
2361 thought you defined; if so, you have a problem.  Check also for ones that
2362 are obvious typos for what you meant.
2363 
2364      It is possible to do extravagantly complex things with the compiler;
2365 especially, via the constructs known as L^H__^Hi_^Hs_^Hp M^H__^Ha_^Hc_^Hr_^Ho_^Hs (via which, incidentally,
2366 the E^H__^Hm_^Ha_^Hc_^Hs environment special forms are implemented) to construct your
2367 own special forms.  We will not go into any of that here.  Consult other
2368 documents on Multics Maclisp.
2369 
2370      It is sometimes desireable, while editing a large extension program,
2371 to load only one function, the one you are looking dead at on the screen,
2372 into the editor environment.  The powerful function compile-function,
2373 on ESC-^C in Lisp mode, will compile the function you are looking at
2374 (whose start is found by ESC-^A from where you are now) out of a temporary
2375 segment in the process directory, load the object segment, and display the
2376 compiler diagnostics via local printout.  It should be used with care by
2377 any except experienced Emacs extension coders.  Be careful, when using it,
2378 to remember to write out your changes, and recompile your whole program,
2379 because a program incrementally debugged in this mode gives the impression
2380 that it is working properly when it is only doing so in the current editor
2381 environment.
2382 
2383 
2384                              D^H__^Ho_^Hc_^Hu_^Hm_^He_^Hn_^Ht_^Hi_^Hn_^Hg C^H__^Ho_^Hm_^Hm_^Ha_^Hn_^Hd_^Hs
2385 
2386      One of the most attractive features of the Emacs environment is the
2387 automatic documentation system (apropos, ESC-?), which provides customized
2388 Emacs command documentation on request.  Documentation for supplied
2389 commands is kept in a special file in the Emacs environment directory.
2390 Extension writers may provide documentation for their own commands by
2391 placing a string, which is that documentation, as the "documentation"
2392 property of the symbol which is the command being documented.  For instance,
2393 if the symbol "remove-every-other-word" has the "documentation" property
2394 of
2395 
2396       "Removes every other word from the sentence in which the cursor appears."
2397 
2398 this information will be displayed by ESC-? when used on some key which had
2399 been set-key'ed to remove-every-other-word, or by
2400 
2401      ESC-X describe remove-every-other-word
2402 
2403      Documentation properties are assigned most conveniently via the
2404 Lisp special form "defprop", whose general syntax is:
2405 
2406      (defprop SYMBOL WHAT PROPERTY)
2407 
2408 which gives the symbol SYMBOL a PROPERTY property of WHAT.  "defprop"
2409 is a special form because the actual symbols appearing in the form
2410 are used, they are not variables, as in "(+ a b c)".  Thus,
2411 
2412      (defprop Joe Fred father)
2413 
2414 indeed gives the symbol "Joe" a "father" property of "Fred".
2415 ("defprop" is a special-form way of doing the same thing as the
2416 "putprop" function, but it is a special form because is "arguments"
2417 are NOT forms to be evaluated to produce symbols whose properties
2418 are to be dealt with, but the symbols themselves).  To use
2419 "defprop" to establish Emacs command documentation, place forms like
2420 
2421 (defprop remove-every-other-word
2422           "Removes every other word from the current sentence.
2423 Will not work on sentences ending in ""?"".  For indented
2424 sentences, use $$remove-other-word-from-indented-sentences$.
2425 $$$ is a very powerful, dangerous, command."
2426           documentation)
2427 
2428 Note several things about the documentation string:
2429 
2430  1. It does not need to end in a newline, and may contain newlines.
2431 
2432  2. Quotes (") inside of it must be doubled.
2433 
2434  3. The string "$$$" will be replaced by the key being asked about
2435     (e.g., "ESC-^Z" or "ESC-X remove-every-other-word") at the time
2436     the documentation is displayed.
2437 
2438  4.  The keys used to invoke other commands may be referenced by stating two
2439      dollar signs, the name of the command, and one dollar sign.  Thus,
2440      $$go-to-end-of-line$ will appear as "^E" in most environments;  the point
2441      of this and the previous paragraph is to make documentation expansion
2442      independent of a user's key-bindings.
2443 
2444 The entire documentation string will be "filled" (ESC-Q'ed) _^Ha_^Hf_^Ht_^He_^Hr all
2445 command-name substitutions are made;  thus, the placement of newlines in the
2446 documentation string is basically ignored.  Two consecutive newlines, however,
2447 will be preserved, and thus, lines may be set off for "examples", etc., by
2448 surrounding them with blank lines.
2449 
2450      It is slightly more efficient, but clearly less readable, to place the
2451 defprop's documenting a command _^Hb_^He_^Hf_^Ho_^Hr_^He the "defun" defining the command
2452 itself.  The "defcom" facility may also be used to document commands;
2453 See "Defining commands with defcom" below.
2454 
2455                               W^H__^Hi_^Hn_^Hd_^Ho_^Hw M^H__^Ha_^Hn_^Ha_^Hg_^He_^Hm_^He_^Hn_^Ht
2456 
2457      Although buffers appear in windows on user request, and are switched
2458 between automatically by the redisplay when the user switches windows with the
2459 ^X^O, ^X4, and so forth, there are times when extension writers may
2460 want to take advantage of  multiple windows explicitly.  Good
2461 examples in supplied code are RMAIL reply mode and comout (^X^E).
2462 
2463      Most of the extensions of interest are ones in which the extension
2464 writer wants to place some information in a buffer, or else prepare
2465 some buffer to have information placed in it (e.g., RMAIL reply)
2466 and then display that information in a window.  Normally, all that
2467 is required is to "go to" that buffer (e.g., with go-to-buffer or
2468 go-to-or-create-buffer), and the redisplay will "find" the editor
2469 in that buffer at the time of the next redisplay, and it will
2470 replace the contents of the selected window on the screen.
2471 We will call such commands "autophanic" (self-showing).  Examples
2472 are ^XB (select-buffer), ^X^F (find-file), etc.
2473 
2474      However, there are commands that wish to set up buffers in some
2475 _^Ho_^Ht_^Hh_^He_^Hr window than the current window, usually for multi-window
2476 operations such as mail reply, so as not to disturb the contents
2477 of the current window.  We will call them "heterophanic" (other-showing).
2478 The standard examples are dired-examine, mail reply, and comout (^X^E).
2479 Note that all the examples given are sub-commands of larger,
2480 autophanic commands.
2481 
2482      Heterophanic buffer behavior is provided by the function
2483 find-buffer-in-window, whose purpose is mentioned in windows.info (CH27 Sec.
2484 XVI).  It takes as an argument a buffer-symbol (Lisp symbol representing a
2485 buffer).  That buffer will be created if it does not now exist, and will be
2486 "gone to", as if go-to-buffer had been used.  If Emacs is in single-window
2487 mode, the effect will be the same as that of go-to-or-create-buffer.  In
2488 two-window mode, that buffer will be put on display in one window or some
2489 other as follows:
2490 
2491     If it is already on display in some window, it will be left there.
2492     If it is _^Hn_^Ho_^Ht, it will be put on display in some _^Ho_^Ht_^Hh_^He_^Hr window,
2493        meaning the one in which the cursor is _^Hn_^Ho_^Ht, and the cursor
2494        will move to that window, as if a ^X^O had been done.  The
2495        least-recently used window will be chosen.
2496 
2497      Thus, on printing terminals and in single-window mode, the effect
2498 of find-buffer-in-window is indistinguishable from that of
2499 go-to-or-create-buffer.  In multi-window mode, it is equivalent to
2500 "go-to-or-create-buffer and show it someplace else on the screen."
2501 
2502      You must not use find-buffer-in-window to place a buffer on the
2503 screen once you have already gone to it;  if you think of
2504 find-buffer-in-window as a fancy kind of go-to-or-create-buffer you
2505 will find no need for doing so. IF, however, you encounter this very
2506 rare need (Emacs uses it only once!), how to do it will be
2507 described below.
2508 
2509      It is an extension's responsibility to establish multiple windows if it
2510 _^Hn_^He_^He_^Hd_^Hs them; no current Emacs code _^Hr_^He_^Hq_^Hu_^Hi_^Hr_^He_^Hs multiple windows, although the
2511 facilities mentioned above are more utile when already in it.
2512 
2513      Variables, predicates, and other functions to determine or
2514 effect the window organization (number of windows present, etc.)
2515 are presented below.
2516 
2517      Most extensions that place an auxiliary buffer on display via
2518 find-buffer-in-window provide some command to return to the "main"
2519 buffer (e.g., the RMAIL Incoming Message buffer, the buffer from which
2520 ^X^E was issued, etc.).  It is the case that if you entered a buffer
2521 via find-buffer-in-window, you should probably return to the buffer
2522 from whence you came via find-buffer-in-window as well; the effect of this
2523 is to restore not only the original buffer, but the original window
2524 as well. Thus, save-excursion-buffer _^Hc_^Ha_^Hn_^Hn_^Ho_^Ht be used effectively
2525 to effect returns from trips into buffers entered via find-buffer-in-window;
2526 an attempt to use save-excursion-buffer will result in both windows showing
2527 the same buffer, as the "selected window" (i.e., the cursor-bearing window)
2528 is now changed and a new buffer selection means a new buffer in that window.
2529 
2530      It is the intended standard that ^X^Q be used to exit auxiliary buffers
2531 used by extensions to return to their "main buffer", and usually switch
2532 windows as well, if the multiple-window strategy outlined above is used.
2533 
2534      Pop-up window mode is in essence making all commands heterophanic.
2535 Commands or subcommands that are naturally heterophanic need not worry about
2536 pop-up window mode, because find-buffer-in-window, takes the appropriate
2537 action in either pop-up or non-pop-up mode.  However, if proper heterophanic
2538 behavior under pop-up windows is desired, naturally autophanic commands and
2539 subcommands must call a window-management primitive to obtain
2540 heterophanic behavior in pop-up window mode.  The primitive
2541 of interest is called select-buffer-window, which takes two arguments
2542 a buffer-symbol, and a "key" which gives pop-up window management
2543 some clue to what size window would be wanted if awindow had to be created.
2544 
2545      In non-pop-up window mode, select-buffer-window is equivalent to
2546 go-to-or-create-buffer, and the key is ignored.  In pop-up mode, it is
2547 equivalent to find-buffer-in-window, with the key suggesting the
2548 new window size.
2549 
2550      The following values for the key argument to select-buffer-window
2551 are accepted.  They specify the window size in pop-up mode if the
2552 window does not exist already:
2553 
2554           any number                    That many lines.
2555           'cursize                      Make a choice based on
2556                                         the current number of lines in
2557                                         the buffer.
2558           nil                           Choose some reasonable fraction
2559                                         of the screen.
2560           'cursize-not-empty            Same as nil if the buffer is empty
2561                                         but same as 'cursize if it's not>
2562                                         For example, ^X^F uses this, because
2563                                         you will type into a new buffer.
2564           'default-cursize              If this buffer has never been displayed
2565                                         before, make some decision based on the
2566                                         number of lines.  Otherwise, use
2567                                         what size was chosen last time..
2568 
2569      As we mentioned, find-buffer-in-window may not be used to place
2570 the "current buffer" heterophanically.  If you attempt to do this, i.e.,
2571 
2572           (find-buffer-in-window current-buffer)
2573 
2574 you will find it appearing in both the old and new windows, for the
2575 window manager will find that you were in this buffer in the
2576 current window (a truth) before you went to another one (you had
2577 to go to another one, as per heterophanic behavior), and
2578 will indicate that the current buffer is to be displayed in the old window
2579 as well, for that was the last buffer you were in in that window.
2580 To avoid this, use select-buffer-find-window (of two arguments,
2581 the buffer and a key as for select-buffer-window) if heterophanic
2582 display of the current buffer is needed, i.e.,
2583 
2584           (select-buffer-find-window current-buffer nil)
2585 
2586 It is very rare that this is needed; it is very rare to go to a buffer
2587 and then want to find-buffer-in-window it; in supplied Emacs, only
2588 ^X^E does this.
2589 
2590      As all things that would want to use these features are of necessity
2591 moderately sophisticated, only an outline of an extension using them
2592 is given here.  It is a typical sub-subsystem (e.g., dired) which
2593 sets itself up in an autophanic buffer display, with specific
2594 key bindings, etc., and has a heterophanic sub-display by which
2595 it displays a "menu" in addition to the main display:
2596 
2597 (defun unusual-mode ()                            ;Setup function for this
2598        ...........                                ;mode.
2599        (go-to-or-create-buffer (maknam (explodec "Unusual buffer")))
2600        (set-key 'ESC-^S 'unusual-mode-show-menu)
2601        (select-buffer-window current-buffer nil)
2602        (register-local-var 'unusual-mode-buffer-to-return-to)
2603       ...........)
2604 
2605  ............
2606 (declare (special unusual-mode-buffer-to-return-to))   ;for compiler.
2607 (defun unusual-mode-show menu ()
2608        (setq unusual-mode-buffer-to-return-to current-buffer)    ;save buff
2609        (find-buffer-in-window 'Unusual-Menu)      ;Display menu
2610        (set-key 'r 'unusual-mode-select-item)     ;Set key bindings
2611        (set-key '^X^Q 'unusual-mode-menu-return)
2612        (insert-string "Unusual menu delicacies")  ;Fill it up
2613        ;; Will not actually be displayed until command finishes.
2614        .......
2615        (go-to-beginning-of-buffer)
2616        (setq current-buffer-mode 'Unusual/ Menu buffer-modified-flag nil
2617              read-only-flag t)
2618        .........)
2619 
2620 (defun unusual-mode-menu-return ()
2621        (find-buffer-in-window unusual-mode-buffer-to-return-to))
2622        ;;Return to calling buffer.
2623 
2624      There are several more primitives the window-sensitive
2625 extension writer should be aware of.  They deal with windows by "window
2626 number".  The topmost window on the screen is window number 1; The
2627 next one down, if any, is number 2, and so forth down (the minibuffer and
2628 mode line do not count as windows in this consideration).  The concept
2629 of selected-window (and selection of windows) is as in windows.info
2630 (or CH27, Section XVI.)
2631 
2632    selected-window
2633           This _^Hv_^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He contains the number of the currently
2634           selected window.  Do _^Hn_^Ho_^Ht attempt to setq it to select a window;
2635           Use select-window instead.
2636 
2637    nuwindows
2638           This _^Hv_^Ha_^Hr_^Hi_^Ha_^Hb_^Hl_^He contains the number of windows on the
2639           screen; do _^Hn_^Ho_^Ht attempt to setq it to create or delete
2640           windows; use delete-window and the ^X2 and ^X3 functions
2641           to do these things.
2642 
2643    select-window
2644           This _^Hf_^Hu_^Hn_^Hc_^Ht_^Hi_^Ho_^Hn  (of one argument, a window number)
2645           does what ^X4 does (with an argument), i.e., selects that
2646           window.
2647 
2648    delete-window
2649           This _^Hf_^Hu_^Hn_^Hc_^Ht_^Hi_^Ho_^Hn of one argument, a window number,
2650           removes that window from the screen, dividing up its space
2651           to adjacent windows.
2652 
2653    buffer-on-display-in-window
2654           This _^Hp_^Hr_^He_^Hd_^Hi_^Hc_^Ha_^Ht_^He function of one argument, a buffer-symbol,
2655           and returns truth/falsity, truth if and only if the specified
2656           buffer is on display in some window currently on the screen.
2657           If used as a _^Hf_^Hu_^Hn_^Hc_^Ht_^Hi_^Ho_^Hn, i.e., the value returned
2658           is inspected, it will be found to be the window number in which
2659           the specified buffer is on display (if it is _^Hn_^Ho_^Ht on display, the
2660           symbol "nil", via which Lisp represents falsity, is returned).
2661 
2662    window-info
2663           This is a function of one argument, a window number, which
2664           returns information about that window.  The information
2665           is in the form of a piece of Lisp list structure, which may be
2666           decomposed by the Lisp list destructuring functions; assuming
2667           that "info" has the result of window-info, the following forms
2668           return the information as follows:
2669 
2670                     (caar info) => The top line-number on the screen of the
2671                                    window.  The topmost is #0.
2672                     (cdar info) => The number of lines in the window.
2673                     (caddr info) => The buffer-symbol of the buffer on
2674                                     display in the window.
2675                     (cadddr info) => A string duplicating the contents of the
2676                                      "cursor line" of the window, including
2677                                      its new-line character.    The cursor
2678                                      line of a buffer is that line where the
2679                                      cursor is (if it is in the selected
2680                                      window) or would be if that window
2681                                      became selected (e.g., ^XO).
2682 
2683    window-adjust-upper
2684           A function of two arguments, the first a window number, and
2685           the second a _^Hs_^Hi_^Hg_^Hn_^He_^Hd number of lines to move its
2686           upper divider-line _^Hd_^Ho_^Hw_^Hn (negative is up).
2687 
2688    window-adjust-lower
2689           Same as window-adjust-upper, but deals with lower divider line.
2690 
2691                                W^H__^Hr_^Hi_^Ht_^Hi_^Hn_^Hg S^H__^He_^Ha_^Hr_^Hc_^Hh_^He_^Hs
2692 
2693      There are several useful functions provided for the extension writer
2694 to aid in providing search-type commands.  These functions prompt
2695 for the search string, defaultify the search string, and announce
2696 search failure in a standardized way which causes all Emacs search
2697 commands to behave in a uniform fashion.  All supplied Emacs searches
2698 use them.
2699 
2700      get-search-string
2701           Takes one argument, the prompt.  The prompt ought contain
2702           the word "search" somehwere, so that the user might know
2703           that a search is being prompted for.  get-search-string will
2704           prompt the user for a search string, which the user must
2705           terminate with a CR, and return it as a string.
2706           If the user gives a null string, the last search string
2707           will be used and echoed.  The last search string will be set
2708           to the returned string for the next defaulting.
2709 
2710      search-failure-annunciator
2711           Causes the "Search Fails." message to appear in the minibuffer,
2712           and a command-quit (^G) to be performed.  Note that this will
2713           abort any keyboard macro collection or execution in progress.
2714 
2715      The writer of a search-type command should provide two interfaces,
2716 a "command", which deals in calling the above two primitives, and a
2717 "search primitive", also called by the "command".  The search primitive
2718 should return t (truth) if the search succeeds, leaving "point"
2719 at the proper place as the search defines.  If the search fails,
2720 the primitive must return nil (falsity), and leave point where it
2721 was when the primitive was invoked.
2722 
2723      Here is a simple implementation of a "wraparound search", like
2724 the default search in the QEDX editor.  It first looks from point to
2725 the end of the buffer for the search string, and if that fails, it goes
2726 to the top and searches again.  It is not optimal because the it need not
2727 scan farther than the original point when starting from the top.  Using
2728 "point>markp" and searching a line at a time would be very expensive,
2729 due to point>markp's expense.  Searching a line at a time using
2730 forward-search-in-line an mark-on-current-linep would be acceptable, but
2731 more complex than this example need be.  For a search which is probably
2732 going to be used only as a user interface (i.e., not internally), this
2733 implementation is probably adequately efficient.
2734 
2735      Here is the internal primitive for wraparound search:
2736 
2737      (defun wraparound-search-primitive (string)
2738             (with-mark m                          ;Remember starting point
2739                 (if (forward-search string)       ;Look to end of buffer
2740                     t                             ;Return truth.
2741                     else
2742                     (go-to-beginning-of-buffer)
2743                     (if (forward-search string)   ;Look from top.
2744                         t
2745                         else
2746                         (go-to-mark m)            ;Return to orig. place.
2747                         nil)))))                  ;Return falsity
2748                 ;; with-mark and this function, will
2749                 ;; return the value of the outer "if".
2750 
2751      Now here is the command for calling the primitive:
2752 
2753      (defun wraparound-search ()
2754             (if (not (wraparound-search-primitive
2755                         (get-search-string "Wraparound Search: ")))
2756                 (search-failure-annunciator)))
2757 
2758      wraparound-search is the command to which some key should be bound
2759 if this type of search is to be made available from the keyboard.
2760 
2761 
2762                            C^H__^Ha_^Hl_^Hl_^Hi_^Hn_^Hg M^H__^Hu_^Hl_^Ht_^Hi_^Hc_^Hs C^H__^Ho_^Hm_^Hm_^Ha_^Hn_^Hd_^Hs
2763 
2764      There is a common need in extensions, especially those like DIRED,
2765 which manipulate the Multics Environment, to call Multics commands,
2766 or, more generally, execute Multics command lines.
2767 
2768      The issue of calling PL/I-coded subroutines is a separable one.  The
2769 Lisp defpl1 facility is used for that, and we have not documented this yet.
2770 See extant extensions (and e_defpl1_.lisp) for examples and usage until then.
2771 
2772      There are two primitives provided for executing Multics command lines.
2773 Multics command lines are strings submitted to cu_$cp for execution.
2774 This is the Multics agency to which the "e" requests of EDM and QEDX,
2775 the ".." requests of read_mail, send_mail, and debug, and other subsystems
2776 submit command lines.  These are they:
2777 
2778      e_cline_
2779           Takes one argument, a string, which is passed to cu_$cp for
2780           execution.  No reattachment of output takes place.  If the
2781           command line produces output, it will mess up the screen.
2782           This should only be used when no output is anticipated, and
2783           indeed should be used then in preference to comout-get-output,
2784           as it is much faster.
2785 
2786      comout-get-output
2787           Takes any number of arguments, which may be strings or symbols,
2788           and catenates them with one space between them to form a
2789           Multics command line (facilitating things like
2790 
2791                (comout-get-output 'dl this-seg '-bf)
2792 
2793           ).  Reattaches user_output and error_output during the
2794           execution, rerouting them to a process directory file.  When
2795           the command execution completes, the contents of the current
2796           buffer is obliterated (!) and the temporary file read in to it.
2797           This is the primitive that Comout (^X^E) uses.  e_cline_
2798           is used by comout-get-output internally.
2799 
2800      These primitives set up a condition handler that catches all "abnormal"
2801 Multics signals and returns.  A very major deficiency at this point, which is
2802 not likely to be remedied in the near future, is that requests for input by
2803 these command lines cannot be dealt with reasonably at all.  In the case of
2804 e_cline_, the user will get the query in raw teletype modes, and will have to
2805 answer it in raw, nonedited teletype modes.  In the case of comout-get-output,
2806 the query will never appear in any form at all, having been routed to the
2807 temporary segment, and the user's process will hang infinitely, the user
2808 not knowing to respond having never seen the query.
2809 
2810                              M^H__^Hu_^Hl_^Ht_^Hi_^Hc_^Hs E^H__^Hr_^Hr_^Ho_^Hr T^H__^Ha_^Hb_^Hl_^He
2811 
2812      Sometimes it is necessary to get the value of standaard Multics error
2813 codes, from error_table_, into a program, to be able to see if a given
2814 Multics interface has in fact returned it.  The function "error_table_"
2815 (spelled the usual way with underscores, not hyphens) is used for this
2816 purpose.  Its single argument is a symbol, whose name is the name
2817 of the error_table_ entry whose value is sought, and the returned
2818 result is that value, or 1 if it is not a valid entry.
2819 
2820      The error_table_ function optimizes finding the same name over
2821 and over again, so the extension writer need not go through machinations
2822 to "save" an error_table_ value computed by these means.
2823 Here is an example of the use of error_table_:
2824 
2825       (let ((status-result (hcs_$get_user_effmode dir entry "")))
2826            (if (not (= (cadr status-result) 0) ;the return code
2827                (if (= (cadr status-result)(error_table_ 'incorrect_access))
2828                    (display-error-noabort "Warning: not checking access")
2829                    else
2830                    (display-com-error (cadr status-result) dir ">" entry))))
2831 
2832 
2833                         Defining commands with defcom
2834                         _____________________________
2835 
2836      The "Defcom" (short for _^Hd_^He_^Hf_^Hi_^Hn_^He-_^Hc_^Ho_^Hm_^Hm_^Ha_^Hn_^Hd) facility is a fairly new addition
2837 to Emacs (and thus many internal functions are not converted to use it) for
2838 simplifying the definition of Lisp functions to be used as Emacs commands,
2839 either keystroke requests, or extended commands.  Defcom cooperates
2840 with the Emacs command-reader to provide prompting and defaulting
2841 of unspecified arguments, range-checking of numeric arguments,
2842 automatic repetition for numeric arguments, if desired, cross-connecting
2843 symmetrical functions via negative arguments, and other features.
2844 
2845      Defcom should only be used for defining functions actually to
2846 be used as Emacs commands;  internal and auxiliary
2847 functions to be used by these functions should still be defined with
2848 defun.  Emacs commands defined with defun will continue to work, but
2849 those defined with defcom produce much better diagnostics and
2850 offer more features.  Defcom is actually a technique whereby
2851 the necessary "defun"'s are generated automatically, so functions
2852 defined with defcom may be called from other functions, as well.
2853 
2854      To define a function with defcom, one uses defcom instead of defun,
2855 and supplies no Lisp argument list, i.e.,
2856 
2857    (defcom one-word-from-beginning
2858            (go-to-beginning-of-buffer)
2859            (forward-word))
2860 
2861 This is the simplest form of defcom; optional features are supplied by
2862 placing, between the function name and the function code, various keywords,
2863 all of which begin with the "&" character, and some of which take optional
2864 arguments, expressed as lists.
2865 
2866      The most common optional specification is &numeric-argument,
2867 (or &na for short), which specifies what to do with a supplied numeric
2868 argument, if any.  The keyword &numeric-argument must be followed by
2869 a list of specifications, which must include one of the following
2870 maJor processing types:
2871 
2872           &reject             Any numeric argument is rejected as invalid.
2873                               Clearly, no other specifications are valid
2874                               in this case. This is the default if
2875                               &numeric-argument is not given.
2876           &ignore             A numeric argument is ignored.
2877           &repeat             If the argument is positive, the
2878                               command is repeated that many times.
2879           &pass               The value of the Lisp variable "numarg"
2880                               is set, as in non-defcom commands.
2881 
2882      In addition to the major processing type, optional bounds may
2883 be specified by the keywords &upper-bound (&ub) or &lower-bound (&lb).
2884 These, in turn, must be followed by either an integer  being the bound, or the
2885 keyword &eval followed by an expression to evaluate at the time command
2886 execution is attempted, which will then produce a value (such an expression
2887 will be called an "&eval expression".)  Here are some examples of
2888 &numeric-argument specifications:
2889 
2890           &numeric-argument (&pass)
2891           &numeric-argument
2892                     (&repeat &lower-bound 1 &upper-bound &eval (+ max-foos 2))
2893           &numeric-argument
2894                     (&pass &upper-bound 15.)
2895 
2896      A command defined with defcom may elect to receive Lisp arguments,
2897 that is to say, values which are to be prompted for or supplied as
2898 extended command arguments can be provided automatically, and prompted
2899 for, by the Emacs command reader, and supplied as Lisp arguments to the
2900 command function.  Instead of a normal Lisp argument list, the
2901 keyword &arguments (or &args or &a), followed by list of argument
2902 specifications, one for each Lisp argument to be supplied.
2903 
2904      Each argument specification consists of the Lisp name of the argument,
2905 i.e., the name of the variable which will be referred to inside the function,
2906 and any number of "argument qualifiers", separated by spaces.  Each
2907 argument qualifier may consist of several tokens, as necessary.  Argument
2908 qualifiers specify the prompts, defaults, etc. for an argument.
2909 An argument specification  may also be given as the name of the variable
2910 alone, as opposed ot a list of it and qualifiers.  In this case,
2911 it is equivalent to having its own name as a prompt for its value.
2912 
2913      When a defcom-defined commands is invoked as an extended command,
2914 (i.e., via ESC-X), the Emacs command reader will check the type and
2915 number of command arguments supplied and necessary, and prompt for those not
2916 supplied or default them as specified.  When a defcom-defined
2917 command which has arguments is invoked from a key, it is as if
2918 it were invoked as an extended command with no command arguments given,
2919 and all are either prompted for or defaulted.
2920 
2921      Here are the valid argument qualifiers:
2922 
2923           &string
2924           &symbol
2925           &integer            Specify how the argument, when read
2926                               by ESC-X or prompted for is to be converted
2927                               before being passed.  Only one at a time
2928                               of these are valid in a given argument
2929                               specification, and &string (i.e., no
2930                               conversion) is the default.
2931 
2932           &default            Must be followed by either a string,
2933                               symbol, or integer, as consistent with
2934                               the expected data type for this argument,
2935                               or an &eval expression.  Specifies the
2936                               default value to be used if this argument
2937                               is not supplied, or a null response
2938                               is given to a prompt for this argument,
2939                               if any.
2940 
2941           &prompt             Specifies the prompt for this argument, if
2942                               not supplied via ESC-X.  Prompts will be
2943                               put to the user before defaults are evaluated
2944                               or used; A null string causes the &default
2945                               value to be used.  &prompt is followed by
2946                               a prompt string (in quotes)(or an &eval
2947                               expression), and one of the two optional keywords
2948                               NL or ESC, specifying the prompt terminator
2949                               (ESC is obsolete, use NL in all cases).
2950                               If neither NL or ESC is given,
2951                               NL is assumed as the default.
2952 
2953           &rest-as-list       Valid only for the last argument.  Causes
2954                               this variable to be given as a value a
2955                               list of all of the remaining supplied
2956                               arguments, however many they may be. If
2957                               &rest-as-list is used, the caller of this
2958                               function from Lisp (including start-up's written
2959                               by possibly not-Lisp-conscious users)
2960                               must know that the number and organization
2961                               of Lisp arguments is therefore different
2962                               from the apparent argument array given to
2963                               ESC-X.
2964 
2965           &rest-as-string     Valid only for the last argument, causes
2966                               all remaining arguments to be supplied as
2967                               a single string to the function, a single
2968                               argument, as they appeaed to ESC-X, with
2969                               spaces and so forth included.  Same cautions
2970                               as &rest-as-list apply.
2971 
2972      Here is a function definition which accepts three arguments:
2973 
2974 (defcom replace-n-times
2975         &arguments
2976         ((oldstring &string  &default &eval (get-search-string "Old: "))
2977          (newstring &string &prompt "New String: " NL)
2978          (count &integer &prompt "How many times? " NL &default 1))
2979 
2980         (do-times count
2981           (if (not (forward-search oldstring))(search-failure-annunciator))
2982           (do-times (stringlength oldstring)(rubout-char))
2983           (insert-string newstring)))
2984 
2985 Note that it can be invoked as
2986 
2987   ESC-X replace-n-times Washington Lincoln 2 CR
2988 
2989 or
2990 
2991   ESC-X replace-n-times CR
2992 
2993 in which case all arguments will be prompted for, or
2994 
2995    set-perm-key  ^Z9 replace-n-times
2996 
2997 followed by striking that key at some time, will prompt for
2998 all arguments, too.  This function is so defined that it may
2999 be called from Lisp as
3000 
3001           (replace-n-times "this" "that" 17)
3002 
3003 or whatever, i.e., it is a Lisp function of three arguments.
3004 
3005      When defcom-defined commands are re-invoked by ^C, they are
3006 repeated with identical arguments.  This is what makes search-repetition
3007 by ^C work.
3008 
3009      Other than numeric arguments and command arguments, defcom
3010 may be used to spceify prologues, documentation, and negative-functions
3011 of command functions.  Documentation is specified by the
3012 keyword &documentation (or &doc) followed by a documentation
3013 string subject to the same rules as given above under "Documenting
3014 Commands".  Prologues are functions or code to be executed
3015 before any arguments are prompted for, perhaps to check for legal
3016 circumstances for calling this command.  Negative functions are
3017 functions or code to be executed if the command is supplied a negative
3018 numeric argument: the negative function is given the negative numeric
3019 argument made positive.  Prologues and negative functions are
3020 speicifed by the keywords &prologue, or &negative-function
3021 (short, &nf), followed by the name of the appropriate function,
3022 or forms, terminated by &end-code.  Here is an example of the
3023 use of some of these features:
3024 
3025 (defcom forward-topic
3026         &doc "Goes forward one or more topics. See also $$backward-topic$."
3027         &numeric-argument (&repeat)
3028         &negative-function backward-topic
3029         (with-mark m
3030            (forward-search "Topic::"............
3031 
3032 
3033 ^L
3034 Yet to be documented:
3035 
3036 Lisp macro catalogue.
3037 Emacs interrupt system.
3038 
3039 
3040    As this document is extended and augmented, it may not approach true
3041 "completion" in any given length of time.  Thus, there are still "tricks"
3042 and functions that are not documented above.  The extension writer should
3043 study the supplied extensions, such as Fortran Mode (fortran-mode.lisp)
3044 and RMAIL (rmail.lisp), as well as the "fundamental mode extensions"
3045 in e_macops_.lisp.  These programs are found in the Emacs source archive.