1This is emacs-lisp-intro.info, produced by makeinfo version 4.0b from 2emacs-lisp-intro.texi. 3 4INFO-DIR-SECTION Emacs 5START-INFO-DIR-ENTRY 6* Emacs Lisp Intro: (eintr). 7 A simple introduction to Emacs Lisp programming. 8END-INFO-DIR-ENTRY 9 10 This is an introduction to `Programming in Emacs Lisp', for people 11who are not programmers. 12 13 Edition 2.04, 2001 Dec 17 14 15 Copyright (C) 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software 16Foundation, Inc. 17 18 Permission is granted to copy, distribute and/or modify this document 19under the terms of the GNU Free Documentation License, Version 1.1 or 20any later version published by the Free Software Foundation; with the 21Invariant Section being the Preface, with the Front-Cover Texts being 22no Front-Cover Texts, and with the Back-Cover Texts being no Back-Cover 23Texts. A copy of the license is included in the section entitled "GNU 24Free Documentation License". 25 26 27File: emacs-lisp-intro.info, Node: Cutting & Storing Text, Next: List Implementation, Prev: car cdr & cons, Up: Top 28 29Cutting and Storing Text 30************************ 31 32 Whenever you cut or clip text out of a buffer with a `kill' command 33in GNU Emacs, it is stored in a list and you can bring it back with a 34`yank' command. 35 36 (The use of the word `kill' in Emacs for processes which specifically 37_do not_ destroy the values of the entities is an unfortunate 38historical accident. A much more appropriate word would be `clip' since 39that is what the kill commands do; they clip text out of a buffer and 40put it into storage from which it can be brought back. I have often 41been tempted to replace globally all occurrences of `kill' in the Emacs 42sources with `clip' and all occurrences of `killed' with `clipped'.) 43 44* Menu: 45 46* Storing Text:: Text is stored in a list. 47* zap-to-char:: Cutting out text up to a character. 48* kill-region:: Cutting text out of a region. 49* Digression into C:: Minor note on C programming language macros. 50* defvar:: How to give a variable an initial value. 51* copy-region-as-kill:: A definition for copying text. 52* cons & search-fwd Review:: 53* search Exercises:: 54 55 56File: emacs-lisp-intro.info, Node: Storing Text, Next: zap-to-char, Prev: Cutting & Storing Text, Up: Cutting & Storing Text 57 58Storing Text in a List 59====================== 60 61 When text is cut out of a buffer, it is stored on a list. Successive 62pieces of text are stored on the list successively, so the list might 63look like this: 64 65 ("a piece of text" "previous piece") 66 67The function `cons' can be used to add a piece of text to the list, 68like this: 69 70 (cons "another piece" 71 '("a piece of text" "previous piece")) 72 73If you evaluate this expression, a list of three elements will appear in 74the echo area: 75 76 ("another piece" "a piece of text" "previous piece") 77 78 With the `car' and `nthcdr' functions, you can retrieve whichever 79piece of text you want. For example, in the following code, `nthcdr 1 80...' returns the list with the first item removed; and the `car' 81returns the first element of that remainder--the second element of the 82original list: 83 84 (car (nthcdr 1 '("another piece" 85 "a piece of text" 86 "previous piece"))) 87 => "a piece of text" 88 89 The actual functions in Emacs are more complex than this, of course. 90The code for cutting and retrieving text has to be written so that 91Emacs can figure out which element in the list you want--the first, 92second, third, or whatever. In addition, when you get to the end of 93the list, Emacs should give you the first element of the list, rather 94than nothing at all. 95 96 The list that holds the pieces of text is called the "kill ring". 97This chapter leads up to a description of the kill ring and how it is 98used by first tracing how the `zap-to-char' function works. This 99function uses (or `calls') a function that invokes a function that 100manipulates the kill ring. Thus, before reaching the mountains, we 101climb the foothills. 102 103 A subsequent chapter describes how text that is cut from the buffer 104is retrieved. *Note Yanking Text Back: Yanking. 105 106 107File: emacs-lisp-intro.info, Node: zap-to-char, Next: kill-region, Prev: Storing Text, Up: Cutting & Storing Text 108 109`zap-to-char' 110============= 111 112 The `zap-to-char' function barely changed between GNU Emacs version 11319 and GNU Emacs version 21. However, `zap-to-char' calls another 114function, `kill-region', which enjoyed a major rewrite on the way to 115version 21. 116 117 The `kill-region' function in Emacs 19 is complex, but does not use 118code that is important at this time. We will skip it. 119 120 The `kill-region' function in Emacs 21 is easier to read than the 121same function in Emacs 19 and introduces a very important concept, that 122of error handling. We will walk through the function. 123 124 But first, let us look at the interactive `zap-to-char' function. 125 126* Menu: 127 128* Complete zap-to-char:: The complete implementation. 129* zap-to-char interactive:: A three part interactive expression. 130* zap-to-char body:: A short overview. 131* search-forward:: How to search for a string. 132* progn:: The `progn' special form. 133* Summing up zap-to-char:: Using `point' and `search-forward'. 134 135 136File: emacs-lisp-intro.info, Node: Complete zap-to-char, Next: zap-to-char interactive, Prev: zap-to-char, Up: zap-to-char 137 138The Complete `zap-to-char' Implementation 139----------------------------------------- 140 141 The GNU Emacs version 19 and version 21 implementations of the 142`zap-to-char' function are nearly identical in form, and they work 143alike. The function removes the text in the region between the 144location of the cursor (i.e., of point) up to and including the next 145occurrence of a specified character. The text that `zap-to-char' 146removes is put in the kill ring; and it can be retrieved from the kill 147ring by typing `C-y' (`yank'). If the command is given an argument, it 148removes text through that number of occurrences. Thus, if the cursor 149were at the beginning of this sentence and the character were `s', 150`Thus' would be removed. If the argument were two, `Thus, if the curs' 151would be removed, up to and including the `s' in `cursor'. 152 153 If the specified character is not found, `zap-to-char' will say 154"Search failed", tell you the character you typed, and not remove any 155text. 156 157 In order to determine how much text to remove, `zap-to-char' uses a 158search function. Searches are used extensively in code that 159manipulates text, and we will focus attention on them as well as on the 160deletion command. 161 162 Here is the complete text of the version 19 implementation of the 163function: 164 165 (defun zap-to-char (arg char) ; version 19 implementation 166 "Kill up to and including ARG'th occurrence of CHAR. 167 Goes backward if ARG is negative; error if CHAR not found." 168 (interactive "*p\ncZap to char: ") 169 (kill-region (point) 170 (progn 171 (search-forward 172 (char-to-string char) nil nil arg) 173 (point)))) 174 175 176File: emacs-lisp-intro.info, Node: zap-to-char interactive, Next: zap-to-char body, Prev: Complete zap-to-char, Up: zap-to-char 177 178The `interactive' Expression 179---------------------------- 180 181 The interactive expression in the `zap-to-char' command looks like 182this: 183 184 (interactive "*p\ncZap to char: ") 185 186 The part within quotation marks, `"*p\ncZap to char: "', specifies 187three different things. First, and most simply, the asterisk, `*', 188causes an error to be signalled if the buffer is read-only. This means 189that if you try `zap-to-char' in a read-only buffer you will not be 190able to remove text, and you will receive a message that says "Buffer is 191read-only"; your terminal may beep at you as well. 192 193 The version 21 implementation does not have the asterisk, `*'. The 194function works the same as in version 19: in both cases, it cannot 195remove text from a read-only buffer but the function does copy the text 196that would have been removed to the kill ring. Also, in both cases, 197you see an error message. 198 199 However, the version 19 implementation copies text from a read-only 200buffer only because of a mistake in the implementation of 201`interactive'. According to the documentation for `interactive', the 202asterisk, `*', should prevent the `zap-to-char' function from doing 203anything at all when the buffer is read only. The function should not 204copy the text to the kill ring. It is a bug that it does. 205 206 In version 21, `interactive' is implemented correctly. So the 207asterisk, `*', had to be removed from the interactive specification. 208If you insert an `*' and evaluate the function definition, then the 209next time you run the `zap-to-char' function on a read-only buffer, you 210will not copy any text. 211 212 That change aside, and a change to the documentation, the two 213versions of the `zap-to-char' function are identical. 214 215 Let us continue with the interactive specification. 216 217 The second part of `"*p\ncZap to char: "' is the `p'. This part is 218separated from the next part by a newline, `\n'. The `p' means that 219the first argument to the function will be passed the value of a 220`processed prefix'. The prefix argument is passed by typing `C-u' and 221a number, or `M-' and a number. If the function is called 222interactively without a prefix, 1 is passed to this argument. 223 224 The third part of `"*p\ncZap to char: "' is `cZap to char: '. In 225this part, the lower case `c' indicates that `interactive' expects a 226prompt and that the argument will be a character. The prompt follows 227the `c' and is the string `Zap to char: ' (with a space after the colon 228to make it look good). 229 230 What all this does is prepare the arguments to `zap-to-char' so they 231are of the right type, and give the user a prompt. 232 233 234File: emacs-lisp-intro.info, Node: zap-to-char body, Next: search-forward, Prev: zap-to-char interactive, Up: zap-to-char 235 236The Body of `zap-to-char' 237------------------------- 238 239 The body of the `zap-to-char' function contains the code that kills 240(that is, removes) the text in the region from the current position of 241the cursor up to and including the specified character. The first part 242of the code looks like this: 243 244 (kill-region (point) ... 245 246`(point)' is the current position of the cursor. 247 248 The next part of the code is an expression using `progn'. The body 249of the `progn' consists of calls to `search-forward' and `point'. 250 251 It is easier to understand how `progn' works after learning about 252`search-forward', so we will look at `search-forward' and then at 253`progn'. 254 255 256File: emacs-lisp-intro.info, Node: search-forward, Next: progn, Prev: zap-to-char body, Up: zap-to-char 257 258The `search-forward' Function 259----------------------------- 260 261 The `search-forward' function is used to locate the 262zapped-for-character in `zap-to-char'. If the search is successful, 263`search-forward' leaves point immediately after the last character in 264the target string. (In `zap-to-char', the target string is just one 265character long.) If the search is backwards, `search-forward' leaves 266point just before the first character in the target. Also, 267`search-forward' returns `t' for true. (Moving point is therefore a 268`side effect'.) 269 270 In `zap-to-char', the `search-forward' function looks like this: 271 272 (search-forward (char-to-string char) nil nil arg) 273 274 The `search-forward' function takes four arguments: 275 276 1. The first argument is the target, what is searched for. This must 277 be a string, such as `"z"'. 278 279 As it happens, the argument passed to `zap-to-char' is a single 280 character. Because of the way computers are built, the Lisp 281 interpreter may treat a single character as being different from a 282 string of characters. Inside the computer, a single character has 283 a different electronic format than a string of one character. (A 284 single character can often be recorded in the computer using 285 exactly one byte; but a string may be longer, and the computer 286 needs to be ready for this.) Since the `search-forward' function 287 searches for a string, the character that the `zap-to-char' 288 function receives as its argument must be converted inside the 289 computer from one format to the other; otherwise the 290 `search-forward' function will fail. The `char-to-string' 291 function is used to make this conversion. 292 293 2. The second argument bounds the search; it is specified as a 294 position in the buffer. In this case, the search can go to the 295 end of the buffer, so no bound is set and the second argument is 296 `nil'. 297 298 3. The third argument tells the function what it should do if the 299 search fails--it can signal an error (and print a message) or it 300 can return `nil'. A `nil' as the third argument causes the 301 function to signal an error when the search fails. 302 303 4. The fourth argument to `search-forward' is the repeat count--how 304 many occurrences of the string to look for. This argument is 305 optional and if the function is called without a repeat count, 306 this argument is passed the value 1. If this argument is 307 negative, the search goes backwards. 308 309 In template form, a `search-forward' expression looks like this: 310 311 (search-forward "TARGET-STRING" 312 LIMIT-OF-SEARCH 313 WHAT-TO-DO-IF-SEARCH-FAILS 314 REPEAT-COUNT) 315 316 We will look at `progn' next. 317 318 319File: emacs-lisp-intro.info, Node: progn, Next: Summing up zap-to-char, Prev: search-forward, Up: zap-to-char 320 321The `progn' Special Form 322------------------------ 323 324 `progn' is a special form that causes each of its arguments to be 325evaluated in sequence and then returns the value of the last one. The 326preceding expressions are evaluated only for the side effects they 327perform. The values produced by them are discarded. 328 329 The template for a `progn' expression is very simple: 330 331 (progn 332 BODY...) 333 334 In `zap-to-char', the `progn' expression has to do two things: put 335point in exactly the right position; and return the location of point 336so that `kill-region' will know how far to kill to. 337 338 The first argument to the `progn' is `search-forward'. When 339`search-forward' finds the string, the function leaves point 340immediately after the last character in the target string. (In this 341case the target string is just one character long.) If the search is 342backwards, `search-forward' leaves point just before the first 343character in the target. The movement of point is a side effect. 344 345 The second and last argument to `progn' is the expression `(point)'. 346This expression returns the value of point, which in this case will be 347the location to which it has been moved by `search-forward'. This 348value is returned by the `progn' expression and is passed to 349`kill-region' as `kill-region''s second argument. 350 351 352File: emacs-lisp-intro.info, Node: Summing up zap-to-char, Prev: progn, Up: zap-to-char 353 354Summing up `zap-to-char' 355------------------------ 356 357 Now that we have seen how `search-forward' and `progn' work, we can 358see how the `zap-to-char' function works as a whole. 359 360 The first argument to `kill-region' is the position of the cursor 361when the `zap-to-char' command is given--the value of point at that 362time. Within the `progn', the search function then moves point to just 363after the zapped-to-character and `point' returns the value of this 364location. The `kill-region' function puts together these two values of 365point, the first one as the beginning of the region and the second one 366as the end of the region, and removes the region. 367 368 The `progn' special form is necessary because the `kill-region' 369command takes two arguments; and it would fail if `search-forward' and 370`point' expressions were written in sequence as two additional 371arguments. The `progn' expression is a single argument to 372`kill-region' and returns the one value that `kill-region' needs for 373its second argument. 374 375 376File: emacs-lisp-intro.info, Node: kill-region, Next: Digression into C, Prev: zap-to-char, Up: Cutting & Storing Text 377 378`kill-region' 379============= 380 381 The `zap-to-char' function uses the `kill-region' function. This 382function clips text from a region and copies that text to the kill 383ring, from which it may be retrieved. 384 385 The Emacs 21 version of that function uses `condition-case' and 386`copy-region-as-kill', both of which we will explain. `condition-case' 387is an important special form. 388 389 In essence, the `kill-region' function calls `condition-case', which 390takes three arguments. In this function, the first argument does 391nothing. The second argument contains the code that does the work when 392all goes well. The third argument contains the code that is called in 393the event of an error. 394 395* Menu: 396 397* Complete kill-region:: The function definition. 398* condition-case:: Dealing with a problem. 399* delete-and-extract-region:: Doing the work. 400 401 402File: emacs-lisp-intro.info, Node: Complete kill-region, Next: condition-case, Prev: kill-region, Up: kill-region 403 404The Complete `kill-region' Definition 405------------------------------------- 406 407 We will go through the `condition-case' code in a moment. First, 408let us look at the complete definition of `kill-region', with comments 409added: 410 411 (defun kill-region (beg end) 412 "Kill between point and mark. 413 The text is deleted but saved in the kill ring." 414 (interactive "r") 415 416 ;; 1. `condition-case' takes three arguments. 417 ;; If the first argument is nil, as it is here, 418 ;; information about the error signal is not 419 ;; stored for use by another function. 420 (condition-case nil 421 422 ;; 2. The second argument to `condition-case' 423 ;; tells the Lisp interpreter what to do when all goes well. 424 425 ;; The `delete-and-extract-region' function usually does the 426 ;; work. If the beginning and ending of the region are both 427 ;; the same, then the variable `string' will be empty, or nil 428 (let ((string (delete-and-extract-region beg end))) 429 430 ;; `when' is an `if' clause that cannot take an `else-part'. 431 ;; Emacs normally sets the value of `last-command' to the 432 ;; previous command. 433 ;; `kill-append' concatenates the new string and the old. 434 ;; `kill-new' inserts text into a new item in the kill ring. 435 (when string 436 (if (eq last-command 'kill-region) 437 ;; if true, prepend string 438 (kill-append string (< end beg)) 439 (kill-new string))) 440 (setq this-command 'kill-region)) 441 442 ;; 3. The third argument to `condition-case' tells the interpreter 443 ;; what to do with an error. 444 ;; The third argument has a conditions part and a body part. 445 ;; If the conditions are met (in this case, 446 ;; if text or buffer is read-only) 447 ;; then the body is executed. 448 ((buffer-read-only text-read-only) ;; this is the if-part 449 ;; then... 450 (copy-region-as-kill beg end) 451 (if kill-read-only-ok ;; usually this variable is nil 452 (message "Read only text copied to kill ring") 453 ;; or else, signal an error if the buffer is read-only; 454 (barf-if-buffer-read-only) 455 ;; and, in any case, signal that the text is read-only. 456 (signal 'text-read-only (list (current-buffer))))))) 457 458 459File: emacs-lisp-intro.info, Node: condition-case, Next: delete-and-extract-region, Prev: Complete kill-region, Up: kill-region 460 461`condition-case' 462---------------- 463 464 As we have seen earlier (*note Generate an Error Message: Making 465Errors.), when the Emacs Lisp interpreter has trouble evaluating an 466expression, it provides you with help; in the jargon, this is called 467"signaling an error". Usually, the computer stops the program and 468shows you a message. 469 470 However, some programs undertake complicated actions. They should 471not simply stop on an error. In the `kill-region' function, the most 472likely error is that you will try to kill text that is read-only and 473cannot be removed. So the `kill-region' function contains code to 474handle this circumstance. This code, which makes up the body of the 475`kill-region' function, is inside of a `condition-case' special form. 476 477 The template for `condition-case' looks like this: 478 479 (condition-case 480 VAR 481 BODYFORM 482 ERROR-HANDLER...) 483 484 The second argument, BODYFORM, is straightforward. The 485`condition-case' special form causes the Lisp interpreter to evaluate 486the code in BODYFORM. If no error occurs, the special form returns the 487code's value and produces the side-effects, if any. 488 489 In short, the BODYFORM part of a `condition-case' expression 490determines what should happen when everything works correctly. 491 492 However, if an error occurs, among its other actions, the function 493generating the error signal will define one or more error condition 494names. 495 496 An error handler is the third argument to `condition case'. An 497error handler has two parts, a CONDITION-NAME and a BODY. If the 498CONDITION-NAME part of an error handler matches a condition name 499generated by an error, then the BODY part of the error handler is run. 500 501 As you will expect, the CONDITION-NAME part of an error handler may 502be either a single condition name or a list of condition names. 503 504 Also, a complete `condition-case' expression may contain more than 505one error handler. When an error occurs, the first applicable handler 506is run. 507 508 Lastly, the first argument to the `condition-case' expression, the 509VAR argument, is sometimes bound to a variable that contains 510information about the error. However, if that argument is nil, as is 511the case in `kill-region', that information is discarded. 512 513 In brief, in the `kill-region' function, the code `condition-case' 514works like this: 515 516 IF NO ERRORS, RUN ONLY THIS CODE 517 BUT, IF ERRORS, RUN THIS OTHER CODE. 518 519 520File: emacs-lisp-intro.info, Node: delete-and-extract-region, Prev: condition-case, Up: kill-region 521 522`delete-and-extract-region' 523--------------------------- 524 525 A `condition-case' expression has two parts, a part that is 526evaluated in the expectation that all will go well, but which may 527generate an error; and a part that is evaluated when there is an error. 528 529 First, let us look at the code in `kill-region' that is run in the 530expectation that all goes well. This is the core of the function. The 531code looks like this: 532 533 (let ((string (delete-and-extract-region beg end))) 534 (when string 535 (if (eq last-command 'kill-region) 536 (kill-append string (< end beg)) 537 (kill-new string))) 538 (setq this-command 'kill-region)) 539 540 It looks complicated because we have the new functions 541`delete-and-extract-region', `kill-append', and `kill-new' as well as 542the new variables, `last-command' and `this-command'. 543 544 The `delete-and-extract-region' function is straightforward. It is 545a built-in function that deletes the text in a region (a side effect) 546and also returns that text. This is the function that actually removes 547the text. (And if it cannot do that, it signals the error.) 548 549 In this `let' expression, the text that `delete-and-extract-region' 550returns is placed in the local variable called `string'. This is the 551text that is removed from the buffer. (To be more precise, the 552variable is set to point to the address of the extracted text; to say 553it is `placed in' the variable is simply a shorthand.) 554 555 If the variable `string' does point to text, that text is added to 556the kill ring. The variable will have a `nil' value if no text was 557removed. 558 559 The code uses `when' to determine whether the variable `string' 560points to text. A `when' statement is simply a programmers' 561convenience. A `when' statement is an `if' statement without the 562possibility of an else clause. In your mind, you can replace `when' 563with `if' and understand what goes on. That is what the Lisp 564interpreter does. 565 566 Technically speaking, `when' is a Lisp macro. A Lisp "macro" 567enables you to define new control constructs and other language 568features. It tells the interpreter how to compute another Lisp 569expression which will in turn compute the value. In this case, the 570`other expression' is an `if' expression. For more about Lisp macros, 571see *Note Macros: (elisp)Macros. The C programming language also 572provides macros. These are different, but also useful. We will 573briefly look at C macros in *Note `delete-and-extract-region': 574Digressing into C: Digression into C. 575 576 If the string has content, then another conditional expression is 577executed. This is an `if' with both a then-part and an else-part. 578 579 (if (eq last-command 'kill-region) 580 (kill-append string (< end beg)) 581 (kill-new string))) 582 583 The then-part is evaluated if the previous command was another call 584to `kill-region'; if not, the else-part is evaluated. 585 586 `last-command' is a variable that comes with Emacs that we have not 587seen before. Normally, whenever a function is executed, Emacs sets the 588value of `last-command' to the previous command. 589 590 In this segment of the definition, the `if' expression checks 591whether the previous command was `kill-region'. If it was, 592 593 (kill-append string (< end beg)) 594 595concatenates a copy of the newly clipped text to the just previously 596clipped text in the kill ring. (If the `(< end beg))' expression is 597true, `kill-append' prepends the string to the just previously clipped 598text. For a detailed discussion, see *Note The `kill-append' function: 599kill-append function.) 600 601 If you then yank back the text, i.e., `paste' it, you get both 602pieces of text at once. That way, if you delete two words in a row, 603and then yank them back, you get both words, in their proper order, 604with one yank. (The `(< end beg))' expression makes sure the order is 605correct.) 606 607 On the other hand, if the previous command is not `kill-region', 608then the `kill-new' function is called, which adds the text to the kill 609ring as the latest item, and sets the `kill-ring-yank-pointer' variable 610to point to it. 611 612 613File: emacs-lisp-intro.info, Node: Digression into C, Next: defvar, Prev: kill-region, Up: Cutting & Storing Text 614 615`delete-and-extract-region': Digressing into C 616============================================== 617 618 The `zap-to-char' command uses the `delete-and-extract-region' 619function, which in turn uses two other functions, `copy-region-as-kill' 620and `del_range_1'. The `copy-region-as-kill' function will be 621described in a following section; it puts a copy of the region in the 622kill ring so it can be yanked back. (*Note `copy-region-as-kill': 623copy-region-as-kill.) 624 625 The `delete-and-extract-region' function removes the contents of a 626region and you cannot get them back. 627 628 Unlike the other code discussed here, `delete-and-extract-region' is 629not written in Emacs Lisp; it is written in C and is one of the 630primitives of the GNU Emacs system. Since it is very simple, I will 631digress briefly from Lisp and describe it here. 632 633 Like many of the other Emacs primitives, `delete-and-extract-region' 634is written as an instance of a C macro, a macro being a template for 635code. The complete macro looks like this: 636 637 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region, 638 Sdelete_and_extract_region, 2, 2, 0, 639 "Delete the text between START and END and return it.") 640 (start, end) 641 Lisp_Object start, end; 642 { 643 validate_region (&start, &end); 644 return del_range_1 (XINT (start), XINT (end), 1, 1); 645 } 646 647 Without going into the details of the macro writing process, let me 648point out that this macro starts with the word `DEFUN'. The word 649`DEFUN' was chosen since the code serves the same purpose as `defun' 650does in Lisp. The word `DEFUN' is followed by seven parts inside of 651parentheses: 652 653 * The first part is the name given to the function in Lisp, 654 `delete-and-extract-region'. 655 656 * The second part is the name of the function in C, 657 `Fdelete_and_extract_region'. By convention, it starts with `F'. 658 Since C does not use hyphens in names, underscores are used 659 instead. 660 661 * The third part is the name for the C constant structure that 662 records information on this function for internal use. It is the 663 name of the function in C but begins with an `S' instead of an `F'. 664 665 * The fourth and fifth parts specify the minimum and maximum number 666 of arguments the function can have. This function demands exactly 667 2 arguments. 668 669 * The sixth part is nearly like the argument that follows the 670 `interactive' declaration in a function written in Lisp: a letter 671 followed, perhaps, by a prompt. The only difference from the Lisp 672 is when the macro is called with no arguments. Then you write a 673 `0' (which is a `null string'), as in this macro. 674 675 If you were to specify arguments, you would place them between 676 quotation marks. The C macro for `goto-char' includes `"NGoto 677 char: "' in this position to indicate that the function expects a 678 raw prefix, in this case, a numerical location in a buffer, and 679 provides a prompt. 680 681 * The seventh part is a documentation string, just like the one for a 682 function written in Emacs Lisp, except that every newline must be 683 written explicitly as `\n' followed by a backslash and carriage 684 return. 685 686 Thus, the first two lines of documentation for `goto-char' are 687 written like this: 688 689 "Set point to POSITION, a number or marker.\n\ 690 Beginning of buffer is position (point-min), end is (point-max). 691 692 In a C macro, the formal parameters come next, with a statement of 693what kind of object they are, followed by what might be called the 694`body' of the macro. For `delete-and-extract-region' the `body' 695consists of the following two lines: 696 697 validate_region (&start, &end); 698 return del_range_1 (XINT (start), XINT (end), 1, 1); 699 700 The first function, `validate_region' checks whether the values 701passed as the beginning and end of the region are the proper type and 702are within range. The second function, `del_range_1', actually deletes 703the text. 704 705 `del_range_1' is a complex function we will not look into. It 706updates the buffer and does other things. 707 708 However, it is worth looking at the two arguments passed to 709`del_range'. These are `XINT (start)' and `XINT (end)'. 710 711 As far as the C language is concerned, `start' and `end' are two 712integers that mark the beginning and end of the region to be deleted(1). 713 714 In early versions of Emacs, these two numbers were thirty-two bits 715long, but the code is slowly being generalized to handle other lengths. 716Three of the available bits are used to specify the type of 717information and a fourth bit is used for handling the computer's 718memory; the remaining bits are used as `content'. 719 720 `XINT' is a C macro that extracts the relevant number from the 721longer collection of bits; the four other bits are discarded. 722 723 The command in `delete-and-extract-region' looks like this: 724 725 del_range_1 (XINT (start), XINT (end), 1, 1); 726 727It deletes the region between the beginning position, `start', and the 728ending position, `end'. 729 730 From the point of view of the person writing Lisp, Emacs is all very 731simple; but hidden underneath is a great deal of complexity to make it 732all work. 733 734 ---------- Footnotes ---------- 735 736 (1) More precisely, and requiring more expert knowledge to 737understand, the two integers are of type `Lisp_Object', which can also 738be a C union instead of an integer type. 739 740 741File: emacs-lisp-intro.info, Node: defvar, Next: copy-region-as-kill, Prev: Digression into C, Up: Cutting & Storing Text 742 743Initializing a Variable with `defvar' 744===================================== 745 746 Unlike the `delete-and-extract-region' function, the 747`copy-region-as-kill' function is written in Emacs Lisp. Two functions 748within it, `kill-append' and `kill-new', copy a region in a buffer and 749save it in a variable called the `kill-ring'. This section describes 750how the `kill-ring' variable is created and initialized using the 751`defvar' special form. 752 753 (Again we note that the term `kill-ring' is a misnomer. The text 754that is clipped out of the buffer can be brought back; it is not a ring 755of corpses, but a ring of resurrectable text.) 756 757 In Emacs Lisp, a variable such as the `kill-ring' is created and 758given an initial value by using the `defvar' special form. The name 759comes from "define variable". 760 761 The `defvar' special form is similar to `setq' in that it sets the 762value of a variable. It is unlike `setq' in two ways: first, it only 763sets the value of the variable if the variable does not already have a 764value. If the variable already has a value, `defvar' does not override 765the existing value. Second, `defvar' has a documentation string. 766 767 (Another special form, `defcustom', is designed for variables that 768people customize. It has more features than `defvar'. (*Note Setting 769Variables with `defcustom': defcustom.) 770 771* Menu: 772 773* See variable current value:: 774* defvar and asterisk:: An old-time convention. 775 776 777File: emacs-lisp-intro.info, Node: See variable current value, Next: defvar and asterisk, Prev: defvar, Up: defvar 778 779Seeing the Current Value of a Variable 780-------------------------------------- 781 782 You can see the current value of a variable, any variable, by using 783the `describe-variable' function, which is usually invoked by typing 784`C-h v'. If you type `C-h v' and then `kill-ring' (followed by <RET>) 785when prompted, you will see what is in your current kill ring--this may 786be quite a lot! Conversely, if you have been doing nothing this Emacs 787session except read this document, you may have nothing in it. Also, 788you will see the documentation for `kill-ring': 789 790 Documentation: 791 List of killed text sequences. 792 Since the kill ring is supposed to interact nicely with cut-and-paste 793 facilities offered by window systems, use of this variable should 794 interact nicely with `interprogram-cut-function' and 795 `interprogram-paste-function'. The functions `kill-new', 796 `kill-append', and `current-kill' are supposed to implement this 797 interaction; you may want to use them instead of manipulating the kill 798 ring directly. 799 800 The kill ring is defined by a `defvar' in the following way: 801 802 (defvar kill-ring nil 803 "List of killed text sequences. 804 ...") 805 806In this variable definition, the variable is given an initial value of 807`nil', which makes sense, since if you have saved nothing, you want 808nothing back if you give a `yank' command. The documentation string is 809written just like the documentation string of a `defun'. As with the 810documentation string of the `defun', the first line of the 811documentation should be a complete sentence, since some commands, like 812`apropos', print only the first line of documentation. Succeeding 813lines should not be indented; otherwise they look odd when you use `C-h 814v' (`describe-variable'). 815 816 817File: emacs-lisp-intro.info, Node: defvar and asterisk, Prev: See variable current value, Up: defvar 818 819`defvar' and an asterisk 820------------------------ 821 822 In the past, Emacs used the `defvar' special form both for internal 823variables that you would not expect a user to change and for variables 824that you do expect a user to change. Although you can still use 825`defvar' for user customizable variables, please use `defcustom' 826instead, since that special form provides a path into the Customization 827commands. (*Note Setting Variables with `defcustom': defcustom.) 828 829 When you specified a variable using the `defvar' special form, you 830could distinguish a readily settable variable from others by typing an 831asterisk, `*', in the first column of its documentation string. For 832example: 833 834 (defvar shell-command-default-error-buffer nil 835 "*Buffer name for `shell-command' ... error output. 836 ... ") 837 838This means that you could (and still can) use the `edit-options' 839command to change the value of `shell-command-default-error-buffer' 840temporarily. 841 842 However, options set using `edit-options' are set only for the 843duration of your editing session. The new values are not saved between 844sessions. Each time Emacs starts, it reads the original value, unless 845you change the value within your `.emacs' file, either by setting it 846manually or by using `customize'. *Note Your `.emacs' File: Emacs 847Initialization. 848 849 For me, the major use of the `edit-options' command is to suggest 850variables that I might want to set in my `.emacs' file. I urge you to 851look through the list. (*Note Editing Variable Values: (emacs)Edit 852Options.) 853 854 855File: emacs-lisp-intro.info, Node: copy-region-as-kill, Next: cons & search-fwd Review, Prev: defvar, Up: Cutting & Storing Text 856 857`copy-region-as-kill' 858===================== 859 860 The `copy-region-as-kill' function copies a region of text from a 861buffer and (via either `kill-append' or `kill-new') saves it in the 862`kill-ring'. 863 864 If you call `copy-region-as-kill' immediately after a `kill-region' 865command, Emacs appends the newly copied text to the previously copied 866text. This means that if you yank back the text, you get it all, from 867both this and the previous operation. On the other hand, if some other 868command precedes the `copy-region-as-kill', the function copies the 869text into a separate entry in the kill ring. 870 871* Menu: 872 873* Complete copy-region-as-kill:: The complete function definition. 874* copy-region-as-kill body:: The body of `copy-region-as-kill'. 875 876 877File: emacs-lisp-intro.info, Node: Complete copy-region-as-kill, Next: copy-region-as-kill body, Prev: copy-region-as-kill, Up: copy-region-as-kill 878 879The complete `copy-region-as-kill' function definition 880------------------------------------------------------ 881 882 Here is the complete text of the version 21 `copy-region-as-kill' 883function: 884 885 (defun copy-region-as-kill (beg end) 886 "Save the region as if killed, but don't kill it. 887 In Transient Mark mode, deactivate the mark. 888 If `interprogram-cut-function' is non-nil, also save 889 the text for a window system cut and paste." 890 (interactive "r") 891 (if (eq last-command 'kill-region) 892 (kill-append (buffer-substring beg end) (< end beg)) 893 (kill-new (buffer-substring beg end))) 894 (if transient-mark-mode 895 (setq deactivate-mark t)) 896 nil) 897 898 As usual, this function can be divided into its component parts: 899 900 (defun copy-region-as-kill (ARGUMENT-LIST) 901 "DOCUMENTATION..." 902 (interactive "r") 903 BODY...) 904 905 The arguments are `beg' and `end' and the function is interactive 906with `"r"', so the two arguments must refer to the beginning and end of 907the region. If you have been reading though this document from the 908beginning, understanding these parts of a function is almost becoming 909routine. 910 911 The documentation is somewhat confusing unless you remember that the 912word `kill' has a meaning different from its usual meaning. The 913`Transient Mark' and `interprogram-cut-function' comments explain 914certain side-effects. 915 916 After you once set a mark, a buffer always contains a region. If you 917wish, you can use Transient Mark mode to highlight the region 918temporarily. (No one wants to highlight the region all the time, so 919Transient Mark mode highlights it only at appropriate times. Many 920people turn off Transient Mark mode, so the region is never 921highlighted.) 922 923 Also, a windowing system allows you to copy, cut, and paste among 924different programs. In the X windowing system, for example, the 925`interprogram-cut-function' function is `x-select-text', which works 926with the windowing system's equivalent of the Emacs kill ring. 927 928 The body of the `copy-region-as-kill' function starts with an `if' 929clause. What this clause does is distinguish between two different 930situations: whether or not this command is executed immediately after a 931previous `kill-region' command. In the first case, the new region is 932appended to the previously copied text. Otherwise, it is inserted into 933the beginning of the kill ring as a separate piece of text from the 934previous piece. 935 936 The last two lines of the function prevent the region from lighting 937up if Transient Mark mode is turned on. 938 939 The body of `copy-region-as-kill' merits discussion in detail. 940 941 942File: emacs-lisp-intro.info, Node: copy-region-as-kill body, Prev: Complete copy-region-as-kill, Up: copy-region-as-kill 943 944The Body of `copy-region-as-kill' 945--------------------------------- 946 947 The `copy-region-as-kill' function works in much the same way as the 948`kill-region' function (*note `kill-region': kill-region.). Both are 949written so that two or more kills in a row combine their text into a 950single entry. If you yank back the text from the kill ring, you get it 951all in one piece. Moreover, kills that kill forward from the current 952position of the cursor are added to the end of the previously copied 953text and commands that copy text backwards add it to the beginning of 954the previously copied text. This way, the words in the text stay in 955the proper order. 956 957 Like `kill-region', the `copy-region-as-kill' function makes use of 958the `last-command' variable that keeps track of the previous Emacs 959command. 960 961* Menu: 962 963* last-command & this-command:: 964* kill-append function:: 965* kill-new function:: 966 967 968File: emacs-lisp-intro.info, Node: last-command & this-command, Next: kill-append function, Prev: copy-region-as-kill body, Up: copy-region-as-kill body 969 970`last-command' and `this-command' 971................................. 972 973 Normally, whenever a function is executed, Emacs sets the value of 974`this-command' to the function being executed (which in this case would 975be `copy-region-as-kill'). At the same time, Emacs sets the value of 976`last-command' to the previous value of `this-command'. 977 978 In the first part of the body of the `copy-region-as-kill' function, 979an `if' expression determines whether the value of `last-command' is 980`kill-region'. If so, the then-part of the `if' expression is 981evaluated; it uses the `kill-append' function to concatenate the text 982copied at this call to the function with the text already in the first 983element (the CAR) of the kill ring. On the other hand, if the value of 984`last-command' is not `kill-region', then the `copy-region-as-kill' 985function attaches a new element to the kill ring using the `kill-new' 986function. 987 988 The `if' expression reads as follows; it uses `eq', which is a 989function we have not yet seen: 990 991 (if (eq last-command 'kill-region) 992 ;; then-part 993 (kill-append (buffer-substring beg end) (< end beg)) 994 ;; else-part 995 (kill-new (buffer-substring beg end))) 996 997The `eq' function tests whether its first argument is the same Lisp 998object as its second argument. The `eq' function is similar to the 999`equal' function in that it is used to test for equality, but differs 1000in that it determines whether two representations are actually the same 1001object inside the computer, but with different names. `equal' 1002determines whether the structure and contents of two expressions are 1003the same. 1004 1005 If the previous command was `kill-region', then the Emacs Lisp 1006interpreter calls the `kill-append' function 1007 1008 1009File: emacs-lisp-intro.info, Node: kill-append function, Next: kill-new function, Prev: last-command & this-command, Up: copy-region-as-kill body 1010 1011The `kill-append' function 1012.......................... 1013 1014 The `kill-append' function looks like this: 1015 1016 (defun kill-append (string before-p) 1017 "Append STRING to the end of the latest kill in the kill ring. 1018 If BEFORE-P is non-nil, prepend STRING to the kill. 1019 If `interprogram-cut-function' is set, pass the resulting kill to 1020 it." 1021 (kill-new (if before-p 1022 (concat string (car kill-ring)) 1023 (concat (car kill-ring) string)) 1024 t)) 1025 1026The `kill-append' function is fairly straightforward. It uses the 1027`kill-new' function, which we will discuss in more detail in a moment. 1028 1029 First, let us look at the conditional that is one of the two 1030arguments to `kill-new'. It uses `concat' to concatenate the new text 1031to the CAR of the kill ring. Whether it prepends or appends the text 1032depends on the results of an `if' expression: 1033 1034 (if before-p ; if-part 1035 (concat string (car kill-ring)) ; then-part 1036 (concat (car kill-ring) string)) ; else-part 1037 1038If the region being killed is before the region that was killed in the 1039last command, then it should be prepended before the material that was 1040saved in the previous kill; and conversely, if the killed text follows 1041what was just killed, it should be appended after the previous text. 1042The `if' expression depends on the predicate `before-p' to decide 1043whether the newly saved text should be put before or after the 1044previously saved text. 1045 1046 The symbol `before-p' is the name of one of the arguments to 1047`kill-append'. When the `kill-append' function is evaluated, it is 1048bound to the value returned by evaluating the actual argument. In this 1049case, this is the expression `(< end beg)'. This expression does not 1050directly determine whether the killed text in this command is located 1051before or after the kill text of the last command; what is does is 1052determine whether the value of the variable `end' is less than the 1053value of the variable `beg'. If it is, it means that the user is most 1054likely heading towards the beginning of the buffer. Also, the result 1055of evaluating the predicate expression, `(< end beg)', will be true and 1056the text will be prepended before the previous text. On the other 1057hand, if the value of the variable `end' is greater than the value of 1058the variable `beg', the text will be appended after the previous text. 1059 1060 When the newly saved text will be prepended, then the string with 1061the new text will be concatenated before the old text: 1062 1063 (concat string (car kill-ring)) 1064 1065But if the text will be appended, it will be concatenated after the old 1066text: 1067 1068 (concat (car kill-ring) string)) 1069 1070 To understand how this works, we first need to review the `concat' 1071function. The `concat' function links together or unites two strings 1072of text. The result is a string. For example: 1073 1074 (concat "abc" "def") 1075 => "abcdef" 1076 1077 (concat "new " 1078 (car '("first element" "second element"))) 1079 => "new first element" 1080 1081 (concat (car 1082 '("first element" "second element")) " modified") 1083 => "first element modified" 1084 1085 We can now make sense of `kill-append': it modifies the contents of 1086the kill ring. The kill ring is a list, each element of which is saved 1087text. The `kill-append' function uses the `kill-new' function which in 1088turn uses the `setcar' function. 1089 1090