unofficial mirror of emacs-devel@gnu.org 
 help / color / mirror / code / Atom feed
* displaying margins leads to Emacs hanging
@ 2023-02-24 19:29 dalanicolai
  2023-02-24 19:41 ` Eli Zaretskii
  0 siblings, 1 reply; 14+ messages in thread
From: dalanicolai @ 2023-02-24 19:29 UTC (permalink / raw)
  To: Emacs Devel


[-- Attachment #1.1: Type: text/plain, Size: 1869 bytes --]

I am encountering the problem as described in the subject of this email.

I hope you could enlighten me again about this issue.

Some brief context:
I am trying to build a kind of swiper/swoop for searching documents.
I have tried to use Ivy/Vertico (see
https://github.com/minad/consult/issues/625),
but I think they are not well suited/too heavy for this. So, I concluded
that,
unfortunately, I have to 'reinvent the wheel'.

Anyway, to reproduce the issue starting from emacs -q,
please load the attached file and do `M-x baleen` (the file is large because
it includes the text of `An Introduction to Programming in Emacs Lisp`).
Then type 'ho' and optionally continue typing to narrow down the results.
Press RET to finish (I am just starting development, so never mind further
'testing' the current functionality. Although of course, suggestions for
improvements are welcome).
As you will find, hopefully, things seem to work fine.
Page numbers are nicely displayed in the margins.

Now, do `M-x baleen2`. This time, the data consists of the contents of the
the book `An Introduction to Programming in Emacs Lisp.' Now type e.g.
'emacs' to narrow down the results. The page numbers are not displayed
in the margins, to show that things still work fine.

NOTE the next step should (well, should not of course) make Emacs hang:

Now just uncomment the line
  ;; (set-window-margins nil 4)
in the function `baleen2` and repeat the last step (`M-x baleen2`).
Again, try to type 'emacs'. Unfortunately, Emacs more or less hangs.

I have no idea why suddenly Emacs hangs. I was wondering if any of
you could explain this behavior, and hopefully suggest how to
prevent it.
(Of course, if there is no other solution, then I could just display the
page numbers in the buffer text).

I also have a second question, but I will send it in another mail (with its
own subject).

[-- Attachment #1.2: Type: text/html, Size: 2443 bytes --]

[-- Attachment #2: baleen.el --]
[-- Type: text/x-emacs-lisp, Size: 856423 bytes --]

;;; baleen.el --- Search documents by filtering.     -*- lexical-binding: t; -*-

;; Copyright (C) 2023  Daniel Nicolai

;; Author: Daniel Nicolai <dalanicolai@gmail.com>
;; Keywords: tools

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; 

;;; Code:
(require 'cl-lib)
(require 'page-break-lines nil t)

(defun baleen-render (data)
  (dolist (page data)
    (let* ((props (cdr page))
           (max (1- (length props))))
      (seq-do-indexed (lambda (match i)
                        (let ((o (make-overlay (point)
                                               (progn (progn (insert (nth 4 match))
                                                             (point))))))
                          (overlay-put o
                                       'before-string (propertize " "
                                                                  'display `((margin left-margin)
                                                                             ,(propertize (format " %3d" (car page))
                                                                                          'face 'bold))
                                                                  )))
                        ;; (unless (= i max) (insert "\n")))
                      (insert "\n"))
                      props))
    (insert "\f\n")))

(defun baleen-filter-page (data query)
  (seq-filter (lambda (c)
               (string-match-p query (nth 4 c)))
             (cdr data)))

;; (baleen-filter-page (car test) "eig")

(defun baleen-filter (data query)
  (nreverse
   (seq-reduce (lambda (v p)
                 (if-let (m (baleen-filter-page p query))
                     (cons (cons (car p) m)
                           v)
                   v))
               data
               nil)))

;; (baleen-filter test "q")

(defun baleen-update ()
  (let* ((query (minibuffer-contents))
         (query-length (length query))
         (parent-results (unless (< query-length 2)
                             (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
         (current-results (if parent-results
                              (baleen-filter parent-results query)
                            (unless (string-empty-p query) (baleen-filter test query)))))
    (when current-results
      (with-current-buffer (get-buffer-create "*baleen*")
        (erase-buffer)
        (baleen-render current-results))
      (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))))

(defun baleen ()
  (interactive)
  (pop-to-buffer "*baleen*")
  (set-window-margins nil 4)
  (when (featurep 'page-break-lines)
    (page-break-lines-mode))
  (minibuffer-with-setup-hook
      (lambda ()
        (add-hook 'post-command-hook #'baleen-update nil t))
    (dlet (baleen-results)
      (read-string "Baleen: ")
      (pp baleen-results)))
  (kill-buffer "*baleen*"))

;; NOTE alternatively use doc-pymupdf-text-blocks
(setq test '((1 (1 2 3 4 "hello")
                (2 3 4 5 "hoi"))
             (2 (3 4 2 4 "how do"))))

(defun baleen-update2 ()
  ;; (let ((query (minibuffer-contents)))
  ;;   (with-current-buffer (get-buffer-create "*baleen*")
  ;;     (erase-buffer)
  ;;     (baleen-render (baleen-filter test2 query)))))
  (let* ((query (minibuffer-contents))
         (query-length (length query)))
    (if (> (length previous-query) query-length)
        (with-current-buffer (get-buffer-create "*baleen*")
          (erase-buffer)
          (baleen-render (cdr (alist-get query baleen-results nil nil #'string=))))
      (let* ((parent-results (unless (< query-length 2)
                               (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
             (current-results (if parent-results
                                  (baleen-filter parent-results query)
                                (unless (string-empty-p query) (baleen-filter test2 query)))))
        (when current-results
          (with-current-buffer (get-buffer-create "*baleen*")
            (erase-buffer)
            (baleen-render current-results))
          (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))

        (setq previous-query query)))))

(defun baleen2 ()
  (interactive)
  (pop-to-buffer "*baleen*")
  (buffer-disable-undo)
  ;; (set-window-margins nil 4)
  (when (featurep 'page-break-lines)
    (page-break-lines-mode))
  (minibuffer-with-setup-hook
      (lambda ()
        (add-hook 'post-command-hook #'baleen-update2 nil t))
    (dlet (previous-query
           baleen-results)
      (read-string "Baleen: ")
      (print (length baleen-results))))
  (kill-buffer "*baleen*"))

;; NOTE alternatively use doc-pymupdf-text-blocks
(setq test2
      '((1 (189.0 195.02845764160156 350.99603271484375 212.2610626220703 "An Introduction to
" 0 0) (149.28021240234375 237.02845764160156 390.6446228027344 254.2610626220703 "Programming in Emacs Lisp
" 1 0)) (3 (172.8000030517578 267.5661315917969 367.04559326171875 288.2452697753906 "An Introduction to
" 0 0) (125.160400390625 306.9261169433594 414.5801696777344 327.6052551269531 "Programming in Emacs Lisp
" 1 0) (233.8809051513672 347.60906982421875 305.9354553222656 360.9072570800781 "Second Edition
" 2 0) (218.40089416503906 407.48907470703125 321.4480895996094 420.7872619628906 "by Robert J. Chassell
" 3 0)) (4 (89.999755859375 389.84906005859375 449.3995666503906 415.38726806640625 "Copyright c⃝ 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002 Free
Software Foundation, Inc.
" 0 0) (89.99954223632812 440.00909423828125 321.0759582519531 477.1872863769531 "Published by the Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA
" 1 0) (89.99752807617188 489.8091125488281 449.4958190917969 628.6273803710938 "Edition 2.05, 2001 Jan 5
ISBN 1-882114-43-4
Permission is granted to copy, distribute and/or modify this document under
the terms of the GNU Free Documentation License, Version 1.1 or any later
version published by the Free Software Foundation; there being no Invariant
Section, with the Front-Cover Texts being “A GNU Manual”, and with the
Back-Cover Texts as in (a) below. A copy of the license is included in the
section entitled “GNU Free Documentation License”.
(a) The FSF’s Back-Cover Text is: “You have freedom to copy and modify
this GNU Manual, like GNU software. Copies published by the Free Software
Foundation raise funds for GNU development.”
" 2 0)) (5 (446.760009765625 49.213592529296875 450.0118103027344 61.180747985839844 "i
" 0 0) (90.0 75.14844512939453 219.12728881835938 92.38106536865234 "Short Contents
" 1 0) (89.99615478515625 106.16294860839844 449.7834167480469 510.0864562988281 "Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1
List Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2
Practicing Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3
How To Write Function Definitions . . . . . . . . . . . . . . . . . . 29
4
A Few Buffer–Related Functions . . . . . . . . . . . . . . . . . . . . 51
5
A Few More Complex Functions . . . . . . . . . . . . . . . . . . . . 63
6
Narrowing and Widening . . . . . . . . . . . . . . . . . . . . . . . . . 77
7
car, cdr, cons: Fundamental Functions . . . . . . . . . . . . . 81
8
Cutting and Storing Text. . . . . . . . . . . . . . . . . . . . . . . . . 89
9
How Lists are Implemented. . . . . . . . . . . . . . . . . . . . . . . 113
10
Yanking Text Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
11
Loops and Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
12
Regular Expression Searches . . . . . . . . . . . . . . . . . . . . . . 149
13
Counting: Repetition and Regexps. . . . . . . . . . . . . . . . . . 167
14
Counting Words in a defun. . . . . . . . . . . . . . . . . . . . . . 181
15
Readying a Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
16
Your ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
18
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Appendix A
The the-the Function . . . . . . . . . . . . . . . . . . 241
Appendix B
Handling the Kill Ring . . . . . . . . . . . . . . . . . . . 243
Appendix C
A Graph with Labelled Axes . . . . . . . . . . . . . . . 255
Appendix D
GNU Free Documentation License . . . . . . . . . . . 279
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
" 2 0)) (6 (90.0 49.213592529296875 96.4916763305664 61.180747985839844 "ii
" 0 0)) (7 (440.8800048828125 47.60907745361328 449.89093017578125 60.90726852416992 "iii
" 0 0) (90.0 75.14844512939453 240.67727661132812 92.38106536865234 "Table of Contents
" 1 0) (90.00009155273438 117.08299255371094 449.61639404296875 193.38731384277344 "Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
On Reading this Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
For Whom This is Written. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Lisp History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
A Note for Novices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Thank You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv
" 2 0) (90.000732421875 207.6830291748047 449.66815185546875 535.1473999023438 "1
List Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1
Lisp Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1
Lisp Atoms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2
Whitespace in Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3
GNU Emacs Helps You Type Lists . . . . . . . . . . . . . . . 3
1.2
Run a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3
Generate an Error Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4
Symbol Names and Function Definitions . . . . . . . . . . . . . . . . . . 6
1.5
The Lisp Interpreter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5.1
Byte Compiling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6
Evaluation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6.1
Evaluating Inner Lists . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7.1
Error Message for a Symbol Without a Function. . 11
1.7.2
Error Message for a Symbol Without a Value . . . . 11
1.8
Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8.1
Arguments’ Data Types . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8.2
An Argument as the Value of a Variable or List . . 13
1.8.3
Variable Number of Arguments . . . . . . . . . . . . . . . . . 14
1.8.4
Using the Wrong Type Object as an Argument . . 14
1.8.5
The message Function . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9
Setting the Value of a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9.1
Using set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9.2
Using setq. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.9.3
Counting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.10
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.11
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
" 3 0) (90.00164794921875 549.443115234375 449.662109375 625.7474365234375 "2
Practicing Evaluation . . . . . . . . . . . . . . . . . . . . . 23
2.1
Buffer Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2
Getting Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3
Switching Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4
Buffer Size and the Location of Point . . . . . . . . . . . . . . . . . . . . 27
2.5
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
" 4 0)) (8 (90.0 47.60907745361328 98.74909210205078 60.90726852416992 "iv
" 0 0) (90.0 71.24296569824219 449.7541198730469 314.9472961425781 "3
How To Write Function Definitions . . . . . . . . 29
3.1
The defun Special Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2
Install a Function Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1
Change a Function Definition. . . . . . . . . . . . . . . . . . . 32
3.3
Make a Function Interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.1
An Interactive multiply-by-seven .. . . . . . . . . . . . 34
3.4
Different Options for interactive . . . . . . . . . . . . . . . . . . . . . . 35
3.5
Install Code Permanently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6
let . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6.1
The Parts of a let Expression . . . . . . . . . . . . . . . . . . 37
3.6.2
Sample let Expression. . . . . . . . . . . . . . . . . . . . . . . . . 38
3.6.3
Uninitialized Variables in a let Statement. . . . . . . 39
3.7
The if Special Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7.1
The type-of-animal Function in Detail. . . . . . . . . 41
3.8
If–then–else Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.9
Truth and Falsehood in Emacs Lisp . . . . . . . . . . . . . . . . . . . . . 43
3.10
save-excursion .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.10.1
Template for a save-excursion Expression . . . . 45
3.11
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.12
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
" 1 0) (90.00115966796875 329.24298095703125 449.7353210449219 465.30731201171875 "4
A Few Buffer–Related Functions. . . . . . . . . . . 51
4.1
Finding More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.2
A Simplified beginning-of-buffer Definition. . . . . . . . . . . . 52
4.3
The Definition of mark-whole-buffer . . . . . . . . . . . . . . . . . . . 54
4.3.1
Body of mark-whole-buffer .. . . . . . . . . . . . . . . . . . 55
4.4
The Definition of append-to-buffer . . . . . . . . . . . . . . . . . . . . 56
4.4.1
The append-to-buffer Interactive Expression. . . 57
4.4.2
The Body of append-to-buffer .. . . . . . . . . . . . . . . 57
4.4.3
save-excursion in append-to-buffer.. . . . . . . . . 58
4.5
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.6
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
" 2 0)) (9 (444.239990234375 47.60907745361328 450.0 60.90726852416992 "v
" 0 0) (90.0 71.24296569824219 449.7479553222656 291.0672912597656 "5
A Few More Complex Functions . . . . . . . . . . . 63
5.1
The Definition of copy-to-buffer.. . . . . . . . . . . . . . . . . . . . . . 63
5.2
The Definition of insert-buffer.. . . . . . . . . . . . . . . . . . . . . . . 64
5.2.1
The Interactive Expression in insert-buffer.. . . 65
A Read-only Buffer. . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
‘b’ in an Interactive Expression. . . . . . . . . . . . . . . . . 65
5.2.2
The Body of the insert-buffer Function . . . . . . . 65
5.2.3
insert-buffer With an if Instead of an or. . . . . 66
5.2.4
The or in the Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.2.5
The let Expression in insert-buffer .. . . . . . . . . 68
5.3
Complete Definition of beginning-of-buffer .. . . . . . . . . . . 69
5.3.1
Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.3.2
beginning-of-buffer with an Argument . . . . . . . 71
What happens in a large buffer. . . . . . . . . . . . . . . . . 71
What happens in a small buffer . . . . . . . . . . . . . . . . 72
5.3.3
The Complete beginning-of-buffer .. . . . . . . . . . 73
5.4
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.5
optional Argument Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
" 1 0) (89.99783325195312 305.3630065917969 449.7347106933594 357.7873229980469 "6
Narrowing and Widening. . . . . . . . . . . . . . . . . . 77
6.1
The save-restriction Special Form . . . . . . . . . . . . . . . . . . . . 77
6.2
what-line.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.3
Exercise with Narrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
" 2 0) (89.9976806640625 372.0830078125 449.7032775878906 484.267333984375 "7
car, cdr, cons: Fundamental Functions . . . . . 81
7.1
car and cdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.2
cons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2.1
Find the Length of a List: length . . . . . . . . . . . . . . 84
7.3
nthcdr .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.4
nth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.5
setcar .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.6
setcdr .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.7
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
" 3 0)) (10 (90.0 47.60907745361328 98.78182220458984 60.90726852416992 "vi
" 0 0) (90.0 71.24296569824219 449.7066650390625 302.9472961425781 "8
Cutting and Storing Text . . . . . . . . . . . . . . . . . 89
8.1
zap-to-char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.1.1
The interactive Expression . . . . . . . . . . . . . . . . . . . 90
8.1.2
The Body of zap-to-char.. . . . . . . . . . . . . . . . . . . . . 91
8.1.3
The search-forward Function . . . . . . . . . . . . . . . . . 92
8.1.4
The progn Special Form . . . . . . . . . . . . . . . . . . . . . . . 93
8.1.5
Summing up zap-to-char . . . . . . . . . . . . . . . . . . . . . 93
8.2
kill-region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.2.1
condition-case.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.2.2
delete-and-extract-region . . . . . . . . . . . . . . . . . . 96
8.3
delete-and-extract-region: Digressing into C . . . . . . . . . 98
8.4
Initializing a Variable with defvar . . . . . . . . . . . . . . . . . . . . . 100
8.4.1
defvar and an asterisk. . . . . . . . . . . . . . . . . . . . . . . . 101
8.5
copy-region-as-kill.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.5.1
The Body of copy-region-as-kill.. . . . . . . . . . . 103
The kill-append function. . . . . . . . . . . . . . . . . . . . 104
The kill-new function . . . . . . . . . . . . . . . . . . . . . . . 105
8.6
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.7
Searching Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
" 1 0) (90.00201416015625 317.3630065917969 449.6243896484375 357.7873229980469 "9
How Lists are Implemented . . . . . . . . . . . . . . 113
9.1
Symbols as a Chest of Drawers . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.2
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
" 2 0) (90.00247192382812 372.0830078125 449.5589599609375 424.50732421875 "10
Yanking Text Back . . . . . . . . . . . . . . . . . . . . . 117
10.1
Kill Ring Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.2
The kill-ring-yank-pointer Variable . . . . . . . . . . . . . . . 117
10.3
Exercises with yank and nthcdr. . . . . . . . . . . . . . . . . . . . . . . 119
" 3 0) (90.00210571289062 438.9230041503906 449.5998229980469 622.7473754882812 "11
Loops and Recursion. . . . . . . . . . . . . . . . . . . . 121
11.1
while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
11.1.1
A while Loop and a List. . . . . . . . . . . . . . . . . . . . . 122
11.1.2
An Example: print-elements-of-list . . . . . . 123
11.1.3
A Loop with an Incrementing Counter . . . . . . . . 124
Example with incrementing counter . . . . . . . . . . . 125
The parts of the function definition. . . . . . . . . . . . 126
Putting the function definition together . . . . . . . . 127
11.1.4
Loop with a Decrementing Counter . . . . . . . . . . . 129
Example with decrementing counter . . . . . . . . . . . 129
The parts of the function definition. . . . . . . . . . . . 130
Putting the function definition together . . . . . . . . 130
11.2
Save your time: dolist and dotimes . . . . . . . . . . . . . . . . . . 131
The dolist Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
The dotimes Macro . . . . . . . . . . . . . . . . . . . . . . . . . . 133
" 4 0)) (11 (438.239990234375 47.60907745361328 450.0108947753906 60.90726852416992 "vii
" 0 0) (125.8800048828125 71.48908233642578 449.4754333496094 240.1873016357422 "11.3
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
11.3.1
Building Robots: Extending the Metaphor. . . . . 134
11.3.2
The Parts of a Recursive Definition . . . . . . . . . . . 135
11.3.3
Recursion with a List . . . . . . . . . . . . . . . . . . . . . . . . 136
11.3.4
Recursion in Place of a Counter . . . . . . . . . . . . . . 137
An argument of 3 or 4. . . . . . . . . . . . . . . . . . . . . . . . 138
11.3.5
Recursion Example Using cond . . . . . . . . . . . . . . . 139
11.3.6
Recursive Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Recursive Pattern: every . . . . . . . . . . . . . . . . . . . . . 141
Recursive Pattern: accumulate . . . . . . . . . . . . . . . . 142
Recursive Pattern: keep . . . . . . . . . . . . . . . . . . . . . . 143
11.3.7
Recursion without Deferments . . . . . . . . . . . . . . . . 143
11.3.8
No Deferment Solution. . . . . . . . . . . . . . . . . . . . . . . 145
11.4
Looping Exercise. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
" 1 0) (90.00149536132812 254.60301208496094 449.6435241699219 462.4273376464844 "12
Regular Expression Searches . . . . . . . . . . . . 149
12.1
The Regular Expression for sentence-end .. . . . . . . . . . . . 149
12.2
The re-search-forward Function. . . . . . . . . . . . . . . . . . . . . 150
12.3
forward-sentence .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
The while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
The regular expression search . . . . . . . . . . . . . . . . . . . . . . . . 154
12.4
forward-paragraph: a Goldmine of Functions . . . . . . . . . 155
The let* expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
The forward motion while loop . . . . . . . . . . . . . . . . . . . . . . 158
Between paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Within paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
No fill prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
With a fill prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Summary.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12.5
Create Your Own ‘TAGS’ File. . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.6
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.7
Exercises with re-search-forward.. . . . . . . . . . . . . . . . . . . 166
" 2 0) (90.00076293945312 476.7230224609375 449.64251708984375 541.02734375 "13
Counting: Repetition and Regexps . . . . . . 167
13.1
The count-words-region Function . . . . . . . . . . . . . . . . . . . 167
13.1.1
The Whitespace Bug in count-words-region.. 170
13.2
Count Words Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
13.3
Exercise: Counting Punctuation . . . . . . . . . . . . . . . . . . . . . . . 179
" 3 0)) (12 (90.0 47.60907745361328 104.76000213623047 60.90726852416992 "viii
" 0 0) (90.0 71.24296569824219 449.6117858886719 243.1873016357422 "14
Counting Words in a defun . . . . . . . . . . . . . . 181
14.1
What to Count? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.2
What Constitutes a Word or Symbol? . . . . . . . . . . . . . . . . . 182
14.3
The count-words-in-defun Function . . . . . . . . . . . . . . . . . 183
14.4
Count Several defuns Within a File . . . . . . . . . . . . . . . . . . . 186
14.5
Find a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
14.6
lengths-list-file in Detail . . . . . . . . . . . . . . . . . . . . . . . . . 188
14.7
Count Words in defuns in Different Files . . . . . . . . . . . . . . 190
14.7.1
The append Function . . . . . . . . . . . . . . . . . . . . . . . . 191
14.8
Recursively Count Words in Different Files. . . . . . . . . . . . . 192
14.9
Prepare the Data for Display in a Graph . . . . . . . . . . . . . . . 193
14.9.1
Sorting Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
14.9.2
Making a List of Files. . . . . . . . . . . . . . . . . . . . . . . . 194
14.9.3
Counting function definitions . . . . . . . . . . . . . . . . . 197
" 1 0) (89.99942016601562 257.6029968261719 449.582275390625 321.9073181152344 "15
Readying a Graph . . . . . . . . . . . . . . . . . . . . . . 203
15.1
The graph-body-print Function. . . . . . . . . . . . . . . . . . . . . . 208
15.2
The recursive-graph-body-print Function. . . . . . . . . . . 210
15.3
Need for Printed Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
15.4
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
" 2 0) (89.99984741210938 336.2030029296875 449.5562744140625 520.1473388671875 "16
Your ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . 213
16.1
Site-wide Initialization Files. . . . . . . . . . . . . . . . . . . . . . . . . . . 213
16.2
Specifying Variables using defcustom.. . . . . . . . . . . . . . . . . 214
16.3
Beginning a ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
16.4
Text and Auto Fill Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
16.5
Mail Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.6
Indent Tabs Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.7
Some Keybindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
16.8
Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
16.9
Loading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
16.10
Autoloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
16.11
A Simple Extension: line-to-top-of-window . . . . . . . . 224
16.12
X11 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
16.13
Miscellaneous Settings for a ‘.emacs’ File . . . . . . . . . . . . . 227
16.14
A Modified Mode Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
" 3 0) (90.00198364257812 534.5630493164062 449.5606689453125 610.8673706054688 "17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
17.1
debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
17.2
debug-on-entry .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
17.3
debug-on-quit and (debug).. . . . . . . . . . . . . . . . . . . . . . . . . 234
17.4
The edebug Source Level Debugger. . . . . . . . . . . . . . . . . . . . 235
17.5
Debugging Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
" 4 0)) (13 (441.239990234375 47.60907745361328 449.9891052246094 60.90726852416992 "ix
" 0 0) (90.0 71.24296569824219 449.5467834472656 85.66089630126953 "18
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
" 1 0) (90.0001220703125 102.08299255371094 449.6182556152344 116.51359558105469 "Appendix A
The the-the Function. . . . . . . . . . 241
" 2 0) (89.99960327148438 133.0430145263672 449.6458740234375 269.1073303222656 "Appendix B
Handling the Kill Ring . . . . . . . . 243
B.1
The rotate-yank-pointer Function . . . . . . . . . . . . . . . . . . . 243
B.1.1
The Body of rotate-yank-pointer .. . . . . . . . . . 244
The else-part of the if expression . . . . . . . . . . . . . 245
The % remainder function . . . . . . . . . . . . . . . . . . . . . 247
Using % in rotate-yank-pointer . . . . . . . . . . . . . 248
Pointing to the last element. . . . . . . . . . . . . . . . . . . 248
B.2
yank.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Passing the argument . . . . . . . . . . . . . . . . . . . . . . . . 250
Passing a negative argument . . . . . . . . . . . . . . . . . . 251
B.3
yank-pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
" 3 0) (90.0001220703125 283.4030456542969 449.68988037109375 479.3473815917969 "Appendix C
A Graph with Labelled Axes. . . 255
C.1
The print-graph Varlist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
C.2
The print-Y-axis Function. . . . . . . . . . . . . . . . . . . . . . . . . . . 256
C.2.1
Side Trip: Compute a Remainder. . . . . . . . . . . . . . 258
C.2.2
Construct a Y Axis Element . . . . . . . . . . . . . . . . . . 259
C.2.3
Create a Y Axis Column. . . . . . . . . . . . . . . . . . . . . . 261
C.2.4
The Not Quite Final Version of print-Y-axis.. 262
C.3
The print-X-axis Function. . . . . . . . . . . . . . . . . . . . . . . . . . . 263
C.3.1
X Axis Tic Marks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
C.4
Printing the Whole Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
C.4.1
Testing print-graph .. . . . . . . . . . . . . . . . . . . . . . . . 270
C.4.2
Graphing Numbers of Words and Symbols . . . . . 271
C.4.3
A lambda Expression: Useful Anonymity. . . . . . . 272
C.4.4
The mapcar Function. . . . . . . . . . . . . . . . . . . . . . . . . 274
C.4.5
Another Bug . . . Most Insidious . . . . . . . . . . . . . . 274
C.4.6
The Printed Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . 277
" 4 0) (89.99880981445312 493.7004699707031 449.52435302734375 524.02099609375 "Appendix D
GNU Free Documentation License
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
" 5 0) (89.99868774414062 540.443115234375 449.5042724609375 554.8610229492188 "Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
" 6 0)) (14 (90.0 47.60907745361328 95.76000213623047 60.90726852416992 "x
" 0 0)) (15 (90.0 47.60907745361328 449.83599853515625 60.90726852416992 "On Reading this Text
xi
" 0 0) (90.00021362304688 75.14844512939453 152.6470489501953 92.38106536865234 "Preface
" 1 0) (89.999267578125 102.08905792236328 449.4326477050781 360.4271545410156 "Most of the GNU Emacs integrated environment is written in the pro-
gramming language called Emacs Lisp. The code written in this program-
ming language is the software—the sets of instructions—that tell the com-
puter what to do when you give it commands. Emacs is designed so that
you can write new code in Emacs Lisp and easily install it as an extension
to the editor.
(GNU Emacs is sometimes called an “extensible editor”, but it does much
more than provide editing capabilities.
It is better to refer to Emacs as
an “extensible computing environment”. However, that phrase is quite a
mouthful.
It is easier to refer to Emacs simply as an editor.
Moreover,
everything you do in Emacs—find the Mayan date and phases of the moon,
simplify polynomials, debug code, manage files, read letters, write books—all
these activities are kinds of editing in the most general sense of the word.)
Although Emacs Lisp is usually thought of in association only with
Emacs, it is a full computer programming language. You can use Emacs
Lisp as you would any other programming language.
Perhaps you want to understand programming; perhaps you want to ex-
tend Emacs; or perhaps you want to become a programmer. This introduc-
tion to Emacs Lisp is designed to get you started: to guide you in learning
the fundamentals of programming, and more importantly, to show you how
you can teach yourself to go further.
" 2 0) (90.00047302246094 376.2202453613281 243.05418395996094 390.5807800292969 "On Reading this Text
" 3 0) (89.99932861328125 398.24896240234375 449.6614685058594 630.7872314453125 "All through this document, you will see little sample programs you can
run inside of Emacs.
If you read this document in Info inside of GNU
Emacs, you can run the programs as they appear. (This is easy to do and
is explained when the examples are presented.) Alternatively, you can read
this introduction as a printed book while sitting beside a computer running
Emacs. (This is what I like to do; I like printed books.) If you don’t have a
running Emacs beside you, you can still read this book, but in this case, it
is best to treat it as a novel or as a travel guide to a country not yet visited:
interesting, but not the same as being there.
Much of this introduction is dedicated to walk-throughs or guided tours
of code used in GNU Emacs. These tours are designed for two purposes:
first, to give you familiarity with real, working code (code you use every
day); and, second, to give you familiarity with the way Emacs works. It is
interesting to see how a working environment is implemented. Also, I hope
that you will pick up the habit of browsing through source code. You can
learn from it and mine it for ideas. Having GNU Emacs is like having a
dragon’s cave of treasures.
In addition to learning about Emacs as an editor and Emacs Lisp as
a programming language, the examples and guided tours will give you an
" 4 0)) (16 (90.0 47.60907745361328 449.8251953125 60.90726852416992 "xii
Preface
" 0 0) (89.99826049804688 77.48908233642578 449.3992919921875 201.1873016357422 "opportunity to get acquainted with Emacs as a Lisp programming environ-
ment. GNU Emacs supports programming and provides tools that you will
want to become comfortable using, such as M-. (the key which invokes the
find-tag command). You will also learn about buffers and other objects
that are part of the environment. Learning about these features of Emacs is
like learning new routes around your home town.
Finally, I hope to convey some of the skills for using Emacs to learn
aspects of programming that you don’t know. You can often use Emacs to
help you understand what puzzles you or to find out how to do something
new. This self-reliance is not only a pleasure, but an advantage.
" 1 0) (89.99856567382812 221.06036376953125 279.07073974609375 235.4208984375 "For Whom This is Written
" 2 0) (89.99630737304688 244.049072265625 449.50616455078125 630.7874755859375 "This text is written as an elementary introduction for people who are not
programmers. If you are a programmer, you may not be satisfied with this
primer. The reason is that you may have become expert at reading reference
manuals and be put off by the way this text is organized.
An expert programmer who reviewed this text said to me:
I prefer to learn from reference manuals. I “dive into” each para-
graph, and “come up for air” between paragraphs.
When I get to the end of a paragraph, I assume that that subject
is done, finished, that I know everything I need (with the possible
exception of the case when the next paragraph starts talking about
it in more detail). I expect that a well written reference manual
will not have a lot of redundancy, and that it will have excellent
pointers to the (one) place where the information I want is.
This introduction is not written for this person!
Firstly, I try to say everything at least three times: first, to introduce it;
second, to show it in context; and third, to show it in a different context, or
to review it.
Secondly, I hardly ever put all the information about a subject in one
place, much less in one paragraph. To my way of thinking, that imposes
too heavy a burden on the reader. Instead I try to explain only what you
need to know at the time. (Sometimes I include a little extra information
so you won’t be surprised later when the additional information is formally
introduced.)
When you read this text, you are not expected to learn everything the first
time. Frequently, you need only make, as it were, a ‘nodding acquaintance’
with some of the items mentioned. My hope is that I have structured the
text and given you enough hints that you will be alert to what is important,
and concentrate on it.
You will need to “dive into” some paragraphs; there is no other way to
read them. But I have tried to keep down the number of such paragraphs.
" 3 0)) (17 (90.0 47.60907745361328 449.7156982421875 60.90726852416992 "A Note for Novices
xiii
" 0 0) (89.99826049804688 77.48908233642578 449.42022705078125 188.34727478027344 "This book is intended as an approachable hill, rather than as a daunting
mountain.
This introduction to Programming in Emacs Lisp has a companion doc-
ument, The GNU Emacs Lisp Reference Manual. The reference manual has
more detail than this introduction. In the reference manual, all the infor-
mation about one topic is concentrated in one place. You should turn to it
if you are like the programmer quoted above. And, of course, after you have
read this Introduction, you will find the Reference Manual useful when you
are writing your own programs.
" 1 0) (89.99887084960938 204.8603515625 177.66000366210938 219.22088623046875 "Lisp History
" 2 0) (89.999267578125 226.88909912109375 449.4208068847656 337.8672790527344 "Lisp was first developed in the late 1950s at the Massachusetts Institute
of Technology for research in artificial intelligence. The great power of the
Lisp language makes it superior for other purposes as well, such as writing
editor commands and integrated environments.
GNU Emacs Lisp is largely inspired by Maclisp, which was written at
MIT in the 1960s. It is somewhat inspired by Common Lisp, which became
a standard in the 1980s. However, Emacs Lisp is much simpler than Common
Lisp. (The standard Emacs distribution contains an optional extensions file,
‘cl.el’, that adds many Common Lisp features to Emacs Lisp.)
" 3 0) (89.99957275390625 354.2603759765625 226.11309814453125 368.62091064453125 "A Note for Novices
" 4 0) (89.99993896484375 376.4090881347656 449.44329833984375 443.3298034667969 "If you don’t know GNU Emacs, you can still read this document prof-
itably. However, I recommend you learn Emacs, if only to learn to move
around your computer screen. You can teach yourself how to use Emacs
with the on-line tutorial. To use it, type C-h t. (This means you press and
release the ⟨
" 5 0) (145.54800415039062 427.552001953125 169.30799865722656 428.0320129394531 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (145.55999755859375 428.7624206542969 169.3109130859375 436.7325134277344 "CTRL
" 7 0) (145.54800415039062 436.1919860839844 169.30799865722656 436.6719970703125 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99853515625 423.80908203125 449.4320983886719 541.0098266601562 "⟩ key and the h at the same time, and then press and release
t.)
Also, I often refer to one of Emacs’ standard commands by listing the
keys which you press to invoke the command and then giving the name of
the command in parentheses, like this: M-C-\\ (indent-region). What this
means is that the indent-region command is customarily invoked by typing
M-C-\\. (You can, if you wish, change the keys that are typed to invoke the
command; this is called rebinding. See Section 16.8, “Keymaps”, page 221.)
The abbreviation M-C-\\ means that you type your ⟨
" 9 0) (344.26800537109375 525.2319946289062 369.5880126953125 525.7119750976562 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (344.2799987792969 526.4424438476562 369.5664978027344 534.41259765625 "META
" 11 0) (344.26800537109375 533.751953125 369.5880126953125 534.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (369.0 521.4890747070312 403.426513671875 541.0098266601562 "⟩ key, ⟨
" 13 0) (402.7080078125 525.2319946289062 426.468017578125 525.7119750976562 "<image: None, width: 1, height: 1, bpc: 1>" 14 1) (402.7200012207031 526.4424438476562 426.4709167480469 534.41259765625 "CTRL
" 15 0) (402.7080078125 533.751953125 426.468017578125 534.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 16 1) (90.00009155273438 521.4890747070312 449.8581848144531 552.8898315429688 "⟩ key
and ⟨
" 17 0) (114.58800506591797 536.751953125 120.34800720214844 537.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 18 1) (114.5999984741211 535.5726928710938 120.32727813720703 546.8636474609375 "\\
" 19 0) (114.58800506591797 545.751953125 120.34800720214844 546.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 20 1) (119.76000213623047 533.3690795898438 422.3863830566406 552.8897705078125 "⟩ key all at the same time. (On many modern keyboards the ⟨
" 21 0) (421.66802978515625 537.1119995117188 446.988037109375 537.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 22 1) (421.67999267578125 538.3223876953125 446.9664001464844 546.2925415039062 "META
" 23 0) (421.66802978515625 545.751953125 446.988037109375 546.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 24 1) (90.0 536.97314453125 449.9865417480469 564.8897705078125 "⟩
key is labelled ⟨
" 25 0) (161.26800537109375 549.1119995117188 178.42800903320312 549.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 26 1) (161.27999877929688 550.3223876953125 178.3014678955078 558.2925415039062 "ALT
" 27 0) (161.26800537109375 557.6319580078125 178.42800903320312 558.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 28 1) (89.99942016601562 545.7290649414062 449.3890380859375 588.769775390625 "⟩.) Sometimes a combination like this is called a keychord,
since it is similar to the way you play a chord on a piano. If your keyboard
does not have a ⟨
" 29 0) (174.58799743652344 572.991943359375 199.90798950195312 573.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 30 1) (174.60000610351562 574.202392578125 199.8865203857422 582.1725463867188 "META
" 31 0) (174.58799743652344 581.6319580078125 199.90798950195312 582.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 32 1) (199.32000732421875 569.2490844726562 253.54656982421875 588.7698364257812 "⟩ key, the ⟨
" 33 0) (252.8280029296875 572.991943359375 269.50799560546875 573.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 34 1) (252.83999633789062 574.202392578125 269.3859558105469 582.1725463867188 "ESC
" 35 0) (252.8280029296875 581.6319580078125 269.50799560546875 582.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 36 1) (90.00003051757812 569.2490844726562 449.7705993652344 600.7698364257812 "⟩ key prefix is used in place of it. In
this case, M-C-\\ means that you press and release your ⟨
" 37 0) (363.3479919433594 584.991943359375 380.0279846191406 585.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 38 1) (363.3599853515625 586.202392578125 379.90594482421875 594.1725463867188 "ESC
" 39 0) (363.3479919433594 593.5120239257812 380.0279846191406 593.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 40 1) (90.00039672851562 581.2490844726562 449.8471374511719 612.7698364257812 "⟩ key and then
type the ⟨
" 41 0) (137.7480010986328 596.9920043945312 161.50799560546875 597.4719848632812 "<image: None, width: 1, height: 1, bpc: 1>" 42 1) (137.75999450683594 598.202392578125 161.5109100341797 606.1725463867188 "CTRL
" 43 0) (137.7480010986328 605.5120239257812 161.50799560546875 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 44 1) (161.0399932861328 593.2490844726562 234.58642578125 612.7698364257812 "⟩ key and the ⟨
" 45 0) (233.9879913330078 596.5120239257812 239.74798583984375 596.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 46 1) (234.0 595.4526977539062 239.72727966308594 606.74365234375 "\\
" 47 0) (233.9879913330078 605.5120239257812 239.74798583984375 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 48 1) (90.00027465820312 593.2490844726562 449.7488708496094 624.6498413085938 "⟩ key at the same time. But usually M-C-\\
means press the ⟨
" 49 0) (172.42800903320312 608.8720092773438 196.18800354003906 609.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 50 1) (172.44000244140625 610.0823974609375 196.19091796875 618.0525512695312 "CTRL
" 51 0) (172.42800903320312 617.5120239257812 196.18800354003906 617.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 52 1) (195.60000610351562 605.1290893554688 393.1064147949219 624.6497802734375 "⟩ key along with the key that is labelled ⟨
" 53 0) (392.38800048828125 608.8720092773438 409.5480041503906 609.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 54 1) (392.3999938964844 610.0823974609375 409.42144775390625 618.0525512695312 "ALT
" 55 0) (392.38800048828125 617.5120239257812 409.5480041503906 617.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 56 1) (90.00039672851562 605.1290893554688 449.869140625 636.6497802734375 "⟩ and, at
the same time, press the ⟨
" 57 0) (213.10801696777344 620.3919677734375 218.86801147460938 620.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 58 1) (213.1199951171875 619.3327026367188 218.84727478027344 630.6236572265625 "\\
" 59 0) (213.10801696777344 629.3919677734375 218.86801147460938 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 60 1) (218.27999877929688 617.1290893554688 243.59999084472656 636.289794921875 "⟩ key.
" 61 0)) (18 (90.0 47.60907745361328 449.8251953125 60.90726852416992 "xiv
Preface
" 0 0) (89.9986572265625 77.48908233642578 449.4637756347656 194.2097930908203 "In addition to typing a lone keychord, you can prefix what you type with
C-u, which is called the ‘universal argument’. The C-u keychord passes an
argument to the subsequent command. Thus, to indent a region of plain
text by 6 spaces, mark the region, and then type C-u 6 M-C-\\. (If you do
not specify a number, Emacs either passes the number 4 to the command
or otherwise runs the command differently than it would otherwise.) See
section “Numeric Arguments” in The GNU Emacs Manual.
If you are reading this in Info using GNU Emacs, you can read through
this whole document just by pressing the space bar, ⟨
" 1 0) (346.3080139160156 178.43194580078125 362.9880065917969 178.9119415283203 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (346.32000732421875 179.6424102783203 362.865966796875 187.61251831054688 "SPC
" 3 0) (346.3080139160156 187.072021484375 362.9880065917969 187.55201721191406 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (89.9993896484375 175.049072265625 449.90179443359375 238.2672576904297 "⟩. (To learn about
Info, type C-h i and then select Info.)
A note on terminology: when I use the word Lisp alone, I often am
referring to the various dialects of Lisp in general, but when I speak of
Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
" 5 0) (89.99943542480469 254.66033935546875 168.7605743408203 269.0208740234375 "Thank You
" 6 0) (89.99978637695312 276.6890869140625 449.869384765625 352.26727294921875 "My thanks to all who helped me with this book. My especial thanks to
Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
Randy Smith, Richard M. Stallman, and Melissa Weisshaus.
My thanks
also go to both Philip Johnson and David Stampe for their patient encour-
agement. My mistakes are my own.
Robert J. Chassell
" 7 0)) (19 (90.0 47.60907745361328 449.9559631347656 60.90726852416992 "Lisp Atoms
1
" 0 0) (89.9993896484375 75.14844512939453 237.94793701171875 92.38106536865234 "1 List Processing
" 1 0) (89.9981689453125 104.12909698486328 449.4855041503906 189.1873016357422 "To the untutored eye, Lisp is a strange programming language. In Lisp
code there are parentheses everywhere. Some people even claim that the
name stands for ‘Lots of Isolated Silly Parentheses’. But the claim is un-
warranted. Lisp stands for LISt Processing, and the programming language
handles lists (and lists of lists) by putting them between parentheses. The
parentheses mark the boundaries of the list. Sometimes a list is preceded by
a single apostrophe or quotation mark, ‘’’. Lists are the basis of Lisp.
" 2 0) (89.99810791015625 206.18035888671875 186.65130615234375 220.5408935546875 "1.1 Lisp Lists
" 3 0) (89.997314453125 228.4490966796875 449.47412109375 277.6272888183594 "In Lisp, a list looks like this: ’(rose violet daisy buttercup). This
list is preceded by a single apostrophe. It could just as well be written as
follows, which looks more like the kind of list you are likely to be familiar
with:
" 4 0) (89.99658203125 282.6976623535156 449.4080810546875 481.8672790527344 "’(rose
violet
daisy
buttercup)
The elements of this list are the names of the four different flowers, separated
from each other by whitespace and surrounded by parentheses, like flowers
in a field with a stone wall around them.
Lists can also have numbers in them, as in this list: (+ 2 2). This list
has a plus-sign, ‘+’, followed by two ‘2’s, each separated by whitespace.
In Lisp, both data and programs are represented the same way; that is,
they are both lists of words, numbers, or other lists, separated by white-
space and surrounded by parentheses. (Since a program looks like data, one
program may easily serve as data for another; this is a very powerful feature
of Lisp.) (Incidentally, these two parenthetical remarks are not Lisp lists,
because they contain ‘;’ and ‘.’ as punctuation marks.)
Here is another list, this time with a list inside of it:
" 5 0) (89.99627685546875 487.0576477050781 449.39642333984375 534.54736328125 "’(this list has (a list inside of it))
The components of this list are the words ‘this’, ‘list’, ‘has’, and the
list ‘(a list inside of it)’. The interior list is made up of the words ‘a’,
‘list’, ‘inside’, ‘of’, ‘it’.
" 6 0) (89.99640655517578 548.2818603515625 201.3193817138672 561.3858642578125 "1.1.1 Lisp Atoms
" 7 0) (89.99514770507812 569.609130859375 449.3634948730469 630.787353515625 "In Lisp, what we have been calling words are called atoms. This term
comes from the historical meaning of the word atom, which means ‘indivis-
ible’. As far as Lisp is concerned, the words we have been using in the lists
cannot be divided into any smaller parts and still mean the same thing as
part of a program; likewise with numbers and single character symbols like
" 8 0)) (20 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "2
Chapter 1: List Processing
" 0 0) (90.00003051757812 77.48908233642578 449.2689514160156 102.66727447509766 "‘+’. On the other hand, unlike an atom, a list can be split into parts. (See
Chapter 7, “car cdr & cons Fundamental Functions”, page 81.)
" 1 0) (89.99966430664062 117.68909454345703 449.32330322265625 142.86729431152344 "In a list, atoms are separated from each other by whitespace. They can
be right next to a parenthesis.
" 2 0) (89.9991455078125 157.88909912109375 449.6281433105469 230.9473114013672 "Technically speaking, a list in Lisp consists of parentheses surrounding
atoms separated by whitespace or surrounding other lists or surrounding
both atoms and other lists.
A list can have just one atom in it or have
nothing in it at all. A list with nothing in it looks like this: (), and is called
the empty list. Unlike anything else, an empty list is considered both an
atom and a list at the same time.
" 3 0) (89.99899291992188 245.84912109375 449.39892578125 318.9073181152344 "The printed representation of both atoms and lists are called symbolic
expressions or, more concisely, s-expressions. The word expression by itself
can refer to either the printed representation, or to the atom or list as it
is held internally in the computer. Often, people use the term expression
indiscriminately. (Also, in many texts, the word form is used as a synonym
for expression.)
" 4 0) (89.99847412109375 333.80914306640625 449.4320373535156 430.8673400878906 "Incidentally, the atoms that make up our universe were named such when
they were thought to be indivisible; but it has been found that physical atoms
are not indivisible. Parts can split off an atom or it can fission into two parts
of roughly equal size. Physical atoms were named prematurely, before their
truer nature was found. In Lisp, certain kinds of atom, such as an array, can
be separated into parts; but the mechanism for doing this is different from
the mechanism for splitting a list. As far as list operations are concerned,
the atoms of a list are unsplittable.
" 5 0) (89.99725341796875 445.7691650390625 449.41961669921875 494.9473571777344 "As in English, the meanings of the component letters of a Lisp atom are
different from the meaning the letters make as a word. For example, the
word for the South American sloth, the ‘ai’, is completely different from the
two words, ‘a’, and ‘i’.
" 6 0) (89.99642944335938 509.84918212890625 449.41912841796875 630.7874145507812 "There are many kinds of atom in nature but only a few in Lisp: for
example, numbers, such as 37, 511, or 1729, and symbols, such as ‘+’, ‘foo’,
or ‘forward-line’. The words we have listed in the examples above are
all symbols. In everyday Lisp conversation, the word “atom” is not often
used, because programmers usually try to be more specific about what kind
of atom they are dealing with. Lisp programming is mostly about symbols
(and sometimes numbers) within lists.
(Incidentally, the preceding three
word parenthetical remark is a proper list in Lisp, since it consists of atoms,
which in this case are symbols, separated by whitespace and enclosed by
parentheses, without any non-Lisp punctuation.)
" 7 0)) (21 (90.0 47.60907745361328 449.78131103515625 60.90726852416992 "GNU Emacs Helps You Type Lists
3
" 0 0) (89.99951171875 79.64905548095703 449.333984375 104.9472427368164 "In addition, text between double quotation marks—even sentences or
paragraphs—is an atom. Here is an example:
" 1 0) (89.998046875 110.13748168945312 449.41973876953125 181.5071258544922 "’(this list includes \"text between quotation marks.\")
In Lisp, all of the quoted text including the punctuation mark and the blank
spaces is a single atom. This kind of atom is called a string (for ‘string
of characters’) and is the sort of thing that is used for messages that a
computer can print for a human to read. Strings are a different kind of atom
than numbers or symbols and are used differently.
" 2 0) (89.99826049804688 195.24169921875 254.18441772460938 208.34568786621094 "1.1.2 Whitespace in Lists
" 3 0) (89.99853515625 216.68896484375 449.3758239746094 241.86717224121094 "The amount of whitespace in a list does not matter. From the point of
view of the Lisp language,
" 4 0) (89.9984359741211 247.05752563476562 218.55104064941406 284.2271423339844 "’(this list
looks like this)
is exactly the same as this:
" 5 0) (89.99649047851562 289.4173889160156 449.4737854003906 460.7470397949219 "’(this list looks like this)
Both examples show what to Lisp is the same list, the list made up of
the symbols ‘this’, ‘list’, ‘looks’, ‘like’, and ‘this’ in that order.
Extra whitespace and newlines are designed to make a list more readable
by humans. When Lisp reads the expression, it gets rid of all the extra
whitespace (but it needs to have at least one space between atoms in order
to tell them apart.)
Odd as it seems, the examples we have seen cover almost all of what
Lisp lists look like! Every other list in Lisp looks more or less like one of
these examples, except that the list may be longer and more complex. In
brief, a list is between parentheses, a string is between quotation marks, a
symbol looks like a word, and a number looks like a number. (For certain
situations, square brackets, dots and a few other special characters may be
used; however, we will go quite far without them.)
" 6 0) (89.99827575683594 474.4815979003906 352.74591064453125 487.5856018066406 "1.1.3 GNU Emacs Helps You Type Lists
" 7 0) (89.99734497070312 495.808837890625 449.5176086425781 550.8495483398438 "When you type a Lisp expression in GNU Emacs using either Lisp Interac-
tion mode or Emacs Lisp mode, you have available to you several commands
to format the Lisp expression so it is easy to read. For example, pressing
the ⟨
" 8 0) (112.66800689697266 535.072021484375 130.42800903320312 535.552001953125 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (112.68000030517578 536.2824096679688 130.4187774658203 544.2525634765625 "TAB
" 10 0) (112.66800689697266 543.5919799804688 130.42800903320312 544.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (90.00009155273438 531.3291015625 449.35589599609375 630.787353515625 "⟩ key automatically indents the line the cursor is on by the right
amount. A command to properly indent the code in a region is customarily
bound to M-C-\\. Indentation is designed so that you can see which elements
of a list belongs to which list—elements of a sub-list are indented more than
the elements of the enclosing list.
In addition, when you type a closing parenthesis, Emacs momentarily
jumps the cursor back to the matching opening parenthesis, so you can see
which one it is. This is very useful, since every list you type in Lisp must have
" 12 0)) (22 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "4
Chapter 1: List Processing
" 0 0) (90.00039672851562 77.48908233642578 449.3244323730469 114.66727447509766 "its closing parenthesis match its opening parenthesis. (See section “Major
Modes” in The GNU Emacs Manual, for more information about Emacs’
modes.)
" 1 0) (90.001220703125 131.30035400390625 228.78074645996094 145.660888671875 "1.2 Run a Program
" 2 0) (90.00100708007812 153.4490966796875 449.4663391113281 350.236083984375 "A list in Lisp—any list—is a program ready to run. If you run it (for
which the Lisp jargon is evaluate), the computer will do one of three things:
do nothing except return to you the list itself; send you an error message; or,
treat the first symbol in the list as a command to do something. (Usually,
of course, it is the last of these three things that you really want!)
The single apostrophe, ’, that I put in front of some of the example lists
in preceding sections is called a quote; when it precedes a list, it tells Lisp
to do nothing with the list, other than take it as it is written. But if there is
no quote preceding a list, the first item of the list is special: it is a command
for the computer to obey. (In Lisp, these commands are called functions.)
The list (+ 2 2) shown above did not have a quote in front of it, so Lisp
understands that the + is an instruction to do something with the rest of the
list: add the numbers that follow.
If you are reading this inside of GNU Emacs in Info, here is how you
can evaluate such a list: place your cursor immediately after the right hand
parenthesis of the following list and then type C-x C-e:
" 3 0) (90.00213623046875 355.297607421875 449.45660400390625 414.67608642578125 "(+ 2 2)
You will see the number 4 appear in the echo area. (In the jargon, what you
have just done is “evaluate the list.” The echo area is the line at the bottom
of the screen that displays or “echoes” text.) Now try the same thing with a
quoted list: place the cursor right after the following list and type C-x C-e:
" 4 0) (89.99981689453125 419.61761474609375 449.44403076171875 566.7073364257812 "’(this is a quoted list)
You will see (this is a quoted list) appear in the echo area.
In both cases, what you are doing is giving a command to the program
inside of GNU Emacs called the Lisp interpreter—giving the interpreter a
command to evaluate the expression. The name of the Lisp interpreter comes
from the word for the task done by a human who comes up with the meaning
of an expression—who “interprets” it.
You can also evaluate an atom that is not part of a list—one that is not
surrounded by parentheses; again, the Lisp interpreter translates from the
humanly readable expression to the language of the computer. But before
discussing this (see Section 1.7, “Variables”, page 10), we will discuss what
the Lisp interpreter does when you make an error.
" 5 0) (90.00013732910156 583.3403930664062 312.9887390136719 597.700927734375 "1.3 Generate an Error Message
" 6 0) (90.00048828125 605.4891357421875 449.4440612792969 630.787353515625 "Partly so you won’t worry if you do it accidentally, we will now give a
command to the Lisp interpreter that generates an error message. This is a
" 7 0)) (23 (90.0 47.60907745361328 449.8147888183594 60.90726852416992 "Generate an Error Message
5
" 0 0) (89.99969482421875 77.48908233642578 449.3667907714844 138.5472869873047 "harmless activity; and indeed, we will often try to generate error messages
intentionally. Once you understand the jargon, error messages can be in-
formative. Instead of being called “error” messages, they should be called
“help” messages. They are like signposts to a traveller in a strange country;
deciphering them can be hard, but once understood, they can point the way.
" 1 0) (89.99981689453125 141.80908203125 449.3234558105469 167.10728454589844 "The error message is generated by a built-in GNU Emacs debugger. We
will ‘enter the debugger’. You get out of the debugger by typing q.
" 2 0) (89.99853515625 170.24908447265625 449.3768005371094 219.43609619140625 "What we will do is evaluate a list that is not quoted and does not have
a meaningful command as its first element. Here is a list almost exactly the
same as the one we just used, but without the single-quote in front of it.
Position the cursor right after it and type C-x C-e:
" 3 0) (111.59806823730469 227.01760864257812 233.72633361816406 235.98399353027344 "(this is an unquoted list)
" 4 0) (89.9980697631836 239.72906494140625 449.3874206542969 288.9072570800781 "What you see depends on which version of Emacs you are running. GNU
Emacs version 21 provides more information than version 20 and before.
First, the more recent result of generating an error; then the earlier, version
20 result.
" 5 0) (89.998046875 292.1690673828125 449.3435974121094 317.4672546386719 "In GNU Emacs version 21, a ‘*Backtrace*’ window will open up and you
will see the following in it:
" 6 0) (111.59724426269531 325.0576171875 346.4422912597656 421.1441345214844 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function this)
(this is an unquoted list)
eval((this is an unquoted list))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 7 0) (89.99765014648438 426.689208984375 449.3754577636719 463.9873962402344 "Your cursor will be in this window (you may have to wait a few seconds
before it becomes visible). To quit the debugger and make the debugger
window go away, type:
" 8 0) (111.5979995727539 471.5777587890625 116.30535125732422 480.54412841796875 "q
" 9 0) (89.99800109863281 484.1692199707031 449.3653259277344 509.4762268066406 "Please type q right now, so you become confident that you can get out of
the debugger. Then, type C-x C-e again to re-enter it.
" 10 0) (104.99765014648438 512.729248046875 449.299072265625 526.0274658203125 "Based on what we already know, we can almost read this error message.
" 11 0) (89.99639892578125 529.169189453125 449.42919921875 590.347412109375 "You read the ‘*Backtrace*’ buffer from the bottom up; it tells you what
Emacs did. When you typed C-x C-e, you made an interactive call to the
command eval-last-sexp. eval is an abbreviation for ‘evaluate’ and sexp
is an abbreviation for ‘symbolic expression’. The command means ‘evaluate
last symbolic expression’, which is the expression just before your cursor.
" 12 0) (89.99649047851562 593.6092529296875 449.75628662109375 630.7874755859375 "Each line above tells you what the Lisp interpreter evaluated next. The
most recent action is at the top. The buffer is called the ‘*Backtrace*’
buffer because it enables you to track Emacs backwards.
" 13 0)) (24 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "6
Chapter 1: List Processing
" 0 0) (105.00039672851562 79.88904571533203 373.5820617675781 93.1872329711914 "At the top of the ‘*Backtrace*’ buffer, you see the line:
" 1 0) (89.99893188476562 98.61758422851562 449.7381286621094 363.90740966796875 "Debugger entered--Lisp error: (void-function this)
The Lisp interpreter tried to evaluate the first atom of the list, the word
‘this’. It is this action that generated the error message ‘void-function
this’.
The message contains the words ‘void-function’ and ‘this’.
The word ‘function’ was mentioned once before. It is a very important
word. For our purposes, we can define it by saying that a function is a set
of instructions to the computer that tell the computer to do something.
Now we can begin to understand the error message: ‘void-function
this’. The function (that is, the word ‘this’) does not have a definition of
any set of instructions for the computer to carry out.
The slightly odd word, ‘void-function’, is designed to cover the way
Emacs Lisp is implemented, which is that when a symbol does not have a
function definition attached to it, the place that should contain the instruc-
tions is ‘void’.
On the other hand, since we were able to add 2 plus 2 successfully, by
evaluating (+ 2 2), we can infer that the symbol + must have a set of in-
structions for the computer to obey and those instructions must be to add
the numbers that follow the +.
In GNU Emacs version 20, and in earlier versions, you will see only one
line of error message; it will appear in the echo area and look like this:
" 2 0) (89.99703979492188 369.2177734375 449.7022399902344 517.2674560546875 "Symbol’s function definition is void: this
(Also, your terminal may beep at you—some do, some don’t; and others
blink. This is just a device to get your attention.) The message goes away
as soon as you type another key, even just to move the cursor.
We know the meaning of the word ‘Symbol’. It refers to the first atom of
the list, the word ‘this’. The word ‘function’ refers to the instructions that
tell the computer what to do. (Technically, the symbol tells the computer
where to find the instructions, but this is a complication we can ignore for
the moment.)
The error message can be understood: ‘Symbol’s function definition
is void: this’. The symbol (that is, the word ‘this’) lacks instructions for
the computer to carry out.
" 3 0) (89.99691772460938 535.2205200195312 403.7975158691406 549.5810546875 "1.4 Symbol Names and Function Definitions
" 4 0) (89.996826171875 557.729248046875 449.39691162109375 630.7874755859375 "We can articulate another characteristic of Lisp based on what we have
discussed so far—an important characteristic: a symbol, like +, is not itself
the set of instructions for the computer to carry out. Instead, the symbol
is used, perhaps temporarily, as a way of locating the definition or set of
instructions. What we see is the name through which the instructions can
be found. Names of people work the same way.
I can be referred to as
" 5 0)) (25 (90.0 47.60907745361328 449.8582458496094 60.90726852416992 "The Lisp Interpreter
7
" 0 0) (89.99691772460938 77.48908233642578 449.4644775390625 305.9473571777344 "‘Bob’; however, I am not the letters ‘B’, ‘o’, ‘b’ but am the consciousness
consistently associated with a particular life-form. The name is not me, but
it can be used to refer to me.
In Lisp, one set of instructions can be attached to several names. For
example, the computer instructions for adding numbers can be linked to the
symbol plus as well as to the symbol + (and are in some dialects of Lisp).
Among humans, I can be referred to as ‘Robert’ as well as ‘Bob’ and by
other words as well.
On the other hand, a symbol can have only one function definition at-
tached to it at a time. Otherwise, the computer would be confused as to
which definition to use. If this were the case among people, only one person
in the world could be named ‘Bob’. However, the function definition to which
the name refers can be changed readily. (See Section 3.2, “Install a Function
Definition”, page 31.)
Since Emacs Lisp is large, it is customary to name symbols in a way that
identifies the part of Emacs to which the function belongs. Thus, all the
names for functions that deal with Texinfo start with ‘texinfo-’ and those
for functions that deal with reading mail start with ‘rmail-’.
" 1 0) (89.99710083007812 330.38043212890625 264.1138916015625 344.740966796875 "1.5 The Lisp Interpreter
" 2 0) (89.99496459960938 354.44915771484375 449.4619140625 630.787353515625 "Based on what we have seen, we can now start to figure out what the Lisp
interpreter does when we command it to evaluate a list. First, it looks to see
whether there is a quote before the list; if there is, the interpreter just gives
us the list. On the other hand, if there is no quote, the interpreter looks at
the first element in the list and sees whether it has a function definition. If
it does, the interpreter carries out the instructions in the function definition.
Otherwise, the interpreter prints an error message.
This is how Lisp works. Simple. There are added complications which
we will get to in a minute, but these are the fundamentals. Of course, to
write Lisp programs, you need to know how to write function definitions and
attach them to names, and how to do this without confusing either yourself
or the computer.
Now, for the first complication. In addition to lists, the Lisp interpreter
can evaluate a symbol that is not quoted and does not have parentheses
around it.
The Lisp interpreter will attempt to determine the symbol’s
value as a variable. This situation is described in the section on variables.
(See Section 1.7, “Variables”, page 10.)
The second complication occurs because some functions are unusual and
do not work in the usual manner. Those that don’t are called special forms.
They are used for special jobs, like defining a function, and there are not
many of them. In the next few chapters, you will be introduced to several
of the more important special forms.
" 3 0)) (26 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "8
Chapter 1: List Processing
" 0 0) (89.99853515625 77.48908233642578 449.49615478515625 213.4272918701172 "The third and final complication is this: if the function that the Lisp
interpreter is looking at is not a special form, and if it is part of a list, the
Lisp interpreter looks to see whether the list has a list inside of it. If there
is an inner list, the Lisp interpreter first figures out what it should do with
the inside list, and then it works on the outside list. If there is yet another
list embedded inside the inner list, it works on that one first, and so on.
It always works on the innermost list first. The interpreter works on the
innermost list first, to evaluate the result of that list. The result may be
used by the enclosing expression.
Otherwise, the interpreter works left to right, from one expression to the
next.
" 1 0) (89.99853515625 229.9217529296875 229.24867248535156 243.02574157714844 "1.5.1 Byte Compiling
" 2 0) (89.99526977539062 252.208984375 449.4936218261719 427.0271911621094 "One other aspect of interpreting: the Lisp interpreter is able to interpret
two kinds of entity: humanly readable code, on which we will focus exclu-
sively, and specially processed code, called byte compiled code, which is not
humanly readable. Byte compiled code runs faster than humanly readable
code.
You can transform humanly readable code into byte compiled code by
running one of the compile commands such as byte-compile-file. Byte
compiled code is usually stored in a file that ends with a ‘.elc’ exten-
sion rather than a ‘.el’ extension. You will see both kinds of file in the
‘emacs/lisp’ directory; the files to read are those with ‘.el’ extensions.
As a practical matter, for most things you might do to customize or
extend Emacs, you do not need to byte compile; and I will not discuss
the topic here. See section “Byte Compilation” in The GNU Emacs Lisp
Reference Manual, for a full description of byte compilation.
" 3 0) (89.99472045898438 447.74029541015625 193.54904174804688 462.100830078125 "1.6 Evaluation
" 4 0) (89.99298095703125 470.9690246582031 449.40380859375 630.7872314453125 "When the Lisp interpreter works on an expression, the term for the ac-
tivity is called evaluation. We say that the interpreter ‘evaluates the expres-
sion’. I’ve used this term several times before. The word comes from its
use in everyday language, ‘to ascertain the value or amount of; to appraise’,
according to Webster’s New Collegiate Dictionary.
After evaluating an expression, the Lisp interpreter will most likely return
the value that the computer produces by carrying out the instructions it
found in the function definition, or perhaps it will give up on that function
and produce an error message. (The interpreter may also find itself tossed,
so to speak, to a different function or it may attempt to repeat continually
what it is doing for ever and ever in what is called an ‘infinite loop’. These
actions are less common; and we can ignore them.) Most frequently, the
interpreter returns a value.
" 5 0)) (27 (90.0 47.60907745361328 449.83587646484375 60.90726852416992 "Evaluating Inner Lists
9
" 0 0) (89.99923706054688 77.48908233642578 449.3990783691406 188.58726501464844 "At the same time the interpreter returns a value, it may do something
else as well, such as move a cursor or copy a file; this other kind of action
is called a side effect. Actions that we humans think are important, such as
printing results, are often “side effects” to the Lisp interpreter. The jargon
can sound peculiar, but it turns out that it is fairly easy to learn to use side
effects.
In summary, evaluating a symbolic expression most commonly causes the
Lisp interpreter to return a value and perhaps carry out a side effect; or else
produce an error.
" 1 0) (89.99913024902344 202.56182861328125 270.7168884277344 215.6658172607422 "1.6.1 Evaluating Inner Lists
" 2 0) (89.99765014648438 223.88909912109375 449.3211669921875 299.2362060546875 "If evaluation applies to a list that is inside another list, the outer list may
use the value returned by the first evaluation as information when the outer
list is evaluated. This explains why inner expressions are evaluated first: the
values they return are used by the outer expressions.
We can investigate this process by evaluating another addition example.
Place your cursor after the following expression and type C-x C-e:
" 3 0) (89.99594116210938 304.4176330566406 449.461181640625 492.1872863769531 "(+ 2 (+ 3 3))
The number 8 will appear in the echo area.
What happens is that the Lisp interpreter first evaluates the inner ex-
pression, (+ 3 3), for which the value 6 is returned; then it evaluates the
outer expression as if it were written (+ 2 6), which returns the value 8.
Since there are no more enclosing expressions to evaluate, the interpreter
prints that value in the echo area.
Now it is easy to understand the name of the command invoked by the
keystrokes C-x C-e: the name is eval-last-sexp.
The letters sexp are
an abbreviation for ‘symbolic expression’, and eval is an abbreviation for
‘evaluate’. The command means ‘evaluate last symbolic expression’.
As an experiment, you can try evaluating the expression by putting the
cursor at the beginning of the next line immediately following the expression,
or inside the expression.
Here is another copy of the expression:
" 4 0) (89.99530029296875 497.3776550292969 449.4059143066406 630.787353515625 "(+ 2 (+ 3 3))
If you place the cursor at the beginning of the blank line that immediately
follows the expression and type C-x C-e, you will still get the value 8 printed
in the echo area. Now try putting the cursor inside the expression. If you
put it right after the next to last parenthesis (so it appears to sit on top
of the last parenthesis), you will get a 6 printed in the echo area! This is
because the command evaluates the expression (+ 3 3).
Now put the cursor immediately after a number. Type C-x C-e and you
will get the number itself. In Lisp, if you evaluate a number, you get the
number itself—this is how numbers differ from symbols. If you evaluate a
list starting with a symbol like +, you will get a value returned that is the
" 5 0)) (28 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "10
Chapter 1: List Processing
" 0 0) (89.999267578125 77.48908233642578 449.2245178222656 114.66727447509766 "result of the computer carrying out the instructions in the function definition
attached to that name. If a symbol by itself is evaluated, something different
happens, as we will see in the next section.
" 1 0) (89.9996337890625 137.54034423828125 183.30419921875 151.90087890625 "1.7 Variables
" 2 0) (89.9949951171875 161.24908447265625 449.5032958984375 436.5160827636719 "In Emacs Lisp, a symbol can have a value attached to it just as it can
have a function definition attached to it. The two are different. The function
definition is a set of instructions that a computer will obey. A value, on the
other hand, is something, such as number or a name, that can vary (which
is why such a symbol is called a variable). The value of a symbol can be any
expression in Lisp, such as a symbol, number, list, or string. A symbol that
has a value is often called a variable.
A symbol can have both a function definition and a value attached to it
at the same time. Or it can have just one or the other. The two are separate.
This is somewhat similar to the way the name Cambridge can refer to the
city in Massachusetts and have some information attached to the name as
well, such as “great programming center”.
Another way to think about this is to imagine a symbol as being a chest of
drawers. The function definition is put in one drawer, the value in another,
and so on. What is put in the drawer holding the value can be changed
without affecting the contents of the drawer holding the function definition,
and vice-versa.
The variable fill-column illustrates a symbol with a value attached to
it: in every GNU Emacs buffer, this symbol is set to some value, usually 72
or 70, but sometimes to some other value. To find the value of this symbol,
evaluate it by itself. If you are reading this in Info inside of GNU Emacs,
you can do this by putting the cursor after the symbol and typing C-x C-e:
" 3 0) (89.9940185546875 443.1376037597656 449.47039794921875 630.787353515625 "fill-column
After I typed C-x C-e, Emacs printed the number 72 in my echo area. This
is the value for which fill-column is set for me as I write this. It may
be different for you in your Info buffer. Notice that the value returned as
a variable is printed in exactly the same way as the value returned by a
function carrying out its instructions. From the point of view of the Lisp
interpreter, a value returned is a value returned. What kind of expression it
came from ceases to matter once the value is known.
A symbol can have any value attached to it or, to use the jargon, we can
bind the variable to a value: to a number, such as 72; to a string, \"such as
this\"; to a list, such as (spruce pine oak); we can even bind a variable to
a function definition.
A symbol can be bound to a value in several ways.
See Section 1.9,
“Setting the Value of a Variable”, page 17, for information about one way
to do this.
" 4 0)) (29 (90.0 47.60907745361328 449.5411682128906 60.90726852416992 "Error Message for a Symbol Without a Value
11
" 0 0) (89.99951171875 78.2418212890625 441.228759765625 91.34580993652344 "1.7.1 Error Message for a Symbol Without a Function
" 1 0) (89.99884033203125 99.68909454345703 449.4649353027344 175.02732849121094 "When we evaluated fill-column to find its value as a variable, we did
not place parentheses around the word. This is because we did not intend
to use it as a function name.
If fill-column were the first or only element of a list, the Lisp interpreter
would attempt to find the function definition attached to it.
But fill-
column has no function definition. Try evaluating this:
" 2 0) (89.99842071533203 180.33767700195312 449.25616455078125 204.06736755371094 "(fill-column)
In GNU Emacs version 21, you will create a ‘*Backtrace*’ buffer that says:
" 3 0) (89.99859619140625 209.37771606445312 449.3437194824219 359.34735107421875 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function fill-column)
(fill-column)
eval((fill-column))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(Remember, to quit the debugger and make the debugger window go away,
type q in the ‘*Backtrace*’ buffer.)
In GNU Emacs 20 and before, you will produce an error message that
says:
" 4 0) (89.99845886230469 364.65771484375 449.4523620605469 400.2673645019531 "Symbol’s function definition is void: fill-column
(The message will go away away as soon as you move the cursor or type
another key.)
" 5 0) (89.99870300292969 414.6019287109375 421.0548095703125 427.7059326171875 "1.7.2 Error Message for a Symbol Without a Value
" 6 0) (89.99868774414062 436.0491943359375 449.5945739746094 485.2362060546875 "If you attempt to evaluate a symbol that does not have a value bound
to it, you will receive an error message. You can see this by experimenting
with our 2 plus 2 addition. In the following expression, put your cursor right
after the +, before the first number 2, type C-x C-e:
" 7 0) (89.99947357177734 490.4177551269531 416.4536437988281 514.2673950195312 "(+ 2 2)
In GNU Emacs 21, you will create a ‘*Backtrace*’ buffer that says:
" 8 0) (89.99969482421875 519.5778198242188 449.3229675292969 630.7874755859375 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-variable +)
eval(+)
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(As with the other times we entered the debugger, you can quit by typing q
in the ‘*Backtrace*’ buffer.)
" 9 0)) (30 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "12
Chapter 1: List Processing
" 0 0) (89.99711608886719 77.48908233642578 449.40985107421875 275.7072448730469 "This backtrace is different from the very first error message we saw,
which said, ‘Debugger entered--Lisp error: (void-function this)’. In
this case, the function does not have a value as a variable; while in the other
error message, the function (the word ‘this’) did not have a definition.
In this experiment with the +, what we did was cause the Lisp interpreter
to evaluate the + and look for the value of the variable instead of the function
definition. We did this by placing the cursor right after the symbol rather
than after the parenthesis of the enclosing list as we did before. As a conse-
quence, the Lisp interpreter evaluated the preceding s-expression, which in
this case was the + by itself.
Since + does not have a value bound to it, just the function definition,
the error message reported that the symbol’s value as a variable was void.
In GNU Emacs version 20 and before, your error message will say:
Symbol’s value as variable is void: +
The meaning is the same as in GNU Emacs 21.
" 1 0) (89.99661254882812 297.7403564453125 196.37869262695312 312.10089111328125 "1.8 Arguments
" 2 0) (89.9964599609375 321.2090759277344 449.287109375 346.50726318359375 "To see how information is passed to functions, let’s look again at our old
standby, the addition of two plus two. In Lisp, this is written as follows:
" 3 0) (89.99591064453125 352.8976135253906 449.4605712890625 503.9472351074219 "(+ 2 2)
If you evaluate this expression, the number 4 will appear in your echo
area. What the Lisp interpreter does is add the numbers that follow the +.
The numbers added by + are called the arguments of the function +.
These numbers are the information that is given to or passed to the function.
The word ‘argument’ comes from the way it is used in mathematics and
does not refer to a disputation between two people; instead it refers to the
information presented to the function, in this case, to the +. In Lisp, the
arguments to a function are the atoms or lists that follow the function. The
values returned by the evaluation of these atoms or lists are passed to the
function. Different functions require different numbers of arguments; some
functions require none at all.1
" 4 0) (89.98799896240234 517.9119873046875 233.98800659179688 518.3919677734375 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (95.87999725341797 518.8551635742188 449.8175354003906 630.3016357421875 "1 It is curious to track the path by which the word ‘argument’ came to have two differ-
ent meanings, one in mathematics and the other in everyday English. According to
the Oxford English Dictionary, the word derives from the Latin for ‘to make clear,
prove’; thus it came to mean, by one thread of derivation, ‘the evidence offered as
proof’, which is to say, ‘the information offered’, which led to its meaning in Lisp.
But in the other thread of derivation, it came to mean ‘to assert in a manner against
which others may make counter assertions’, which led to the meaning of the word as a
disputation. (Note here that the English word has two different definitions attached to
it at the same time. By contrast, in Emacs Lisp, a symbol cannot have two different
function definitions at the same time.)
" 6 0)) (31 (90.0 47.60907745361328 449.5195007324219 60.90726852416992 "An Argument as the Value of a Variable or List
13
" 0 0) (89.99984741210938 78.2418212890625 282.3642272949219 91.34580993652344 "1.8.1 Arguments’ Data Types
" 1 0) (89.99920654296875 99.56909942626953 449.4541320800781 198.6672821044922 "The type of data that should be passed to a function depends on what
kind of information it uses. The arguments to a function such as + must
have values that are numbers, since + adds numbers. Other functions use
different kinds of data for their arguments.
For example, the concat function links together or unites two or more
strings of text to produce a string. The arguments are strings. Concate-
nating the two character strings abc, def produces the single string abcdef.
This can be seen by evaluating the following:
" 2 0) (89.99880981445312 203.73764038085938 449.5189208984375 327.3072204589844 "(concat \"abc\" \"def\")
The value produced by evaluating this expression is \"abcdef\".
A function such as substring uses both a string and numbers as argu-
ments. The function returns a part of the string, a substring of the first
argument. This function takes three arguments. Its first argument is the
string of characters, the second and third arguments are numbers that in-
dicate the beginning and end of the substring. The numbers are a count
of the number of characters (including spaces and punctuations) from the
beginning of the string.
For example, if you evaluate the following:
" 3 0) (89.99746704101562 332.3775634765625 449.5065002441406 453.7873229980469 "(substring \"The quick brown fox jumped.\" 16 19)
you will see \"fox\" appear in the echo area. The arguments are the string
and the two numbers.
Note that the string passed to substring is a single atom even though
it is made up of several words separated by spaces. Lisp counts everything
between the two quotation marks as part of the string, including the spaces.
You can think of the substring function as a kind of ‘atom smasher’ since it
takes an otherwise indivisible atom and extracts a part. However, substring
is only able to extract a substring from an argument that is a string, not
from another type of atom such as a number or symbol.
" 4 0) (89.99795532226562 467.5218811035156 435.76593017578125 480.6258850097656 "1.8.2 An Argument as the Value of a Variable or List
" 5 0) (89.99832153320312 488.84912109375 449.4090576171875 540.1961669921875 "An argument can be a symbol that returns a value when it is evaluated.
For example, when the symbol fill-column by itself is evaluated, it returns
a number. This number can be used in an addition.
Position the cursor after the following expression and type C-x C-e:
" 6 0) (89.9979248046875 545.3777465820312 449.3211669921875 630.787353515625 "(+ 2 fill-column)
The value will be a number two more than what you get by evaluating
fill-column alone. For me, this is 74, because the value of fill-column is
72.
As we have just seen, an argument can be a symbol that returns a value
when evaluated. In addition, an argument can be a list that returns a value
when it is evaluated. For example, in the following expression, the arguments
" 7 0)) (32 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "14
Chapter 1: List Processing
" 0 0) (89.99893188476562 77.48908233642578 449.4317321777344 102.66727447509766 "to the function concat are the strings \"The \" and \" red foxes.\" and the
list (number-to-string (+ 2 fill-column)).
" 1 0) (89.9990234375 108.93759155273438 449.813720703125 193.3872528076172 "(concat \"The \" (number-to-string (+ 2 fill-column)) \" red foxes.\")
If you evaluate this expression—and if, as with my Emacs, fill-column
evaluates to 72—\"The 74 red foxes.\" will appear in the echo area. (Note
that you must put spaces after the word ‘The’ and before the word ‘red’
so they will appear in the final string.
The function number-to-string
converts the integer that the addition function returns to a string. number-
to-string is also known as int-to-string.)
" 2 0) (89.99903869628906 210.601806640625 331.18389892578125 223.70579528808594 "1.8.3 Variable Number of Arguments
" 3 0) (89.99853515625 233.009033203125 449.4313049316406 309.4272155761719 "Some functions, such as concat, + or *, take any number of arguments.
(The * is the symbol for multiplication.) This can be seen by evaluating
each of the following expressions in the usual way. What you will see in the
echo area is printed in this text after ‘⇒’, which you may read as ‘evaluates
to’.
In the first set, the functions have no arguments:
" 4 0) (111.59883117675781 314.8530578613281 177.5061798095703 330.40972900390625 "(+)
⇒ 0
" 5 0) (111.59883117675781 339.8130187988281 177.5061798095703 355.36968994140625 "(*)
⇒ 1
" 6 0) (104.99882507324219 353.2489929199219 343.0240783691406 366.54718017578125 "In this set, the functions have one argument each:
" 7 0) (111.59925842285156 371.9730224609375 177.50660705566406 387.5296936035156 "(+ 3)
⇒ 3
" 8 0) (111.59925842285156 396.8130187988281 177.50660705566406 412.36968994140625 "(* 3)
⇒ 3
" 9 0) (104.99925231933594 410.3689880371094 355.2318115234375 423.66717529296875 "In this set, the functions have three arguments each:
" 10 0) (111.5989990234375 429.093017578125 182.17779541015625 445.24969482421875 "(+ 3 4 5) ⇒ 12
" 11 0) (111.59896850585938 453.9330139160156 182.17776489257812 470.0896911621094 "(* 3 4 5) ⇒ 60
" 12 0) (89.99893188476562 480.4817199707031 431.9792785644531 493.5857238769531 "1.8.4 Using the Wrong Type Object as an Argument
" 13 0) (89.99838256835938 502.88897705078125 449.4961242675781 563.9559936523438 "When a function is passed an argument of the wrong type, the Lisp
interpreter produces an error message. For example, the + function expects
the values of its arguments to be numbers. As an experiment we can pass it
the quoted symbol hello instead of a number. Position the cursor after the
following expression and type C-x C-e:
" 14 0) (89.99658203125 570.2175903320312 449.3319091796875 630.7872314453125 "(+ 2 ’hello)
When you do this you will generate an error message. What has happened is
that + has tried to add the 2 to the value returned by ’hello, but the value
returned by ’hello is the symbol hello, not a number. Only numbers can
be added. So + could not carry out its addition.
" 15 0)) (33 (90.0 47.60907745361328 449.54150390625 60.90726852416992 "Using the Wrong Type Object as an Argument
15
" 0 0) (89.99951171875 85.52906036376953 449.80322265625 110.8272476196289 "In GNU Emacs version 21, you will create and enter a ‘*Backtrace*’
buffer that says:
" 1 0) (111.59939575195312 121.77761840820312 369.980712890625 230.46385192871094 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error:
(wrong-type-argument number-or-marker-p hello)
+(2 hello)
eval((+ 2 (quote hello)))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 2 0) (90.00003051757812 238.7689208984375 449.30157470703125 264.0671081542969 "As usual, the error message tries to be helpful and makes sense after you
learn how to read it.
" 3 0) (89.99972534179688 270.68890380859375 449.4212341308594 307.8670959472656 "The first part of the error message is straightforward; it says ‘wrong type
argument’. Next comes the mysterious jargon word ‘number-or-marker-p’.
This word is trying to tell you what kind of argument the + expected.
" 4 0) (89.99972534179688 314.60888671875 449.43310546875 405.0495910644531 "The symbol number-or-marker-p says that the Lisp interpreter is try-
ing to determine whether the information presented it (the value of the
argument) is a number or a marker (a special object representing a buffer
position). What it does is test to see whether the + is being given numbers to
add. It also tests to see whether the argument is something called a marker,
which is a specific feature of Emacs Lisp. (In Emacs, locations in a buffer
are recorded as markers.
When the mark is set with the C-@ or C-⟨
" 5 0) (430.3080139160156 389.6319885253906 446.9880065917969 390.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (430.32000732421875 390.8424377441406 446.865966796875 398.8125305175781 "SPC
" 7 0) (430.3080139160156 398.2720031738281 446.9880065917969 398.75201416015625 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99850463867188 389.49310302734375 449.9865417480469 447.42724609375 "⟩
command, its position is kept as a marker. The mark can be considered a
number—the number of characters the location is from the beginning of the
buffer.) In Emacs Lisp, + can be used to add the numeric value of marker
positions as numbers.
" 9 0) (89.99911499023438 454.049072265625 449.3556213378906 562.9873046875 "The ‘p’ of number-or-marker-p is the embodiment of a practice started
in the early days of Lisp programming. The ‘p’ stands for ‘predicate’. In the
jargon used by the early Lisp researchers, a predicate refers to a function
to determine whether some property is true or false. So the ‘p’ tells us that
number-or-marker-p is the name of a function that determines whether it
is true or false that the argument supplied is a number or a marker. Other
Lisp symbols that end in ‘p’ include zerop, a function that tests whether its
argument has the value of zero, and listp, a function that tests whether its
argument is a list.
" 10 0) (89.99859619140625 569.609130859375 449.3768005371094 630.787353515625 "Finally, the last part of the error message is the symbol hello. This is the
value of the argument that was passed to +. If the addition had been passed
the correct type of object, the value passed would have been a number, such
as 37, rather than a symbol like hello. But then you would not have got
the error message.
" 11 0)) (34 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "16
Chapter 1: List Processing
" 0 0) (89.99951171875 79.52906036376953 449.3662414550781 104.8272476196289 "In GNU Emacs version 20 and before, the echo area displays an error
message that says:
" 1 0) (89.99954223632812 109.77761840820312 449.72625732421875 145.1472625732422 "Wrong type argument: number-or-marker-p, hello
This says, in different words, the same as the top line of the ‘*Backtrace*’
buffer.
" 2 0) (89.99954223632812 157.92181396484375 265.9501037597656 171.03736877441406 "1.8.5 The message Function
" 3 0) (89.99853515625 179.00909423828125 449.47509765625 242.22727966308594 "Like +, the message function takes a variable number of arguments. It is
used to send messages to the user and is so useful that we will describe it
here.
A message is printed in the echo area.
For example, you can print a
message in your echo area by evaluating the following list:
" 4 0) (89.99856567382812 247.29763793945312 449.5411376953125 418.2760009765625 "(message \"This message appears in the echo area!\")
The whole string between double quotation marks is a single argument
and is printed in toto. (Note that in this example, the message itself will ap-
pear in the echo area within double quotes; that is because you see the value
returned by the message function. In most uses of message in programs that
you write, the text will be printed in the echo area as a side-effect, without
the quotes. See Section 3.3.1, “multiply-by-seven in detail”, page 34, for
an example of this.)
However, if there is a ‘%s’ in the quoted string of characters, the message
function does not print the ‘%s’ as such, but looks to the argument that
follows the string. It evaluates the second argument and prints the value at
the location in the string where the ‘%s’ is.
You can see this by positioning the cursor after the following expression
and typing C-x C-e:
" 5 0) (89.9979248046875 423.217529296875 449.4093017578125 508.38720703125 "(message \"The name of this buffer is: %s.\" (buffer-name))
In Info, \"The name of this buffer is: *info*.\" will appear in the echo
area. The function buffer-name returns the name of the buffer as a string,
which the message function inserts in place of %s.
To print a value as an integer, use ‘%d’ in the same way as ‘%s’. For
example, to print a message in the echo area that states the value of the
fill-column, evaluate the following:
" 6 0) (89.9979248046875 513.3375854492188 449.5290832519531 598.5072631835938 "(message \"The value of fill-column is %d.\" fill-column)
On my system, when I evaluate this list, \"The value of fill-column is
72.\" appears in my echo area2.
If there is more than one ‘%s’ in the quoted string, the value of the first
argument following the quoted string is printed at the location of the first
‘%s’ and the value of the second argument is printed at the location of the
second ‘%s’, and so on.
" 7 0) (89.98799896240234 605.5120239257812 233.98800659179688 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (95.87999725341797 606.5751953125 449.7224426269531 630.3015747070312 "2 Actually, you can use %s to print a number. It is non-specific. %d prints only the part
of a number left of a decimal point, and not anything that is not a number.
" 9 0)) (35 (90.0 47.60907745361328 449.8360595703125 60.90726852416992 "Using set
17
" 0 0) (104.9993896484375 80.60907745361328 307.3194274902344 93.90726470947266 "For example, if you evaluate the following,
" 1 0) (89.99725341796875 100.05758666992188 449.41925048828125 250.9872283935547 "(message \"There are %d %s in the office!\"
(- fill-column 14) \"pink elephants\")
a rather whimsical message will appear in your echo area. On my system it
says, \"There are 58 pink elephants in the office!\".
The expression (- fill-column 14) is evaluated and the resulting num-
ber is inserted in place of the ‘%d’; and the string in double quotes, \"pink
elephants\", is treated as a single argument and inserted in place of the
‘%s’. (That is to say, a string between double quotes evaluates to itself, like
a number.)
Finally, here is a somewhat complex example that not only illustrates
the computation of a number, but also shows how you can use an expression
within an expression to generate the text that is substituted for ‘%s’:
" 2 0) (89.99569702148438 257.1375427246094 449.5152893066406 418.9872131347656 "(message \"He saw %d %s\"
(- fill-column 34)
(concat \"red \"
(substring
\"The quick brown foxes jumped.\" 16 21)
\" leaping.\"))
In this example, message has three arguments: the string, \"He saw %d
%s\", the expression, (- fill-column 32), and the expression beginning with
the function concat. The value resulting from the evaluation of (- fill-
column 32) is inserted in place of the ‘%d’; and the value returned by the
expression beginning with concat is inserted in place of the ‘%s’.
When I evaluate the expression, the message \"He saw 38 red foxes
leaping.\" appears in my echo area.
" 3 0) (89.99574279785156 439.7003173828125 337.15985107421875 454.06085205078125 "1.9 Setting the Value of a Variable
" 4 0) (89.99496459960938 462.9290466308594 449.36309814453125 539.1072998046875 "There are several ways by which a variable can be given a value. One of
the ways is to use either the function set or the function setq. Another way
is to use let (see Section 3.6, “let”, page 36). (The jargon for this process
is to bind a variable to a value.)
The following sections not only describe how set and setq work but also
illustrate how arguments are passed.
" 5 0) (89.99526977539062 555.7218017578125 189.42724609375 568.8373413085938 "1.9.1 Using set
" 6 0) (89.99478149414062 578.009033203125 449.4709777832031 615.196044921875 "To set the value of the symbol flowers to the list ’(rose violet daisy
buttercup), evaluate the following expression by positioning the cursor after
the expression and typing C-x C-e.
" 7 0) (111.59518432617188 621.337646484375 322.8502197265625 630.3040161132812 "(set ’flowers ’(rose violet daisy buttercup))
" 8 0)) (36 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "18
Chapter 1: List Processing
" 0 0) (89.99588012695312 77.48908233642578 449.5401611328125 214.6361083984375 "The list (rose violet daisy buttercup) will appear in the echo area. This
is what is returned by the set function. As a side effect, the symbol flowers
is bound to the list ; that is, the symbol flowers, which can be viewed as a
variable, is given the list as its value. (This process, by the way, illustrates
how a side effect to the Lisp interpreter, setting the value, can be the primary
effect that we humans are interested in. This is because every Lisp function
must return a value if it does not get an error, but it will only have a side
effect if it is designed to have one.)
After evaluating the set expression, you can evaluate the symbol flowers
and it will return the value you just set. Here is the symbol. Place your
cursor after it and type C-x C-e.
" 1 0) (89.99557495117188 221.97763061523438 449.3955078125 299.8273010253906 "flowers
When you evaluate flowers, the list (rose violet daisy buttercup) ap-
pears in the echo area.
Incidentally, if you evaluate ’flowers, the variable with a quote in front
of it, what you will see in the echo area is the symbol itself, flowers. Here
is the quoted symbol, so you can try this:
" 2 0) (89.99444580078125 307.1776428222656 449.5155334472656 440.5873107910156 "’flowers
Note also, that when you use set, you need to quote both arguments to
set, unless you want them evaluated. Since we do not want either argument
evaluated, neither the variable flowers nor the list (rose violet daisy
buttercup), both are quoted. (When you use set without quoting its first
argument, the first argument is evaluated before anything else is done. If
you did this and flowers did not have a value already, you would get an
error message that the ‘Symbol’s value as variable is void’; on the other
hand, if flowers did return a value after it was evaluated, the set would
attempt to set the value that was returned. There are situations where this
is the right thing for the function to do; but such situations are rare.)
" 3 0) (89.99407958984375 460.921875 196.14169311523438 474.0374450683594 "1.9.2 Using setq
" 4 0) (89.99331665039062 484.40911865234375 449.50286865234375 585.787353515625 "As a practical matter, you almost always quote the first argument to set.
The combination of set and a quoted first argument is so common that it
has its own name: the special form setq. This special form is just like set
except that the first argument is quoted automatically, so you don’t need to
type the quote mark yourself. Also, as an added convenience, setq permits
you to set several different variables to different values, all in one expression.
To set the value of the variable carnivores to the list ’(lion tiger
leopard) using setq, the following expression is used:
" 5 0) (89.99374389648438 593.0177001953125 449.1311950683594 630.787353515625 "(setq carnivores ’(lion tiger leopard))
This is exactly the same as using set except the first argument is automat-
ically quoted by setq. (The ‘q’ in setq means quote.)
" 6 0)) (37 (90.0 47.60907745361328 449.8360595703125 60.90726852416992 "Counting
19
" 0 0) (104.9993896484375 79.52906036376953 324.09747314453125 92.8272476196289 "With set, the expression would look like this:
" 1 0) (89.99957275390625 97.89761352539062 449.4219665527344 169.1472625732422 "(set ’carnivores ’(lion tiger leopard))
Also, setq can be used to assign different values to different variables.
The first argument is bound to the value of the second argument, the third
argument is bound to the value of the fourth argument, and so on.
For
example, you could use the following to assign a list of trees to the symbol
trees and a list of herbivores to the symbol herbivores:
" 2 0) (89.99673461914062 174.09762573242188 449.462646484375 308.4672546386719 "(setq trees ’(pine fir oak maple)
herbivores ’(gazelle antelope zebra))
(The expression could just as well have been on one line, but it might not
have fit on a page; and humans find it easier to read nicely formatted lists.)
Although I have been using the term ‘assign’, there is another way of
thinking about the workings of set and setq; and that is to say that set
and setq make the symbol point to the list. This latter way of thinking is
very common and in forthcoming chapters we shall come upon at least one
symbol that has ‘pointer’ as part of its name. The name is chosen because the
symbol has a value, specifically a list, attached to it; or, expressed another
way, the symbol is set to “point” to the list.
" 3 0) (89.99659729003906 321.9618225097656 186.9347686767578 335.0658264160156 "1.9.3 Counting
" 4 0) (89.99603271484375 343.049072265625 449.38531494140625 428.1072692871094 "Here is an example that shows how to use setq in a counter. You might
use this to count how many times a part of your program repeats itself. First
set a variable to zero; then add one to the number each time the program
repeats itself. To do this, you need a variable that serves as a counter, and
two expressions: an initial setq expression that sets the counter variable to
zero; and a second setq expression that increments the counter each time it
is evaluated.
" 5 0) (111.59613800048828 433.1752014160156 385.1600646972656 442.14398193359375 "(setq counter 0)
; Let’s call this the initializer.
" 6 0) (111.59576416015625 458.01519775390625 367.5655212402344 466.9839782714844 "(setq counter (+ counter 1))
; This is the incrementer.
" 7 0) (89.99337768554688 482.9751892089844 449.4482727050781 630.7872924804688 "counter
; This is the counter.
(The text following the ‘;’ are comments.
See Section 3.2.1, “Change a
Function Definition”, page 32.)
If you evaluate the first of these expressions, the initializer, (setq
counter 0), and then evaluate the third expression, counter, the number 0
will appear in the echo area. If you then evaluate the second expression, the
incrementer, (setq counter (+ counter 1)), the counter will get the value
1. So if you again evaluate counter, the number 1 will appear in the echo
area. Each time you evaluate the second expression, the value of the counter
will be incremented.
When you evaluate the incrementer, (setq counter (+ counter 1)), the
Lisp interpreter first evaluates the innermost list; this is the addition. In
" 8 0)) (38 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "20
Chapter 1: List Processing
" 0 0) (89.99929809570312 77.48908233642578 449.4102478027344 150.5472869873047 "order to evaluate this list, it must evaluate the variable counter and the
number 1. When it evaluates the variable counter, it receives its current
value.
It passes this value and the number 1 to the + which adds them
together. The sum is then returned as the value of the inner list and passed
to the setq which sets the variable counter to this new value. Thus, the
value of the variable, counter, is changed.
" 1 0) (89.99888610839844 168.2603759765625 194.45069885253906 182.62091064453125 "1.10 Summary
" 2 0) (89.99853515625 190.64910888671875 449.4289855957031 550.1472778320312 "Learning Lisp is like climbing a hill in which the first part is the steepest.
You have now climbed the most difficult part; what remains becomes easier
as you progress onwards.
In summary,
• Lisp programs are made up of expressions, which are lists or single
atoms.
• Lists are made up of zero or more atoms or inner lists, separated by
whitespace and surrounded by parentheses. A list can be empty.
• Atoms are multi-character symbols, like forward-paragraph, single
character symbols like +, strings of characters between double quota-
tion marks, or numbers.
• A number evaluates to itself.
• A string between double quotes also evaluates to itself.
• When you evaluate a symbol by itself, its value is returned.
• When you evaluate a list, the Lisp interpreter looks at the first symbol
in the list and then at the function definition bound to that symbol.
Then the instructions in the function definition are carried out.
• A single-quote, ’, tells the Lisp interpreter that it should return the
following expression as written, and not evaluate it as it would if the
quote were not there.
• Arguments are the information passed to a function. The arguments to
a function are computed by evaluating the rest of the elements of the
list of which the function is the first element.
• A function always returns a value when it is evaluated (unless it gets
an error); in addition, it may also carry out some action called a “side
effect”. In many cases, a function’s primary purpose is to create a side
effect.
" 3 0) (89.99552154541016 567.8603515625 191.33419799804688 582.2208862304688 "1.11 Exercises
" 4 0) (98.99540710449219 590.2490844726562 449.3295593261719 630.7872924804688 "A few simple exercises:
• Generate an error message by evaluating an appropriate symbol that is
not within parentheses.
" 5 0)) (39 (90.0 47.60907745361328 449.8256530761719 60.90726852416992 "Exercises
21
" 0 0) (98.99981689453125 77.48908233642578 449.3341979980469 144.5472869873047 "• Generate an error message by evaluating an appropriate symbol that is
between parentheses.
• Create a counter that increments by two rather than one.
• Write an expression that prints a message in the echo area when evalu-
ated.
" 1 0)) (40 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "22
Chapter 1: List Processing
" 0 0)) (41 (90.0 47.60907745361328 449.8140563964844 60.90726852416992 "Buffer Names
23
" 0 0) (89.9993896484375 75.14844512939453 292.32098388671875 92.38106536865234 "2 Practicing Evaluation
" 1 0) (89.997802734375 102.08905792236328 449.6385498046875 434.1072692871094 "Before learning how to write a function definition in Emacs Lisp, it is
useful to spend a little time evaluating various expressions that have already
been written. These expressions will be lists with the functions as their first
(and often only) element. Since some of the functions associated with buffers
are both simple and interesting, we will start with those. In this section, we
will evaluate a few of these. In another section, we will study the code of
several other buffer-related functions, to see how they were written.
Whenever you give an editing command to Emacs Lisp, such as the com-
mand to move the cursor or to scroll the screen, you are evaluating an ex-
pression, the first element of which is a function. This is how Emacs works.
When you type keys, you cause the Lisp interpreter to evaluate an expres-
sion and that is how you get your results. Even typing plain text involves
evaluating an Emacs Lisp function, in this case, one that uses self-insert-
command, which simply inserts the character you typed. The functions you
evaluate by typing keystrokes are called interactive functions, or commands;
how you make a function interactive will be illustrated in the chapter on
how to write function definitions. See Section 3.3, “Making a Function In-
teractive”, page 33.
In addition to typing keyboard commands, we have seen a second way
to evaluate an expression: by positioning the cursor after a list and typing
C-x C-e. This is what we will do in the rest of this section. There are other
ways to evaluate an expression as well; these will be described as we come
to them.
Besides being used for practicing evaluation, the functions shown in the
next few sections are important in their own right. A study of these functions
makes clear the distinction between buffers and files, how to switch to a
buffer, and how to determine a location within it.
" 2 0) (89.9981689453125 449.9003601074219 215.32943725585938 464.2608947753906 "2.1 Buffer Names
" 3 0) (89.99673461914062 472.049072265625 449.4408264160156 630.787353515625 "The two functions, buffer-name and buffer-file-name, show the differ-
ence between a file and a buffer. When you evaluate the following expression,
(buffer-name), the name of the buffer appears in the echo area. When you
evaluate (buffer-file-name), the name of the file to which the buffer refers
appears in the echo area. Usually, the name returned by (buffer-name) is
the same as the name of the file to which it refers, and the name returned
by (buffer-file-name) is the full path-name of the file.
A file and a buffer are two different entities. A file is information recorded
permanently in the computer (unless you delete it). A buffer, on the other
hand, is information inside of Emacs that will vanish at the end of the editing
session (or when you kill the buffer). Usually, a buffer contains information
that you have copied from a file; we say the buffer is visiting that file. This
copy is what you work on and modify. Changes to the buffer do not change
" 4 0)) (42 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "24
Chapter 2: Practicing Evaluation
" 0 0) (89.99951171875 77.48908233642578 449.3558044433594 142.15606689453125 "the file, until you save the buffer. When you save the buffer, the buffer is
copied to the file and is thus saved permanently.
If you are reading this in Info inside of GNU Emacs, you can evaluate
each of the following expressions by positioning the cursor after it and typing
C-x C-e.
" 1 0) (111.60028076171875 148.53750610351562 172.3654022216797 157.50389099121094 "(buffer-name)
" 2 0) (89.99502563476562 173.49752807617188 450.076171875 630.7871704101562 "(buffer-file-name)
When I do this, ‘\"introduction.texinfo\"’ is the value returned by eval-
uating (buffer-name), and ‘\"/gnu/work/intro/introduction.texinfo\"’
is the value returned by evaluating (buffer-file-name). The former is the
name of the buffer and the latter is the name of the file. (In the expres-
sions, the parentheses tell the Lisp interpreter to treat buffer-name and
buffer-file-name as functions; without the parentheses, the interpreter
would attempt to evaluate the symbols as variables. See Section 1.7, “Vari-
ables”, page 10.)
In spite of the distinction between files and buffers, you will often find
that people refer to a file when they mean a buffer and vice-versa. Indeed,
most people say, “I am editing a file,” rather than saying, “I am editing a
buffer which I will soon save to a file.” It is almost always clear from context
what people mean. When dealing with computer programs, however, it is
important to keep the distinction in mind, since the computer is not as smart
as a person.
The word ‘buffer’, by the way, comes from the meaning of the word as
a cushion that deadens the force of a collision. In early computers, a buffer
cushioned the interaction between files and the computer’s central processing
unit. The drums or tapes that held a file and the central processing unit
were pieces of equipment that were very different from each other, working
at their own speeds, in spurts. The buffer made it possible for them to work
together effectively. Eventually, the buffer grew from being an intermediary,
a temporary holding place, to being the place where work is done. This
transformation is rather like that of a small seaport that grew into a great
city: once it was merely the place where cargo was warehoused temporarily
before being loaded onto ships; then it became a business and cultural center
in its own right.
Not all buffers are associated with files. For example, when you start
an Emacs session by typing the command emacs alone, without naming any
files, Emacs will start with the ‘*scratch*’ buffer on the screen. This buffer
is not visiting any file. Similarly, a ‘*Help*’ buffer is not associated with
any file.
If you switch to the ‘*scratch*’ buffer, type (buffer-name), position
the cursor after it, and type C-x C-e to evaluate the expression, the name
\"*scratch*\" is returned and will appear in the echo area. \"*scratch*\"
is the name of the buffer. However, if you type (buffer-file-name) in
" 3 0)) (43 (90.0 47.60907745361328 449.78125 60.90726852416992 "Getting Buffers
25
" 0 0) (89.99859619140625 77.48908233642578 449.4100036621094 176.46726989746094 "the ‘*scratch*’ buffer and evaluate that, nil will appear in the echo area.
nil is from the Latin word for ‘nothing’; in this case, it means that the
‘*scratch*’ buffer is not associated with any file. (In Lisp, nil is also used
to mean ‘false’ and is a synonym for the empty list, ().)
Incidentally, if you are in the ‘*scratch*’ buffer and want the value
returned by an expression to appear in the ‘*scratch*’ buffer itself rather
than in the echo area, type C-u C-x C-e instead of C-x C-e. This causes the
value returned to appear after the expression. The buffer will look like this:
" 1 0) (89.99822998046875 181.53762817382812 449.3982238769531 240.9072723388672 "(buffer-name)\"*scratch*\"
You cannot do this in Info since Info is read-only and it will not allow you
to change the contents of the buffer. But you can do this in any buffer you
can edit; and when you write code or documentation (such as this book),
this feature is very useful.
" 2 0) (89.99812316894531 257.54034423828125 228.2606201171875 271.90087890625 "2.2 Getting Buffers
" 3 0) (89.99639892578125 279.6890869140625 449.77862548828125 514.50732421875 "The buffer-name function returns the name of the buffer; to get the
buffer itself, a different function is needed: the current-buffer function. If
you use this function in code, what you get is the buffer itself.
A name and the object or entity to which the name refers are different
from each other. You are not your name. You are a person to whom others
refer by name. If you ask to speak to George and someone hands you a
card with the letters ‘G’, ‘e’, ‘o’, ‘r’, ‘g’, and ‘e’ written on it, you might be
amused, but you would not be satisfied. You do not want to speak to the
name, but to the person to whom the name refers. A buffer is similar: the
name of the scratch buffer is ‘*scratch*’, but the name is not the buffer.
To get a buffer itself, you need to use a function such as current-buffer.
However, there is a slight complication: if you evaluate current-buffer
in an expression on its own, as we will do here, what you see is a printed
representation of the name of the buffer without the contents of the buffer.
Emacs works this way for two reasons: the buffer may be thousands of lines
long—too long to be conveniently displayed; and, another buffer may have
the same contents but a different name, and it is important to distinguish
between them.
Here is an expression containing the function:
" 4 0) (89.99655151367188 519.4577026367188 449.4071044921875 630.787353515625 "(current-buffer)
If you evaluate the expression in the usual way, ‘#<buffer *info*>’ appears
in the echo area. The special format indicates that the buffer itself is being
returned, rather than just its name.
Incidentally, while you can type a number or symbol into a program, you
cannot do that with the printed representation of a buffer: the only way to
get a buffer itself is with a function such as current-buffer.
A related function is other-buffer. This returns the most recently se-
lected buffer other than the one you are in currently. If you have recently
" 5 0)) (44 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "26
Chapter 2: Practicing Evaluation
" 0 0) (89.99960327148438 77.48908233642578 449.38861083984375 117.30728912353516 "switched back and forth from the ‘*scratch*’ buffer, other-buffer will
return that buffer.
You can see this by evaluating the expression:
" 1 0) (89.99948120117188 122.85763549804688 449.3883972167969 158.7073211669922 "(other-buffer)
You should see ‘#<buffer *scratch*>’ appear in the echo area, or the name
of whatever other buffer you switched back from most recently1.
" 2 0) (89.99954223632812 177.2603759765625 242.77392578125 191.62091064453125 "2.3 Switching Buffers
" 3 0) (89.9981689453125 199.88909912109375 449.7664794921875 376.2673645019531 "The other-buffer function actually provides a buffer when it is used
as an argument to a function that requires one. We can see this by using
other-buffer and switch-to-buffer to switch to a different buffer.
But first, a brief introduction to the switch-to-buffer function. When
you switched back and forth from Info to the ‘*scratch*’ buffer to evaluate
(buffer-name), you most likely typed C-x b and then typed ‘*scratch*’2
when prompted in the minibuffer for the name of the buffer to which you
wanted to switch. The keystrokes, C-x b, cause the Lisp interpreter to eval-
uate the interactive function switch-to-buffer. As we said before, this is
how Emacs works: different keystrokes call or run different functions. For
example, C-f calls forward-char, M-e calls forward-sentence, and so on.
By writing switch-to-buffer in an expression, and giving it a buffer to
switch to, we can switch buffers just the way C-x b does.
Here is the Lisp expression:
" 4 0) (89.99703979492188 381.8177185058594 449.5504150390625 507.2898864746094 "(switch-to-buffer (other-buffer))
The symbol switch-to-buffer is the first element of the list, so the Lisp
interpreter will treat it as a function and carry out the instructions that
are attached to it.
But before doing that, the interpreter will note that
other-buffer is inside parentheses and work on that symbol first. other-
buffer is the first (and in this case, the only) element of this list, so the Lisp
interpreter calls or runs the function. It returns another buffer. Next, the
interpreter runs switch-to-buffer, passing to it, as an argument, the other
buffer, which is what Emacs will switch to. If you are reading this in Info,
try this now. Evaluate the expression. (To get back, type C-x b ⟨
" 5 0) (401.6280212402344 491.5119934082031 419.7480163574219 491.99200439453125 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (401.6400146484375 492.7224426269531 419.7401428222656 500.6925354003906 "RET
" 7 0) (401.6280212402344 500.0320129394531 419.7480163574219 500.51202392578125 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (419.2799987792969 488.1290588378906 434.0481262207031 506.9297790527344 "⟩.)3
" 9 0) (89.98799896240234 512.3919677734375 233.98800659179688 512.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (95.87995910644531 513.4552001953125 449.8567810058594 615.3016357421875 "1 Actually, by default, if the buffer from which you just switched is visible to you in
another window, other-buffer will choose the most recent buffer that you cannot see;
this is a subtlety that I often forget.
2 Or rather, to save typing, you probably typed just part of the name, such as *sc, and
then pressed your TAB key to cause it to expand to the full name; and then typed your
RET key.
3 Remember, this expression will move you to your most recent other buffer that you
cannot see. If you really want to go to your most recently selected buffer, even if you
can still see it, you need to evaluate the following more complex expression:
" 11 0) (111.60035705566406 621.3377075195312 355.89874267578125 630.3040771484375 "(switch-to-buffer (other-buffer (current-buffer) t))
" 12 0)) (45 (90.0 47.60907745361328 449.5959167480469 60.90726852416992 "Buffer Size and the Location of Point
27
" 0 0) (89.99728393554688 77.48908233642578 449.47625732421875 300.0672912597656 "In the programming examples in later sections of this document, you will
see the function set-buffer more often than switch-to-buffer. This is
because of a difference between computer programs and humans: humans
have eyes and expect to see the buffer on which they are working on their
computer terminals. This is so obvious, it almost goes without saying. How-
ever, programs do not have eyes. When a computer program works on a
buffer, that buffer does not need to be visible on the screen.
switch-to-buffer is designed for humans and does two different things:
it switches the buffer to which Emacs’ attention is directed; and it switches
the buffer displayed in the window to the new buffer. set-buffer, on the
other hand, does only one thing: it switches the attention of the computer
program to a different buffer. The buffer on the screen remains unchanged (of
course, normally nothing happens there until the command finishes running).
Also, we have just introduced another jargon term, the word call. When
you evaluate a list in which the first symbol is a function, you are calling
that function. The use of the term comes from the notion of the function as
an entity that can do something for you if you ‘call’ it—just as a plumber is
an entity who can fix a leak if you call him or her.
" 1 0) (89.99729919433594 320.7803955078125 382.8487243652344 335.14093017578125 "2.4 Buffer Size and the Location of Point
" 2 0) (89.99652099609375 344.0091247558594 449.4404602050781 408.18731689453125 "Finally, let’s look at several rather simple functions, buffer-size, point,
point-min, and point-max. These give information about the size of a buffer
and the location of point within it.
The function buffer-size tells you the size of the current buffer; that
is, the function returns a count of the number of characters in the buffer.
" 3 0) (89.99505615234375 414.2176818847656 449.3948669433594 528.54736328125 "(buffer-size)
You can evaluate this in the usual way, by positioning the cursor after the
expression and typing C-x C-e.
In Emacs, the current position of the cursor is called point. The expres-
sion (point) returns a number that tells you where the cursor is located as
a count of the number of characters from the beginning of the buffer up to
point.
You can see the character count for point in this buffer by evaluating the
following expression in the usual way:
" 4 0) (89.99472045898438 534.6976928710938 449.3069152832031 571.02734375 "(point)
As I write this, the value of point is 65724. The point function is frequently
used in some of the examples later in this book.
" 5 0) (89.98799896240234 583.6719970703125 233.98800659179688 584.1519775390625 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (105.0 588.4552001953125 449.8509216308594 630.308837890625 "In this case, the first argument to other-buffer tells it which buffer to skip—the
current one—and the second argument tells other-buffer it is OK to switch to a
visible buffer.
In regular use, switch-to-buffer takes you to an invisible window
since you would most likely use C-x o (other-window) to go to another visible buffer.
" 7 0)) (46 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "28
Chapter 2: Practicing Evaluation
" 0 0) (90.0001220703125 79.52906036376953 449.50830078125 104.8272476196289 "The value of point depends, of course, on its location within the buffer.
If you evaluate point in this spot, the number will be larger:
" 1 0) (89.99801635742188 109.77761840820312 449.4309997558594 230.82725524902344 "(point)
For me, the value of point in this location is 66043, which means that there
are 319 characters (including spaces) between the two expressions.
The function point-min is somewhat similar to point, but it returns the
value of the minimum permissible value of point in the current buffer. This
is the number 1 unless narrowing is in effect. (Narrowing is a mechanism
whereby you can restrict yourself, or a program, to operations on just a part
of a buffer. See Chapter 6, “Narrowing and Widening”, page 77.) Likewise,
the function point-max returns the value of the maximum permissible value
of point in the current buffer.
" 2 0) (89.99761199951172 247.2203369140625 176.9756317138672 261.58087158203125 "2.5 Exercise
" 3 0) (89.9976806640625 269.36907958984375 449.4519958496094 294.5472717285156 "Find a file with which you are working and move towards its middle.
Find its buffer name, file name, length, and your position in the file.
" 4 0)) (47 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "The defun Special Form
29
" 0 0) (89.99920654296875 75.14844512939453 408.7035217285156 92.38106536865234 "3 How To Write Function Definitions
" 1 0) (89.99887084960938 100.40906524658203 449.50750732421875 356.8272399902344 "When the Lisp interpreter evaluates a list, it looks to see whether the first
symbol on the list has a function definition attached to it; or, put another
way, whether the symbol points to a function definition.
If it does, the
computer carries out the instructions in the definition. A symbol that has a
function definition is called, simply, a function (although, properly speaking,
the definition is the function and the symbol refers to it.)
All functions are defined in terms of other functions, except for a few
primitive functions that are written in the C programming language. When
you write functions’ definitions, you will write them in Emacs Lisp and use
other functions as your building blocks. Some of the functions you will use
will themselves be written in Emacs Lisp (perhaps by you) and some will be
primitives written in C. The primitive functions are used exactly like those
written in Emacs Lisp and behave like them. They are written in C so we
can easily run GNU Emacs on any computer that has sufficient power and
can run C.
Let me re-emphasize this: when you write code in Emacs Lisp, you do
not distinguish between the use of functions written in C and the use of
functions written in Emacs Lisp. The difference is irrelevant.
I mention
the distinction only because it is interesting to know. Indeed, unless you
investigate, you won’t know whether an already-written function is written
in Emacs Lisp or C.
" 2 0) (89.99930572509766 371.66033935546875 285.83026123046875 386.0335693359375 "3.1 The defun Special Form
" 3 0) (89.99844360351562 393.8090515136719 449.5723876953125 630.787353515625 "In Lisp, a symbol such as mark-whole-buffer has code attached to it that
tells the computer what to do when the function is called. This code is called
the function definition and is created by evaluating a Lisp expression that
starts with the symbol defun (which is an abbreviation for define function).
Because defun does not evaluate its arguments in the usual way, it is called
a special form.
In subsequent sections, we will look at function definitions from the Emacs
source code, such as mark-whole-buffer. In this section, we will describe
a simple function definition so you can see how it looks.
This function
definition uses arithmetic because it makes for a simple example.
Some
people dislike examples using arithmetic; however, if you are such a person,
do not despair. Hardly any of the code we will study in the remainder of
this introduction involves arithmetic or mathematics. The examples mostly
involve text in one way or another.
A function definition has up to five parts following the word defun:
1. The name of the symbol to which the function definition should be
attached.
2. A list of the arguments that will be passed to the function. If no argu-
ments will be passed to the function, this is an empty list, ().
" 4 0)) (48 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "30
Chapter 3: How To Write Function Definitions
" 0 0) (95.8790512084961 77.48908233642578 449.5083923339844 170.10728454589844 "3. Documentation describing the function.
(Technically optional, but
strongly recommended.)
4. Optionally, an expression to make the function interactive so you can
use it by typing M-x and then the name of the function; or by typing an
appropriate key or keychord.
5. The code that instructs the computer what to do: the body of the
function definition.
" 1 0) (89.9984130859375 175.4090576171875 449.4312744140625 200.58726501464844 "It is helpful to think of the five parts of a function definition as being
organized in a template, with slots for each part:
" 2 0) (89.99749755859375 206.49517822265625 449.25555419921875 292.1471862792969 "(defun function-name (arguments...)
\"optional-documentation...\"
(interactive argument-passing-info)
; optional
body...)
As an example, here is the code for a function that multiplies its argument
by 7. (This example is not interactive. See Section 3.3, “Making a Function
Interactive”, page 33, for that information.)
" 3 0) (89.99642944335938 298.0575256347656 449.4833984375 630.7872314453125 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
This definition begins with a parenthesis and the symbol defun, followed
by the name of the function.
The name of the function is followed by a list that contains the arguments
that will be passed to the function. This list is called the argument list. In
this example, the list has only one element, the symbol, number. When the
function is used, the symbol will be bound to the value that is used as the
argument to the function.
Instead of choosing the word number for the name of the argument, I
could have picked any other name. For example, I could have chosen the
word multiplicand. I picked the word ‘number’ because it tells what kind
of value is intended for this slot; but I could just as well have chosen the
word ‘multiplicand’ to indicate the role that the value placed in this slot
will play in the workings of the function. I could have called it foogle, but
that would have been a bad choice because it would not tell humans what it
means. The choice of name is up to the programmer and should be chosen
to make the meaning of the function clear.
Indeed, you can choose any name you wish for a symbol in an argument
list, even the name of a symbol used in some other function: the name
you use in an argument list is private to that particular definition. In that
definition, the name refers to a different entity than any use of the same name
outside the function definition. Suppose you have a nick-name ‘Shorty’ in
your family; when your family members refer to ‘Shorty’, they mean you.
But outside your family, in a movie, for example, the name ‘Shorty’ refers to
someone else. Because a name in an argument list is private to the function
" 4 0)) (49 (90.0 47.60907745361328 449.6510314941406 60.90726852416992 "Install a Function Definition
31
" 0 0) (89.9986572265625 77.48908233642578 449.6072692871094 329.7073669433594 "definition, you can change the value of such a symbol inside the body of a
function without changing its value outside the function. The effect is similar
to that produced by a let expression. (See Section 3.6, “let”, page 36.)
The argument list is followed by the documentation string that describes
the function. This is what you see when you type C-h f and the name of a
function. Incidentally, when you write a documentation string like this, you
should make the first line a complete sentence since some commands, such as
apropos, print only the first line of a multi-line documentation string. Also,
you should not indent the second line of a documentation string, if you have
one, because that looks odd when you use C-h f (describe-function). The
documentation string is optional, but it is so useful, it should be included in
almost every function you write.
The third line of the example consists of the body of the function defini-
tion. (Most functions’ definitions, of course, are longer than this.) In this
function, the body is the list, (* 7 number), which says to multiply the value
of number by 7. (In Emacs Lisp, * is the function for multiplication, just as
+ is the function for addition.)
When you use the multiply-by-seven function, the argument number
evaluates to the actual number you want used. Here is an example that
shows how multiply-by-seven is used; but don’t try to evaluate this yet!
" 1 0) (89.99813842773438 336.6977233886719 449.4861755371094 509.4673767089844 "(multiply-by-seven 3)
The symbol number, specified in the function definition in the next section,
is given or “bound to” the value 3 in the actual use of the function. Note
that although number was inside parentheses in the function definition, the
argument passed to the multiply-by-seven function is not in parentheses.
The parentheses are written in the function definition so the computer can
figure out where the argument list ends and the rest of the function definition
begins.
If you evaluate this example, you are likely to get an error message. (Go
ahead, try it!) This is because we have written the function definition, but
not yet told the computer about the definition—we have not yet installed (or
‘loaded’) the function definition in Emacs. Installing a function is the process
that tells the Lisp interpreter the definition of the function. Installation is
described in the next section.
" 2 0) (89.99852752685547 533.6604614257812 318.361572265625 548.02099609375 "3.2 Install a Function Definition
" 3 0) (89.99853515625 557.7291870117188 449.4633483886719 630.7874145507812 "If you are reading this inside of Info in Emacs, you can try out the
multiply-by-seven function by first evaluating the function definition and
then evaluating (multiply-by-seven 3). A copy of the function definition
follows. Place the cursor after the last parenthesis of the function definition
and type C-x C-e. When you do this, multiply-by-seven will appear in the
echo area. (What this means is that when a function definition is evaluated,
" 4 0)) (50 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "32
Chapter 3: How To Write Function Definitions
" 0 0) (89.99884033203125 77.48908233642578 449.2569274902344 102.66727447509766 "the value it returns is the name of the defined function.) At the same time,
this action installs the function definition.
" 1 0) (89.99839782714844 108.33761596679688 449.6280212402344 244.03607177734375 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
By evaluating this defun, you have just installed multiply-by-seven in
Emacs. The function is now just as much a part of Emacs as forward-
word or any other editing function you use. (multiply-by-seven will stay
installed until you quit Emacs. To reload code automatically whenever you
start Emacs, see Section 3.5, “Installing Code Permanently”, page 36.)
You can see the effect of installing multiply-by-seven by evaluating the
following sample. Place the cursor after the following expression and type
C-x C-e. The number 21 will appear in the echo area.
" 2 0) (90.00173950195312 249.69760131835938 449.5650634765625 309.5472717285156 "(multiply-by-seven 3)
If you wish, you can read the documentation for the function by typing
C-h f (describe-function) and then the name of the function, multiply-
by-seven. When you do this, a ‘*Help*’ window will appear on your screen
that says:
" 3 0) (90.00132751464844 315.2176208496094 369.9828186035156 352.6361083984375 "multiply-by-seven:
Multiply NUMBER by seven.
(To return to a single window on your screen, type C-x 1.)
" 4 0) (90.00106811523438 368.0418395996094 317.6019287109375 381.1458435058594 "3.2.1 Change a Function Definition
" 5 0) (90.00045776367188 389.8490905761719 449.45574951171875 501.42730712890625 "If you want to change the code in multiply-by-seven, just rewrite it.
To install the new version in place of the old one, evaluate the function
definition again. This is how you modify code in Emacs. It is very simple.
As an example, you can change the multiply-by-seven function to add
the number to itself seven times instead of multiplying the number by seven.
It produces the same answer, but by a different path. At the same time, we
will add a comment to the code; a comment is text that the Lisp interpreter
ignores, but that a human reader may find useful or enlightening.
The
comment is that this is the “second version”.
" 6 0) (90.00033569335938 507.09527587890625 449.4554138183594 630.787353515625 "(defun multiply-by-seven (number)
; Second version.
\"Multiply NUMBER by seven.\"
(+ number number number number number number number))
The comment follows a semicolon, ‘;’. In Lisp, everything on a line that
follows a semicolon is a comment. The end of the line is the end of the
comment. To stretch a comment over two or more lines, begin each line
with a semicolon.
See Section 16.3, “Beginning a ‘.emacs’ File”, page 216, and section
“Comments” in The GNU Emacs Lisp Reference Manual, for more about
comments.
" 7 0)) (51 (90.0 47.60907745361328 449.6617126464844 60.90726852416992 "Make a Function Interactive
33
" 0 0) (90.00015258789062 77.48908233642578 449.4977111816406 152.9473114013672 "You can install this version of the multiply-by-seven function by eval-
uating it in the same way you evaluated the first function: place the cursor
after the last parenthesis and type C-x C-e.
In summary, this is how you write code in Emacs Lisp: you write a
function; install it; test it; and then make fixes or enhancements and install
it again.
" 1 0) (90.00015258789062 171.0203857421875 318.5445251464844 185.38092041015625 "3.3 Make a Function Interactive
" 2 0) (89.99545288085938 193.52911376953125 449.4504089355469 381.5473327636719 "You make a function interactive by placing a list that begins with the
special form interactive immediately after the documentation.
A user
can invoke an interactive function by typing M-x and then the name of the
function; or by typing the keys to which it is bound, for example, by typing
C-n for next-line or C-x h for mark-whole-buffer.
Interestingly, when you call an interactive function interactively, the value
returned is not automatically displayed in the echo area. This is because you
often call an interactive function for its side effects, such as moving forward
by a word or line, and not for the value returned. If the returned value
were displayed in the echo area each time you typed a key, it would be very
distracting.
Both the use of the special form interactive and one way to display a
value in the echo area can be illustrated by creating an interactive version
of multiply-by-seven.
Here is the code:
" 3 0) (89.9947509765625 386.97528076171875 449.7109375 490.1298828125 "(defun multiply-by-seven (number)
; Interactive version.
\"Multiply NUMBER by seven.\"
(interactive \"p\")
(message \"The result is %d\" (* 7 number)))
You can install this code by placing your cursor after it and typing C-x C-e.
The name of the function will appear in your echo area. Then, you can use
this code by typing C-u and a number and then typing M-x multiply-by-
seven and pressing ⟨
" 4 0) (188.98800659179688 474.35198974609375 207.10800170898438 474.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (189.0 475.56243896484375 207.10011291503906 483.53253173828125 "RET
" 6 0) (188.98800659179688 482.8719787597656 207.10800170898438 483.35198974609375 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (89.9998779296875 470.9690856933594 449.6286926269531 589.1560668945312 "⟩. The phrase ‘The result is ...’ followed by the
product will appear in the echo area.
Speaking more generally, you invoke a function like this in either of two
ways:
1. By typing a prefix argument that contains the number to be passed,
and then typing M-x and the name of the function, as with C-u 3 M-x
forward-sentence; or,
2. By typing whatever key or keychord the function is bound to, as with
C-u 3 M-e.
" 8 0) (89.99884796142578 593.6090698242188 449.2897033691406 630.7872924804688 "Both the examples just mentioned work identically to move point forward
three sentences. (Since multiply-by-seven is not bound to a key, it could
not be used as an example of key binding.)
" 9 0)) (52 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "34
Chapter 3: How To Write Function Definitions
" 0 0) (89.99887084960938 77.48908233642578 449.442626953125 134.2097930908203 "(See Section 16.7, “Some Keybindings”, page 220, to learn how to bind
a command to a key.)
A prefix argument is passed to an interactive function by typing the
⟨
" 1 0) (92.86800384521484 118.7919921875 118.18800354003906 119.2719955444336 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (92.87999725341797 120.00239562988281 118.16650390625 127.9725112915039 "META
" 3 0) (92.86800384521484 127.31201171875 118.18800354003906 127.7920150756836 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00018310546875 115.04907989501953 449.5415344238281 152.58726501464844 "⟩ key followed by a number, for example, M-3 M-e, or by typing C-
u and then a number, for example, C-u 3 M-e (if you type C-u without a
number, it defaults to 4).
" 5 0) (90.00042724609375 166.081787109375 340.1502380371094 179.1973419189453 "3.3.1 An Interactive multiply-by-seven
" 6 0) (90.00039672851562 187.2890625 449.4432067871094 224.46726989746094 "Let’s look at the use of the special form interactive and then at the
function message in the interactive version of multiply-by-seven. You will
recall that the function definition looks like this:
" 7 0) (90.00021362304688 229.53521728515625 449.639892578125 340.5072326660156 "(defun multiply-by-seven (number)
; Interactive version.
\"Multiply NUMBER by seven.\"
(interactive \"p\")
(message \"The result is %d\" (* 7 number)))
In this function, the expression, (interactive \"p\"), is a list of two ele-
ments. The \"p\" tells Emacs to pass the prefix argument to the function and
use its value for the argument of the function.
The argument will be a number. This means that the symbol number
will be bound to a number in the line:
" 8 0) (90.00032043457031 345.57757568359375 449.1166076660156 381.0671081542969 "(message \"The result is %d\" (* 7 number))
For example, if your prefix argument is 5, the Lisp interpreter will evaluate
the line as if it were:
" 9 0) (89.99880981445312 386.0174560546875 449.5517883300781 630.7871704101562 "(message \"The result is %d\" (* 7 5))
(If you are reading this in GNU Emacs, you can evaluate this expression
yourself.) First, the interpreter will evaluate the inner list, which is (* 7
5). This returns a value of 35. Next, it will evaluate the outer list, passing
the values of the second and subsequent elements of the list to the function
message.
As we have seen, message is an Emacs Lisp function especially designed
for sending a one line message to a user. (See Section 1.8.5, “The message
function”, page 16.) In summary, the message function prints its first argu-
ment in the echo area as is, except for occurrences of ‘%d’, ‘%s’, or ‘%c’. When
it sees one of these control sequences, the function looks to the second and
subsequent arguments and prints the value of the argument in the location
in the string where the control sequence is located.
In the interactive multiply-by-seven function, the control string is ‘%d’,
which requires a number, and the value returned by evaluating (* 7 5) is
the number 35. Consequently, the number 35 is printed in place of the ‘%d’
and the message is ‘The result is 35’.
(Note that when you call the function multiply-by-seven, the message
is printed without quotes, but when you call message, the text is printed
in double quotes. This is because the value returned by message is what
" 10 0)) (53 (90.0 47.60907745361328 449.60723876953125 60.90726852416992 "Different Options for interactive
35
" 0 0) (89.99957275390625 77.48908233642578 449.4103088378906 114.66727447509766 "appears in the echo area when you evaluate an expression whose first element
is message; but when embedded in a function, message prints the text as a
side effect without quotes.)
" 1 0) (89.99964904785156 140.54034423828125 353.6011047363281 154.91355895996094 "3.4 Different Options for interactive
" 2 0) (90.0 165.08905029296875 449.3779296875 208.12977600097656 "In the example, multiply-by-seven used \"p\" as the argument to
interactive. This argument told Emacs to interpret your typing either
C-u followed by a number or ⟨
" 3 0) (237.8280029296875 192.35198974609375 263.14801025390625 192.8319854736328 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (237.83999633789062 193.56239318847656 263.1264953613281 201.53250122070312 "META
" 5 0) (237.8280029296875 200.87200927734375 263.14801025390625 201.3520050048828 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99932861328125 188.60906982421875 449.7263488769531 262.0272521972656 "⟩ followed by a number as a command
to pass that number to the function as its argument. Emacs has more than
twenty characters predefined for use with interactive. In almost every
case, one of these options will enable you to pass the right information in-
teractively to a function. (See section “Code Characters for interactive”
in The GNU Emacs Lisp Reference Manual.)
" 7 0) (89.99850463867188 265.1689453125 449.4425048828125 302.3471374511719 "For example, the character ‘r’ causes Emacs to pass the beginning and
end of the region (the current values of point and mark) to the function as
two separate arguments. It is used as follows:
" 8 0) (89.99786376953125 309.6974792480469 449.4625549316406 400.7296447753906 "(interactive \"r\")
On the other hand, a ‘B’ tells Emacs to ask for the name of a buffer that
will be passed to the function. When it sees a ‘B’, Emacs will ask for the
name by prompting the user in the minibuffer, using a string that follows
the ‘B’, as in \"BAppend to buffer: \". Not only will Emacs prompt for the
name, but Emacs will complete the name if you type enough of it and press
⟨
" 9 0) (92.86800384521484 385.31201171875 110.62800598144531 385.7920227050781 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (92.87999725341797 386.5224304199219 110.6187744140625 394.4925231933594 "TAB
" 11 0) (92.86800384521484 393.9519958496094 110.62800598144531 394.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (89.9998779296875 381.92913818359375 449.7382507324219 535.5073852539062 "⟩.
A function with two or more arguments can have information passed
to each argument by adding parts to the string that follows interactive.
When you do this, the information is passed to each argument in the same
order it is specified in the interactive list.
In the string, each part is
separated from the next part by a ‘\\n’, which is a newline. For example,
you could follow \"BAppend to buffer: \" with a ‘\\n’) and an ‘r’. This would
cause Emacs to pass the values of point and mark to the function as well as
prompt you for the buffer—three arguments in all.
In this case, the function definition would look like the following, where
buffer, start, and end are the symbols to which interactive binds the
buffer and the current values of the beginning and ending of the region:
" 13 0) (111.60009765625 542.8552856445312 301.69366455078125 589.1441040039062 "(defun name-of-function (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
body-of-function...)
" 14 0) (89.99908447265625 593.6091918945312 449.36614990234375 630.7874145507812 "(The space after the colon in the prompt makes it look better when you
are prompted. The append-to-buffer function looks exactly like this. See
Section 4.4, “The Definition of append-to-buffer”, page 56.)
" 15 0)) (54 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "36
Chapter 3: How To Write Function Definitions
" 0 0) (89.9991455078125 77.48908233642578 449.42108154296875 164.46726989746094 "If a function does not have arguments, then interactive does not require
any. Such a function contains the simple expression (interactive). The
mark-whole-buffer function is like this.
Alternatively, if the special letter-codes are not right for your application,
you can pass your own arguments to interactive as a list.
See section
“Using Interactive” in The GNU Emacs Lisp Reference Manual, for more
information about this advanced technique.
" 1 0) (89.99888610839844 180.8603515625 299.9631652832031 195.22088623046875 "3.5 Install Code Permanently
" 2 0) (89.99822998046875 203.00909423828125 449.5183410644531 454.3872985839844 "When you install a function definition by evaluating it, it will stay in-
stalled until you quit Emacs.
The next time you start a new session of
Emacs, the function will not be installed unless you evaluate the function
definition again.
At some point, you may want to have code installed automatically when-
ever you start a new session of Emacs.
There are several ways of doing
this:
• If you have code that is just for yourself, you can put the code for the
function definition in your ‘.emacs’ initialization file. When you start
Emacs, your ‘.emacs’ file is automatically evaluated and all the function
definitions within it are installed. See Chapter 16, “Your ‘.emacs’ File”,
page 213.
• Alternatively, you can put the function definitions that you want in-
stalled in one or more files of their own and use the load function to
cause Emacs to evaluate and thereby install each of the functions in the
files. See Section 16.9, “Loading Files”, page 222.
• On the other hand, if you have code that your whole site will use,
it is usual to put it in a file called ‘site-init.el’ that is loaded when
Emacs is built. This makes the code available to everyone who uses your
machine. (See the ‘INSTALL’ file that is part of the Emacs distribution.)
" 3 0) (89.994384765625 458.0091247558594 449.3945007324219 566.9473876953125 "Finally, if you have code that everyone who uses Emacs may want, you
can post it on a computer network or send a copy to the Free Software Foun-
dation. (When you do this, please license the code and its documentation
under a license that permits other people to run, copy, study, modify, and
redistribute the code and which protects you from having your work taken
from you.) If you send a copy of your code to the Free Software Foundation,
and properly protect yourself and others, it may be included in the next
release of Emacs. In large part, this is how Emacs has grown over the past
years, by donations.
" 4 0) (89.99435424804688 583.46044921875 140.906005859375 597.8336791992188 "3.6 let
" 5 0) (89.99359130859375 605.4891357421875 449.3171691894531 630.787353515625 "The let expression is a special form in Lisp that you will need to use in
most function definitions.
" 6 0)) (55 (90.0 47.60907745361328 449.6617126464844 60.90726852416992 "The Parts of a let Expression
37
" 0 0) (89.99655151367188 77.48908233642578 449.54119873046875 534.3071899414062 "let is used to attach or bind a symbol to a value in such a way that
the Lisp interpreter will not confuse the variable with a variable of the same
name that is not part of the function.
To understand why the let special form is necessary, consider the situa-
tion in which you own a home that you generally refer to as ‘the house’, as
in the sentence, “The house needs painting.” If you are visiting a friend and
your host refers to ‘the house’, he is likely to be referring to his house, not
yours, that is, to a different house.
If your friend is referring to his house and you think he is referring to
your house, you may be in for some confusion. The same thing could happen
in Lisp if a variable that is used inside of one function has the same name
as a variable that is used inside of another function, and the two are not
intended to refer to the same value. The let special form prevents this kind
of confusion.
The let special form prevents confusion. let creates a name for a local
variable that overshadows any use of the same name outside the let ex-
pression. This is like understanding that whenever your host refers to ‘the
house’, he means his house, not yours. (Symbols used in argument lists work
the same way. See Section 3.1, “The defun Special Form”, page 29.)
Local variables created by a let expression retain their value only within
the let expression itself (and within expressions called within the let ex-
pression); the local variables have no effect outside the let expression.
Another way to think about let is that it is like a setq that is temporary
and local. The values set by let are automatically undone when the let is
finished. The setting only effects expressions that are inside the bounds of
the let expression. In computer science jargon, we would say “the binding
of a symbol is visible only in functions called in the let form; in Emacs Lisp,
scoping is dynamic, not lexical.”
let can create more than one variable at once.
Also, let gives each
variable it creates an initial value, either a value specified by you, or nil.
(In the jargon, this is called ‘binding the variable to the value’.) After let
has created and bound the variables, it executes the code in the body of the
let, and returns the value of the last expression in the body, as the value of
the whole let expression. (‘Execute’ is a jargon term that means to evaluate
a list; it comes from the use of the word meaning ‘to give practical effect to’
(Oxford English Dictionary). Since you evaluate an expression to perform
an action, ‘execute’ has evolved as a synonym to ‘evaluate’.)
" 1 0) (89.99635314941406 548.2816772460938 320.2282409667969 561.397216796875 "3.6.1 The Parts of a let Expression
" 2 0) (89.99591064453125 569.6089477539062 449.42822265625 630.7871704101562 "A let expression is a list of three parts. The first part is the symbol
let. The second part is a list, called a varlist, each element of which is
either a symbol by itself or a two-element list, the first element of which is
a symbol. The third part of the let expression is the body of the let. The
body usually consists of one or more lists.
" 3 0)) (56 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "38
Chapter 3: How To Write Function Definitions
" 0 0) (104.99932861328125 85.64905548095703 329.6063537597656 98.9472427368164 "A template for a let expression looks like this:
" 1 0) (111.59925842285156 110.13507843017578 204.64085388183594 119.10386657714844 "(let varlist body...)
" 2 0) (89.99923706054688 126.32892608642578 449.5193786621094 187.5071258544922 "The symbols in the varlist are the variables that are given initial values by
the let special form. Symbols by themselves are given the initial value of
nil; and each symbol that is the first element of a two-element list is bound
to the value that is returned when the Lisp interpreter evaluates the second
element.
" 3 0) (89.9986572265625 194.2489013671875 449.33294677734375 231.42710876464844 "Thus, a varlist might look like this: (thread (needles 3)). In this case,
in a let expression, Emacs binds the symbol thread to an initial value of
nil, and binds the symbol needles to an initial value of 3.
" 4 0) (89.99810791015625 238.28887939453125 449.45269775390625 263.4670715332031 "When you write a let expression, what you do is put the appropriate
expressions in the slots of the let expression template.
" 5 0) (89.99835205078125 270.3289794921875 449.3871765136719 295.5071716308594 "If the varlist is composed of two-element lists, as is often the case, the
template for the let expression looks like this:
" 6 0) (111.59841918945312 306.69512939453125 207.2140350341797 352.9839172363281 "(let ((variable value)
(variable value)
...)
body...)
" 7 0) (89.99833679199219 384.24176025390625 273.5873718261719 397.3573303222656 "3.6.2 Sample let Expression
" 8 0) (89.99783325195312 411.5690002441406 449.2343444824219 448.7471923828125 "The following expression creates and gives initial values to the two vari-
ables zebra and tiger. The body of the let expression is a list which calls
the message function.
" 9 0) (111.59782409667969 459.8175354003906 379.4499206542969 506.22393798828125 "(let ((zebra ’stripes)
(tiger ’fierce))
(message \"One kind of animal has %s and another is %s.\"
zebra tiger))
" 10 0) (104.99815368652344 513.6890258789062 387.94696044921875 526.9872436523438 "Here, the varlist is ((zebra ’stripes) (tiger ’fierce)).
" 11 0) (89.99758911132812 533.72900390625 449.4306640625 630.7872314453125 "The two variables are zebra and tiger. Each variable is the first element
of a two-element list and each value is the second element of its two-element
list. In the varlist, Emacs binds the variable zebra to the value stripes, and
binds the variable tiger to the value fierce. In this example, both values
are symbols preceded by a quote. The values could just as well have been
another list or a string. The body of the let follows after the list holding the
variables. In this example, the body is a list that uses the message function
to print a string in the echo area.
" 12 0)) (57 (90.0 47.60907745361328 449.7485656738281 60.90726852416992 "The if Special Form
39
" 0 0) (89.9990234375 80.12909698486328 449.4104309082031 117.42728424072266 "You may evaluate the example in the usual fashion, by placing the cur-
sor after the last parenthesis and typing C-x C-e. When you do this, the
following will appear in the echo area:
" 1 0) (89.99917602539062 122.97763061523438 449.27899169921875 182.8273162841797 "\"One kind of animal has stripes and another is fierce.\"
As we have seen before, the message function prints its first argument,
except for ‘%s’. In this example, the value of the variable zebra is printed
at the location of the first ‘%s’ and the value of the variable tiger is printed
at the location of the second ‘%s’.
" 2 0) (89.99952697753906 198.12188720703125 399.14581298828125 211.23744201660156 "3.6.3 Uninitialized Variables in a let Statement
" 3 0) (90.00033569335938 219.80914306640625 449.35638427734375 257.1073303222656 "If you do not bind the variables in a let statement to specific initial
values, they will automatically be bound to an initial value of nil, as in the
following expression:
" 4 0) (90.00006103515625 262.6576843261719 449.3996276855469 388.26739501953125 "(let ((birch 3)
pine
fir
(oak ’some))
(message
\"Here are %d variables with %s, %s, and %s value.\"
birch pine fir oak))
Here, the varlist is ((birch 3) pine fir (oak ’some)).
If you evaluate this expression in the usual way, the following will appear
in your echo area:
" 5 0) (89.99850463867188 393.8177490234375 449.52935791015625 528.0675048828125 "\"Here are 3 variables with nil, nil, and some value.\"
In this example, Emacs binds the symbol birch to the number 3, binds the
symbols pine and fir to nil, and binds the symbol oak to the value some.
Note that in the first part of the let, the variables pine and fir stand
alone as atoms that are not surrounded by parentheses; this is because they
are being bound to nil, the empty list. But oak is bound to some and so
is a part of the list (oak ’some). Similarly, birch is bound to the number
3 and so is in a list with that number. (Since a number evaluates to itself,
the number does not need to be quoted. Also, the number is printed in the
message using a ‘%d’ rather than a ‘%s’.) The four variables as a group are
put into a list to delimit them from the body of the let.
" 6 0) (89.99874877929688 546.9805297851562 263.7757263183594 561.353759765625 "3.7 The if Special Form
" 7 0) (89.9986572265625 569.6092529296875 449.37689208984375 630.7874755859375 "A third special form, in addition to defun and let, is the conditional if.
This form is used to instruct the computer to make decisions. You can write
function definitions without using if, but it is used often enough, and is
important enough, to be included here. It is used, for example, in the code
for the function beginning-of-buffer.
" 8 0)) (58 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "40
Chapter 3: How To Write Function Definitions
" 0 0) (89.9993896484375 77.48908233642578 449.3011169433594 126.66727447509766 "The basic idea behind an if, is that “if a test is true, then an expression
is evaluated.” If the test is not true, the expression is not evaluated. For
example, you might make a decision such as, “if it is warm and sunny, then
go to the beach!”
" 1 0) (90.00003051757812 133.2890625 449.541015625 182.46726989746094 "An if expression written in Lisp does not use the word ‘then’; the test
and the action are the second and third elements of the list whose first
element is if. Nonetheless, the test part of an if expression is often called
the if-part and the second argument is often called the then-part.
" 2 0) (89.99954223632812 189.08905029296875 449.38836669921875 238.2672576904297 "Also, when an if expression is written, the true-or-false-test is usually
written on the same line as the symbol if, but the action to carry out if the
test is true, the “then-part”, is written on the second and subsequent lines.
This makes the if expression easier to read.
" 3 0) (111.59953308105469 249.2152099609375 266.74188232421875 270.6639709472656 "(if true-or-false-test
action-to-carry-out-if-test-is-true)
" 4 0) (89.99954223632812 278.12908935546875 449.3883056640625 303.3072814941406 "The true-or-false-test will be an expression that is evaluated by the Lisp
interpreter.
" 5 0) (89.99847412109375 309.9290771484375 449.3443908691406 347.2272644042969 "Here is an example that you can evaluate in the usual manner. The test is
whether the number 5 is greater than the number 4. Since it is, the message
‘5 is greater than 4!’ will be printed.
" 6 0) (111.59870910644531 358.1752014160156 347.1021728515625 379.6239929199219 "(if (> 5 4)
; if-part
(message \"5 is greater than 4!\"))
; then-part
" 7 0) (89.99832153320312 387.569091796875 449.27825927734375 412.8672790527344 "(The function > tests whether its first argument is greater than its second
argument and returns true if it is.)
" 8 0) (89.99765014648438 419.4891052246094 449.45269775390625 480.66729736328125 "Of course, in actual use, the test in an if expression will not be fixed
for all time as it is by the expression (> 5 4). Instead, at least one of the
variables used in the test will be bound to a value that is not known ahead
of time. (If the value were known ahead of time, we would not need to run
the test!)
" 9 0) (89.99691772460938 487.28912353515625 449.77838134765625 548.3473510742188 "For example, the value may be bound to an argument of a function defi-
nition. In the following function definition, the character of the animal is a
value that is passed to the function. If the value bound to characteristic
is fierce, then the message, ‘It’s a tiger!’ will be printed; otherwise, nil
will be returned.
" 10 0) (111.59686279296875 559.4176635742188 383.8551025390625 630.6640625 "(defun type-of-animal (characteristic)
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger.\"
(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")))
" 11 0)) (59 (90.0 47.60907745361328 449.5629577636719 60.90726852416992 "The type-of-animal Function in Detail
41
" 0 0) (89.99929809570312 79.76905059814453 449.2897033691406 117.0672378540039 "If you are reading this inside of GNU Emacs, you can evaluate the function
definition in the usual way to install it in Emacs, and then you can evaluate
the following two expressions to see the results:
" 1 0) (111.59971618652344 122.25759887695312 224.23960876464844 131.22398376464844 "(type-of-animal ’fierce)
" 2 0) (111.5997085571289 147.21762084960938 219.56813049316406 156.1840057373047 "(type-of-animal ’zebra)
" 3 0) (89.99862670898438 170.24908447265625 449.1593322753906 207.4272918701172 "When you evaluate (type-of-animal ’fierce), you will see the following
message printed in the echo area: \"It’s a tiger!\"; and when you evaluate
(type-of-animal ’zebra) you will see nil printed in the echo area.
" 4 0) (89.9989013671875 221.5218505859375 374.209228515625 234.6374053955078 "3.7.1 The type-of-animal Function in Detail
" 5 0) (89.998779296875 242.9691162109375 449.4207763671875 308.5874328613281 "Let’s look at the type-of-animal function in detail.
The function definition for type-of-animal was written by filling the
slots of two templates, one for a function definition as a whole, and a second
for an if expression.
The template for every function that is not interactive is:
" 6 0) (104.99870300292969 313.8953857421875 416.442138671875 363.6674499511719 "(defun name-of-function (argument-list)
\"documentation...\"
body...)
The parts of the function that match this template look like this:
" 7 0) (89.99978637695312 368.9779052734375 449.4326477050781 504.7875671386719 "(defun type-of-animal (characteristic)
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger.\"
body: the if expression)
The name of function is type-of-animal; it is passed the value of one
argument.
The argument list is followed by a multi-line documentation
string. The documentation string is included in the example because it is a
good habit to write documentation string for every function definition. The
body of the function definition consists of the if expression.
The template for an if expression looks like this:
" 8 0) (105.00108337402344 509.97552490234375 429.5027160644531 547.3876342773438 "(if true-or-false-test
action-to-carry-out-if-the-test-returns-true)
In the type-of-animal function, the code for the if looks like this:
" 9 0) (105.00122833251953 552.5780029296875 316.1464538574219 589.86767578125 "(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")))
Here, the true-or-false-test is the expression:
" 10 0) (90.00041961669922 595.1780395507812 449.400390625 630.7876586914062 "(equal characteristic ’fierce)
In Lisp, equal is a function that determines whether its first argument is
equal to its second argument. The second argument is the quoted symbol
" 11 0)) (60 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "42
Chapter 3: How To Write Function Definitions
" 0 0) (89.99932861328125 77.48908233642578 449.8138427734375 102.66727447509766 "’fierce and the first argument is the value of the symbol characteristic—
in other words, the argument passed to this function.
" 1 0) (89.999267578125 110.00910186767578 449.5413513183594 171.0673065185547 "In the first exercise of type-of-animal, the argument fierce is passed to
type-of-animal. Since fierce is equal to fierce, the expression, (equal
characteristic ’fierce), returns a value of true. When this happens, the
if evaluates the second argument or then-part of the if: (message \"It’s
tiger!\").
" 2 0) (89.99838256835938 178.40911865234375 449.4090270996094 215.5873260498047 "On the other hand, in the second exercise of type-of-animal, the argu-
ment zebra is passed to type-of-animal. zebra is not equal to fierce, so
the then-part is not evaluated and nil is returned by the if expression.
" 3 0) (89.99838256835938 258.50042724609375 290.74395751953125 272.8609619140625 "3.8 If–then–else Expressions
" 4 0) (89.9981689453125 287.2491455078125 449.3325500488281 360.3073425292969 "An if expression may have an optional third argument, called the else-
part, for the case when the true-or-false-test returns false. When this hap-
pens, the second argument or then-part of the overall if expression is not
evaluated, but the third or else-part is evaluated. You might think of this
as the cloudy day alternative for the decision ‘if it is warm and sunny, then
go to the beach, else read a book!”.
" 5 0) (89.99774169921875 367.649169921875 449.4740905761719 416.8273620605469 "The word “else” is not written in the Lisp code; the else-part of an if
expression comes after the then-part. In the written Lisp, the else-part is
usually written to start on a line of its own and is indented less than the
then-part:
" 6 0) (111.59774017333984 428.37530517578125 300.1712341308594 462.3041076660156 "(if true-or-false-test
action-to-carry-out-if-the-test-returns-true
action-to-carry-out-if-the-test-returns-false)
" 7 0) (89.99734497070312 470.24920654296875 449.4627685546875 495.5473937988281 "For example, the following if expression prints the message ‘4 is not
greater than 5!’ when you evaluate it in the usual way:
" 8 0) (111.59687805175781 507.21533203125 347.1088562011719 541.024169921875 "(if (> 4 5)
; if-part
(message \"5 is greater than 4!\")
; then-part
(message \"4 is not greater than 5!\")) ; else-part
" 9 0) (89.99740600585938 549.0892333984375 449.3863220214844 598.2674560546875 "Note that the different levels of indentation make it easy to distinguish the
then-part from the else-part. (GNU Emacs has several commands that au-
tomatically indent if expressions correctly. See Section 1.1.3, “GNU Emacs
Helps You Type Lists”, page 3.)
" 10 0) (89.997314453125 605.4891967773438 449.3753356933594 630.7874145507812 "We can extend the type-of-animal function to include an else-part by
simply incorporating an additional part to the if expression.
" 11 0)) (61 (90.0 47.60907745361328 449.6175231933594 60.90726852416992 "Truth and Falsehood in Emacs Lisp
43
" 0 0) (89.99917602539062 79.52906036376953 449.3661804199219 128.70726013183594 "You can see the consequences of doing this if you evaluate the following
version of the type-of-animal function definition to install it and then
evaluate the two subsequent expressions to pass different arguments to the
function.
" 1 0) (111.59921264648438 133.77520751953125 383.85723876953125 229.86387634277344 "(defun type-of-animal (characteristic)
; Second version.
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger;
else say it’s not fierce.\"
(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")
(message \"It’s not fierce!\")))
" 2 0) (111.5989761352539 246.33749389648438 224.23887634277344 255.3038787841797 "(type-of-animal ’fierce)
" 3 0) (111.5989761352539 271.2975158691406 219.56739807128906 280.2638854980469 "(type-of-animal ’zebra)
" 4 0) (89.9976806640625 294.0889892578125 449.4304504394531 381.06719970703125 "When you evaluate (type-of-animal ’fierce), you will see the following
message printed in the echo area: \"It’s a tiger!\"; but when you evaluate
(type-of-animal ’zebra), you will see \"It’s not fierce!\".
(Of course, if the characteristic were ferocious, the message \"It’s not
fierce!\" would be printed; and it would be misleading! When you write
code, you need to take into account the possibility that some such argument
will be tested by the if and write your program accordingly.)
" 5 0) (89.99810791015625 396.140380859375 370.0843200683594 410.50091552734375 "3.9 Truth and Falsehood in Emacs Lisp
" 6 0) (89.99664306640625 418.16900634765625 449.47314453125 630.7872924804688 "There is an important aspect to the truth test in an if expression. So
far, we have spoken of ‘true’ and ‘false’ as values of predicates as if they were
new kinds of Emacs Lisp objects. In fact, ‘false’ is just our old friend nil.
Anything else—anything at all—is ‘true’.
The expression that tests for truth is interpreted as true if the result of
evaluating it is a value that is not nil. In other words, the result of the test
is considered true if the value returned is a number such as 47, a string such
as \"hello\", or a symbol (other than nil) such as flowers, or a list, or even
a buffer!
Before illustrating a test for truth, we need an explanation of nil.
In Emacs Lisp, the symbol nil has two meanings. First, it means the
empty list. Second, it means false and is the value returned when a true-or-
false-test tests false. nil can be written as an empty list, (), or as nil. As
far as the Lisp interpreter is concerned, () and nil are the same. Humans,
however, tend to use nil for false and () for the empty list.
In Emacs Lisp, any value that is not nil—is not the empty list—is con-
sidered true. This means that if an evaluation returns something that is not
" 7 0)) (62 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "44
Chapter 3: How To Write Function Definitions
" 0 0) (89.99884033203125 77.48908233642578 449.50787353515625 227.1073455810547 "an empty list, an if expression will test true. For example, if a number is
put in the slot for the test, it will be evaluated and will return itself, since
that is what numbers do when evaluated. In this conditional, the if expres-
sion will test true. The expression tests false only when nil, an empty list,
is returned by evaluating the expression.
You can see this by evaluating the two expressions in the following ex-
amples.
In the first example, the number 4 is evaluated as the test in the if
expression and returns itself; consequently, the then-part of the expression
is evaluated and returned: ‘true’ appears in the echo area. In the second
example, the nil indicates false; consequently, the else-part of the expression
is evaluated and returned: ‘false’ appears in the echo area.
" 1 0) (111.59869384765625 232.53768920898438 153.8319549560547 266.4640197753906 "(if 4
’true
’false)
" 2 0) (89.99874877929688 274.5376281738281 449.2897033691406 360.4272155761719 "(if nil
’true
’false)
Incidentally, if some other useful value is not available for a test that
returns true, then the Lisp interpreter will return the symbol t for true. For
example, the expression (> 5 4) returns t when evaluated, as you can see
by evaluating it in the usual way:
" 3 0) (89.99907684326172 365.8575744628906 392.6931457519531 389.70721435546875 "(> 5 4)
On the other hand, this function returns nil if the test is false.
" 4 0) (111.59896850585938 395.1375732421875 144.47213745117188 404.10394287109375 "(> 4 5)
" 5 0) (89.99890899658203 422.7803039550781 230.6892547607422 437.1535339355469 "3.10 save-excursion
" 6 0) (89.99594116210938 445.2890319824219 449.5833740234375 630.7872314453125 "The save-excursion function is the fourth and final special form that
we will discuss in this chapter.
In Emacs Lisp programs used for editing, the save-excursion function
is very common. It saves the location of point and mark, executes the body
of the function, and then restores point and mark to their previous positions
if their locations were changed. Its primary purpose is to keep the user from
being surprised and disturbed by unexpected movement of point or mark.
Before discussing save-excursion, however, it may be useful first to
review what point and mark are in GNU Emacs. Point is the current location
of the cursor.
Wherever the cursor is, that is point.
More precisely, on
terminals where the cursor appears to be on top of a character, point is
immediately before the character. In Emacs Lisp, point is an integer. The
first character in a buffer is number one, the second is number two, and
so on. The function point returns the current position of the cursor as a
number. Each buffer has its own value for point.
" 7 0)) (63 (90.0 47.60907745361328 449.5309143066406 60.90726852416992 "Template for a save-excursion Expression
45
" 0 0) (89.999755859375 77.48908233642578 449.4543151855469 108.16980743408203 "The mark is another position in the buffer; its value can be set with a
command such as C-⟨
" 1 0) (190.9080047607422 92.75201416015625 207.5880126953125 93.23201751708984 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (190.9199981689453 93.96241760253906 207.4659423828125 101.93253326416016 "SPC
" 3 0) (190.9080047607422 101.3919677734375 207.5880126953125 101.8719711303711 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (89.99887084960938 89.00910186767578 449.5196533203125 168.04981994628906 "⟩ (set-mark-command). If a mark has been set, you
can use the command C-x C-x (exchange-point-and-mark) to cause the
cursor to jump to the mark and set the mark to be the previous position
of point. In addition, if you set another mark, the position of the previous
mark is saved in the mark ring. Many mark positions can be saved this way.
You can jump the cursor to a saved mark by typing C-u C-⟨
" 5 0) (371.14801025390625 152.6319580078125 387.8280029296875 153.11195373535156 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (371.1600036621094 153.84242248535156 387.7059631347656 161.81253051757812 "SPC
" 7 0) (371.14801025390625 161.1519775390625 387.8280029296875 161.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.994873046875 148.88909912109375 449.956298828125 483.3072814941406 "⟩ one or more
times.
The part of the buffer between point and mark is called the region. Nu-
merous commands work on the region, including center-region, count-
lines-region, kill-region, and print-region.
The save-excursion special form saves the locations of point and mark
and restores those positions after the code within the body of the special form
is evaluated by the Lisp interpreter. Thus, if point were in the beginning
of a piece of text and some code moved point to the end of the buffer, the
save-excursion would put point back to where it was before, after the
expressions in the body of the function were evaluated.
In Emacs, a function frequently moves point as part of its internal work-
ings even though a user would not expect this. For example, count-lines-
region moves point. To prevent the user from being bothered by jumps that
are both unexpected and (from the user’s point of view) unnecessary, save-
excursion is often used to keep point and mark in the location expected by
the user. The use of save-excursion is good housekeeping.
To make sure the house stays clean, save-excursion restores the values
of point and mark even if something goes wrong in the code inside of it (or,
to be more precise and to use the proper jargon, “in case of abnormal exit”).
This feature is very helpful.
In addition to recording the values of point and mark, save-excursion
keeps track of the current buffer, and restores it, too. This means you can
write code that will change the buffer and have save-excursion switch you
back to the original buffer. This is how save-excursion is used in append-
to-buffer.
(See Section 4.4, “The Definition of append-to-buffer”,
page 56.)
" 9 0) (89.994873046875 495.3618469238281 403.0967712402344 508.4774169921875 "3.10.1 Template for a save-excursion Expression
" 10 0) (104.99459838867188 516.569091796875 370.936279296875 529.8673095703125 "The template for code using save-excursion is simple:
" 11 0) (89.99346923828125 534.9376831054688 449.4045715332031 630.7872924804688 "(save-excursion
body...)
The body of the function is one or more expressions that will be evaluated
in sequence by the Lisp interpreter. If there is more than one expression
in the body, the value of the last one will be returned as the value of the
save-excursion function. The other expressions in the body are evaluated
only for their side effects; and save-excursion itself is used only for its side
effect (which is restoring the positions of point and mark).
" 12 0)) (64 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "46
Chapter 3: How To Write Function Definitions
" 0 0) (89.99957275390625 79.52906036376953 449.2681884765625 104.8272476196289 "In more detail, the template for a save-excursion expression looks like
this:
" 1 0) (89.99939727783203 109.77761840820312 449.3226013183594 221.5872039794922 "(save-excursion
first-expression-in-body
second-expression-in-body
third-expression-in-body
...
last-expression-in-body)
An expression, of course, may be a symbol on its own or a list.
In Emacs Lisp code, a save-excursion expression often occurs within
the body of a let expression. It looks like this:
" 2 0) (111.59974670410156 226.6551513671875 191.0677947998047 260.4638977050781 "(let varlist
(save-excursion
body...))
" 3 0) (89.99969482421875 275.18023681640625 177.9246826171875 289.540771484375 "3.11 Review
" 4 0) (89.99923706054688 297.32904052734375 449.355712890625 334.5072326660156 "In the last few chapters we have introduced a fair number of functions
and special forms. Here they are described in brief, along with a few similar
functions that have not been mentioned yet.
" 5 0) (89.99917602539062 339.8526611328125 449.5627746582031 411.0760498046875 "eval-last-sexp
Evaluate the last symbolic expression before the current location
of point. The value is printed in the echo area unless the function
is invoked with an argument; in that case, the output is printed
in the current buffer. This command is normally bound to C-x
C-e.
" 6 0) (89.99933624267578 414.56903076171875 449.5079650878906 478.2672119140625 "defun
Define function.
This special form has up to five parts: the
name, a template for the arguments that will be passed to the
function, documentation, an optional interactive declaration,
and the body of the definition.
For example:
" 7 0) (89.99830627441406 483.69757080078125 449.49609375 630.7872314453125 "(defun back-to-indentation ()
\"Move point to first visible character on line.\"
(interactive)
(beginning-of-line 1)
(skip-chars-forward \" \\t\"))
interactive
Declare to the interpreter that the function can be used interac-
tively. This special form may be followed by a string with one
or more parts that pass the information to the arguments of the
function, in sequence. These parts may also tell the interpreter
to prompt for information. Parts of the string are separated by
newlines, ‘\\n’.
" 8 0)) (65 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "Review
47
" 0 0) (147.60000610351562 77.48908233642578 288.6217346191406 90.78726959228516 "Common code characters are:
" 1 0) (147.59974670410156 98.36908721923828 355.07952880859375 111.66727447509766 "b
The name of an existing buffer.
" 2 0) (147.59934997558594 119.12909698486328 341.30096435546875 132.4272918701172 "f
The name of an existing file.
" 3 0) (147.5989532470703 140.00909423828125 449.51861572265625 165.3072967529297 "p
The numeric prefix argument. (Note that this ‘p’ is
lower case.)
" 4 0) (147.59942626953125 172.76910400390625 449.55194091796875 210.0673065185547 "r
Point and the mark, as two numeric arguments,
smallest first. This is the only code letter that spec-
ifies two successive arguments rather than one.
" 5 0) (147.59896850585938 217.52911376953125 449.36614990234375 254.8273162841797 "See section “Code Characters for ‘interactive’” in The GNU
Emacs Lisp Reference Manual, for a complete list of code char-
acters.
" 6 0) (89.99897003173828 262.28912353515625 449.7151184082031 335.4673156738281 "let
Declare that a list of variables is for use within the body of the
let and give them an initial value, either nil or a specified
value; then evaluate the rest of the expressions in the body of
the let and return the value of the last one. Inside the body
of the let, the Lisp interpreter does not see the values of the
variables of the same names that are bound outside of the let.
" 7 0) (147.59890747070312 338.609130859375 209.08262634277344 351.9073181152344 "For example,
" 8 0) (169.19894409179688 359.377685546875 380.4963684082031 418.1440734863281 "(let ((foo (buffer-name))
(bar (buffer-size)))
(message
\"This buffer is %s and has %d characters.\"
foo bar))
" 9 0) (89.99915313720703 427.33282470703125 449.5732727050781 474.6673583984375 "save-excursion
Record the values of point and mark and the current buffer
before evaluating the body of this special form.
Restore the
values of point and mark and buffer afterward.
" 10 0) (147.59910583496094 477.9291687011719 209.08282470703125 491.22735595703125 "For example,
" 11 0) (169.1991424560547 498.6977233886719 399.27691650390625 544.984130859375 "(message \"We are %d characters into this buffer.\"
(- (point)
(save-excursion
(goto-char (point-min)) (point))))
" 12 0) (89.99880981445312 553.2891845703125 449.4642333984375 590.4674072265625 "if
Evaluate the first argument to the function; if it is true, evaluate
the second argument; else evaluate the third argument, if there
is one.
" 13 0) (147.59886169433594 593.6091918945312 449.3445739746094 630.7874145507812 "The if special form is called a conditional. There are other con-
ditionals in Emacs Lisp, but if is perhaps the most commonly
used.
" 14 0)) (66 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "48
Chapter 3: How To Write Function Definitions
" 0 0) (147.59933471679688 80.72907257080078 209.0830535888672 94.02725982666016 "For example,
" 1 0) (169.19937133789062 100.05758666992188 371.13720703125 158.8238983154297 "(if (string-equal
(number-to-string 21)
(substring (emacs-version) 10 12))
(message \"This is version 21 Emacs\")
(message \"This is not version 21 Emacs\"))
" 2 0) (89.99952697753906 165.3726348876953 449.58465576171875 357.9071960449219 "equal
eq
Test whether two objects are the same. equal uses one meaning
of the word ‘same’ and eq uses another: equal returns true if
the two objects have a similar structure and contents, such as
two copies of the same book. On the other hand, eq, returns
true if both arguments are actually the same object.
<
>
<=
>=
The < function tests whether its first argument is smaller than
its second argument. A corresponding function, >, tests whether
the first argument is greater than the second. Likewise, <= tests
whether the first argument is less than or equal to the second
and >= tests whether the first argument is greater than or equal
to the second. In all cases, both arguments must be numbers or
markers (markers indicate positions in buffers).
" 3 0) (90.000732421875 364.692626953125 449.51043701171875 552.7872314453125 "string<
string-lessp
string=
string-equal
The string-lessp function tests whether its first argument is
smaller than the second argument. A shorter, alternative name
for the same function (a defalias) is string<.
The arguments to string-lessp must be strings or symbols;
the ordering is lexicographic, so case is significant. The print
names of symbols are used instead of the symbols themselves.
An empty string, ‘\"\"’, a string with no characters in it, is smaller
than any string of characters.
string-equal provides the corresponding test for equality. Its
shorter, alternative name is string=. There are no string test
functions that correspond to >, >=, or <=.
" 4 0) (90.00051879882812 557.72900390625 449.6075134277344 630.7872314453125 "message
Print a message in the echo area. The first argument is a string
that can contain ‘%s’, ‘%d’, or ‘%c’ to print the value of arguments
that follow the string. The argument used by ‘%s’ must be a
string or a symbol; the argument used by ‘%d’ must be a number.
The argument used by ‘%c’ must be an ascii code number; it will
be printed as the character with that ascii code.
" 5 0)) (67 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "Review
49
" 0 0) (90.0 79.33271789550781 449.48699951171875 162.5472869873047 "setq
set
The setq function sets the value of its first argument to the
value of the second argument. The first argument is automati-
cally quoted by setq. It does the same for succeeding pairs of
arguments. Another function, set, takes only two arguments
and evaluates both of them before setting the value returned by
its first argument to the value returned by its second argument.
" 1 0) (90.00051879882812 174.4927520751953 449.47625732421875 197.9473114013672 "buffer-name
Without an argument, return the name of the buffer, as a string.
" 2 0) (90.0 204.2527618408203 449.4541320800781 239.5873260498047 "buffer-file-name
Without an argument, return the name of the file the buffer is
visiting.
" 3 0) (89.9998550415039 251.6527862548828 449.5303955078125 286.9873352050781 "current-buffer
Return the buffer in which Emacs is active; it may not be the
buffer that is visible on the screen.
" 4 0) (89.9993896484375 299.05279541015625 449.5411376953125 346.3873596191406 "other-buffer
Return the most recently selected buffer (other than the buffer
passed to other-buffer as an argument and other than the
current buffer).
" 5 0) (89.99929809570312 358.33282470703125 449.51898193359375 393.7961730957031 "switch-to-buffer
Select a buffer for Emacs to be active in and display it in the
current window so users can look at it. Usually bound to C-x b.
" 6 0) (89.99923706054688 405.7327880859375 449.5954284667969 441.1873474121094 "set-buffer
Switch Emacs’ attention to a buffer on which programs will run.
Don’t alter what the window is showing.
" 7 0) (89.99992370605469 453.1328125 407.3122253417969 476.58734130859375 "buffer-size
Return the number of characters in the current buffer.
" 8 0) (90.00003051757812 486.80914306640625 449.39996337890625 523.9873657226562 "point
Return the value of the current position of the cursor, as an
integer counting the number of characters from the beginning of
the buffer.
" 9 0) (90.00067138671875 536.052734375 449.4986267089844 571.3873291015625 "point-min
Return the minimum permissible value of point in the current
buffer. This is 1, unless narrowing is in effect.
" 10 0) (90.00077819824219 583.4527587890625 449.47662353515625 630.787353515625 "point-max
Return the value of the maximum permissible value of point in
the current buffer. This is the end of the buffer, unless narrowing
is in effect.
" 11 0)) (68 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "50
Chapter 3: How To Write Function Definitions
" 0 0) (89.99932861328125 94.10033416748047 191.3380126953125 108.46088409423828 "3.12 Exercises
" 1 0) (98.99920654296875 114.20905303955078 449.69317626953125 178.2672576904297 "• Write a non-interactive function that doubles the value of its argument,
a number. Make that function interactive.
• Write a function that tests whether the current value of fill-column
is greater than the argument passed to the function, and if so, prints an
appropriate message.
" 2 0)) (69 (90.0 47.60907745361328 449.6835632324219 60.90726852416992 "Finding More Information
51
" 0 0) (89.99990844726562 75.14844512939453 385.9106140136719 92.38106536865234 "4 A Few Buffer–Related Functions
" 1 0) (89.99786376953125 106.64917755126953 449.40869140625 191.70738220214844 "In this chapter we study in detail several of the functions used in GNU
Emacs. This is called a “walk-through”. These functions are used as ex-
amples of Lisp code, but are not imaginary examples; with the exception of
the first, simplified function definition, these functions show the actual code
used in GNU Emacs. You can learn a great deal from these definitions. The
functions described here are all related to buffers. Later, we will study other
functions.
" 2 0) (89.9979248046875 210.740478515625 304.238525390625 225.10101318359375 "4.1 Finding More Information
" 3 0) (89.99746704101562 233.60919189453125 449.29949951171875 288.64990234375 "In this walk-through, I will describe each new function as we come to it,
sometimes in detail and sometimes briefly. If you are interested, you can get
the full documentation of any Emacs Lisp function at any time by typing
C-h f and then the name of the function (and then ⟨
" 4 0) (348.2279968261719 272.75201416015625 366.3479919433594 273.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (348.239990234375 274.0824279785156 366.3401184082031 282.0525207519531 "RET
" 6 0) (348.2279968261719 281.3919677734375 366.3479919433594 281.8719787597656 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (89.999755859375 269.48907470703125 449.7926940917969 312.52978515625 "⟩). Similarly, you
can get the full documentation for a variable by typing C-h v and then the
name of the variable (and then ⟨
" 8 0) (244.42800903320312 296.75201416015625 262.5480041503906 297.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (244.44000244140625 297.9624328613281 262.54010009765625 305.9325256347656 "RET
" 10 0) (244.42800903320312 305.27203369140625 262.5480041503906 305.7520446777344 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (90.00039672851562 293.36907958984375 449.4324951171875 351.0498046875 "⟩).
In versions 20 and higher, when a function is written in Emacs Lisp,
describe-function will also tell you the location of the function definition.
If you move point over the file name and press the ⟨
" 12 0) (341.7480163574219 335.2720031738281 359.8680114746094 335.75201416015625 "<image: None, width: 1, height: 1, bpc: 1>" 13 1) (341.760009765625 336.482421875 359.8601379394531 344.4525146484375 "RET
" 14 0) (341.7480163574219 343.7919921875 359.8680114746094 344.2720031738281 "<image: None, width: 1, height: 1, bpc: 1>" 15 1) (89.99880981445312 331.5290832519531 449.82550048828125 478.60980224609375 "⟩ key, which is this
case means help-follow rather than ‘return’ or ‘enter’, Emacs will take you
directly to the function definition.
More generally, if you want to see a function in its original source file,
you can use the find-tags function to jump to it. find-tags works with
a wide variety of languages, not just Lisp, and C, and it works with non-
programming text as well. For example, find-tags will jump to the various
nodes in the Texinfo source file of this document.
The find-tags function depends on ‘tags tables’ that record the locations
of the functions, variables, and other items to which find-tags jumps.
To use the find-tags command, type M-. (i.e., type the ⟨
" 16 0) (381.1080017089844 462.7120056152344 406.4280090332031 463.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 17 1) (381.1199951171875 464.04241943359375 406.406494140625 472.01251220703125 "META
" 18 0) (381.1080017089844 471.35198974609375 406.4280090332031 471.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 19 1) (90.00018310546875 459.0890808105469 450.0108337402344 490.48980712890625 "⟩ key and
the period key at the same time, or else type the ⟨
" 20 0) (337.4280090332031 474.7120056152344 354.1080017089844 475.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 21 1) (337.44000244140625 475.92242431640625 353.9859619140625 483.89251708984375 "ESC
" 22 0) (337.4280090332031 483.35198974609375 354.1080017089844 483.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 23 1) (90.00003051757812 470.9690856933594 449.90167236328125 526.3698120117188 "⟩ key and then type
the period key), and then, at the prompt, type in the name of the function
whose source code you want to see, such as mark-whole-buffer, and then
type ⟨
" 24 0) (118.30799865722656 510.59197998046875 136.42799377441406 511.0719909667969 "<image: None, width: 1, height: 1, bpc: 1>" 25 1) (118.31999969482422 511.8024597167969 136.4201202392578 519.7725830078125 "RET
" 26 0) (118.30799865722656 519.1119995117188 136.42799377441406 519.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 27 1) (90.00003051757812 507.2091064453125 449.4978332519531 549.8897705078125 "⟩. Emacs will switch buffers and display the source code for the
function on your screen. To switch back to your current buffer, type C-x b
⟨
" 28 0) (92.86800384521484 534.4719848632812 110.98800659179688 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 29 1) (92.87999725341797 535.6824340820312 110.98011779785156 543.652587890625 "RET
" 30 0) (92.86800384521484 543.1119995117188 110.98800659179688 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 31 1) (110.5199966430664 531.089111328125 248.74658203125 550.2498168945312 "⟩. (On some keyboards, the ⟨
" 32 0) (248.0279998779297 534.4719848632812 273.3479919433594 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 33 1) (248.0399932861328 535.6824340820312 273.3265075683594 543.652587890625 "META
" 34 0) (248.0279998779297 543.1119995117188 273.3479919433594 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 35 1) (272.760009765625 530.7290649414062 354.5865783691406 550.2498168945312 "⟩ key is labelled ⟨
" 36 0) (353.8680114746094 534.4719848632812 371.02801513671875 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 37 1) (353.8800048828125 535.6824340820312 370.9014587402344 543.652587890625 "ALT
" 38 0) (353.8680114746094 543.1119995117188 371.02801513671875 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 39 1) (89.99786376953125 531.089111328125 450.0957946777344 630.787353515625 "⟩.)
Depending on how the initial default values of your copy of Emacs are
set, you may also need to specify the location of your ‘tags table’, which
is a file called ‘TAGS’. For example, if you are interested in Emacs sources,
the tags table you will most likely want, if it has already been created for
you, will be in a subdirectory of the ‘/usr/local/share/emacs/’ direc-
tory; thus you would use the M-x visit-tags-table command and spec-
ify a pathname such as ‘/usr/local/share/emacs/21.0.100/lisp/TAGS’
" 40 0)) (70 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "52
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.99884033203125 77.48908233642578 449.21343994140625 102.66727447509766 "or ‘/usr/local/src/emacs/lisp/TAGS’. If the tags table has not already
been created, you will have to create it yourself.
" 1 0) (89.9990234375 107.12909698486328 449.3988342285156 156.1873016357422 "To create a ‘TAGS’ file in a specific directory, switch to that directory
in Emacs using M-x cd command, or list the directory with C-x d (dired).
Then run the compile command, with etags *.el as the command to exe-
cute
" 2 0) (111.59941864013672 164.85763549804688 252.54220581054688 173.8240203857422 "M-x compile RET etags *.el RET
" 3 0) (89.99945068359375 178.52911376953125 449.1486511230469 203.8273162841797 "For more information, see Section 12.5, “Create Your Own ‘TAGS’ File”,
page 163.
" 4 0) (89.99884033203125 208.04913330078125 449.3875732421875 245.2273406982422 "After you become more familiar with Emacs Lisp, you will find that you
will frequently use find-tags to navigate your way around source code; and
you will create your own ‘TAGS’ tables.
" 5 0) (89.99884033203125 249.56903076171875 449.3661193847656 370.3872375488281 "Incidentally, the files that contain Lisp code are conventionally called
libraries. The metaphor is derived from that of a specialized library, such as
a law library or an engineering library, rather than a general library. Each
library, or file, contains functions that relate to a particular topic or activity,
such as ‘abbrev.el’ for handling abbreviations and other typing shortcuts,
and ‘help.el’ for on-line help. (Sometimes several libraries provide code
for a single activity, as the various ‘rmail...’ files provide code for reading
electronic mail.) In The GNU Emacs Manual, you will see sentences such as
“The C-h p command lets you search the standard Emacs Lisp libraries by
topic keywords.”
" 6 0) (89.99909973144531 401.1803283691406 426.8679504394531 415.5535583496094 "4.2 A Simplified beginning-of-buffer Definition
" 7 0) (89.99945068359375 426.9290466308594 449.3887634277344 488.1160583496094 "The beginning-of-buffer command is a good function to start with
since you are likely to be familiar with it and it is easy to understand. Used
as an interactive command, beginning-of-buffer moves the cursor to the
beginning of the buffer, leaving the mark at the previous position.
It is
generally bound to M-<.
" 8 0) (89.99887084960938 492.32904052734375 449.34490966796875 553.3872680664062 "In this section, we will discuss a shortened version of the function that
shows how it is most frequently used.
This shortened function works as
written, but it does not contain the code for a complex option. In another
section, we will describe the entire function. (See Section 5.3, “Complete
Definition of beginning-of-buffer”, page 69.)
" 9 0) (89.99856567382812 557.7290649414062 449.453125 630.7872924804688 "Before looking at the code, let’s consider what the function definition has
to contain: it must include an expression that makes the function interactive
so it can be called by typing M-x beginning-of-buffer or by typing a
keychord such as C-<; it must include code to leave a mark at the original
position in the buffer; and it must include code to move the cursor to the
beginning of the buffer.
" 10 0)) (71 (90.0 47.60907745361328 449.5094299316406 60.90726852416992 "A Simplified beginning-of-buffer Definition
53
" 0 0) (105.00076293945312 80.36908721923828 420.15325927734375 93.66727447509766 "Here is the complete text of the shortened version of the function:
" 1 0) (90.00039672851562 99.57760620117188 449.3782043457031 277.2670593261719 "(defun simplified-beginning-of-buffer ()
\"Move point to the beginning of the buffer;
leave mark at previous position.\"
(interactive)
(push-mark)
(goto-char (point-min)))
Like all function definitions, this definition has five parts following the
special form defun:
1. The name: in this example, simplified-beginning-of-buffer.
2. A list of the arguments: in this example, an empty list, (),
3. The documentation string.
4. The interactive expression.
5. The body.
" 2 0) (89.99948120117188 282.56884765625 449.48712158203125 385.3870544433594 "In this function definition, the argument list is empty; this means that this
function does not require any arguments. (When we look at the definition
for the complete function, we will see that it may be passed an optional
argument.)
The interactive expression tells Emacs that the function is intended to be
used interactively. In this example, interactive does not have an argument
because simplified-beginning-of-buffer does not require one.
The body of the function consists of the two lines:
" 3 0) (89.99844360351562 391.1773986816406 449.5838317871094 636.6495971679688 "(push-mark)
(goto-char (point-min))
The first of these lines is the expression, (push-mark). When this ex-
pression is evaluated by the Lisp interpreter, it sets a mark at the current
position of the cursor, wherever that may be. The position of this mark is
saved in the mark ring.
The next line is (goto-char (point-min)). This expression jumps the
cursor to the minimum point in the buffer, that is, to the beginning of the
buffer (or to the beginning of the accessible portion of the buffer if it is
narrowed. See Chapter 6, “Narrowing and Widening”, page 77.)
The push-mark command sets a mark at the place where the cursor was
located before it was moved to the beginning of the buffer by the (goto-
char (point-min)) expression. Consequently, you can, if you wish, go back
to where you were originally by typing C-x C-x.
That is all there is to the function definition!
When you are reading code such as this and come upon an unfamiliar
function, such as goto-char, you can find out what it does by using the
describe-function command. To use this command, type C-h f and then
type in the name of the function and press ⟨
" 4 0) (300.947998046875 620.8720092773438 319.0679931640625 621.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (300.9599914550781 622.0823974609375 319.06011962890625 630.0525512695312 "RET
" 6 0) (300.947998046875 629.3919677734375 319.0679931640625 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (318.6000061035156 617.4890747070312 450.3489074707031 636.289794921875 "⟩. The describe-function
" 8 0)) (72 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "54
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.9993896484375 77.48908233642578 449.35546875 102.66727447509766 "command will print the function’s documentation string in a ‘*Help*’ win-
dow. For example, the documentation for goto-char is:
" 1 0) (89.99880981445312 108.81759643554688 449.3445739746094 188.9297637939453 "One arg, a number.
Set point to that number.
Beginning of buffer is position (point-min),
end is (point-max).
(The prompt for describe-function will offer you the symbol under or
preceding the cursor, so you can save typing by positioning the cursor right
over or after the function and then typing C-h f ⟨
" 2 0) (327.1080017089844 173.1519775390625 345.2279968261719 173.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 3 1) (327.1199951171875 174.36244201660156 345.2201232910156 182.33255004882812 "RET
" 4 0) (327.1080017089844 181.6719970703125 345.2279968261719 182.15199279785156 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (89.99908447265625 169.76904296875 449.6611022949219 233.94725036621094 "⟩.)
The end-of-buffer function definition is written in the same way as
the beginning-of-buffer definition except that the body of the function
contains the expression (goto-char (point-max)) in place of (goto-char
(point-min)).
" 6 0) (89.99909210205078 254.90032958984375 371.3376159667969 269.2735595703125 "4.3 The Definition of mark-whole-buffer
" 7 0) (89.999267578125 278.1290283203125 449.4877014160156 381.5472106933594 "The mark-whole-buffer function is no harder to understand than the
simplified-beginning-of-buffer function. In this case, however, we will
look at the complete function, not a shortened version.
The mark-whole-buffer function is not as commonly used as the
beginning-of-buffer function, but is useful nonetheless: it marks a whole
buffer as a region by putting point at the beginning and a mark at the end
of the buffer. It is generally bound to C-x h.
In GNU Emacs 20, the code for the complete function looks like this:
" 8 0) (90.00177001953125 387.69757080078125 449.4015808105469 487.6272277832031 "(defun mark-whole-buffer ()
\"Put point at beginning and mark at end of buffer.\"
(interactive)
(push-mark (point))
(push-mark (point-max))
(goto-char (point-min)))
Like all other functions, the mark-whole-buffer function fits into the
template for a function definition. The template looks like this:
" 9 0) (90.00222778320312 493.7751770019531 449.6968078613281 630.7872314453125 "(defun name-of-function (argument-list)
\"documentation...\"
(interactive-expression...)
body...)
Here is how the function works: the name of the function is mark-whole-
buffer; it is followed by an empty argument list, ‘()’, which means that the
function does not require arguments. The documentation comes next.
The next line is an (interactive) expression that tells Emacs that
the function will be used interactively.
These details are similar to the
simplified-beginning-of-buffer function described in the previous sec-
tion.
" 10 0)) (73 (90.0 47.60907745361328 449.6732482910156 60.90726852416992 "Body of mark-whole-buffer
55
" 0 0) (90.00057983398438 78.2418212890625 297.62017822265625 91.35738372802734 "4.3.1 Body of mark-whole-buffer
" 1 0) (90.00100708007812 100.16907501220703 449.3463134765625 125.4672622680664 "The body of the mark-whole-buffer function consists of three lines of
code:
" 2 0) (89.99725341796875 131.13760375976562 449.5634460449219 445.369873046875 "(push-mark (point))
(push-mark (point-max))
(goto-char (point-min))
The first of these lines is the expression, (push-mark (point)).
This line does exactly the same job as the first line of the body of
the simplified-beginning-of-buffer function, which is written (push-
mark). In both cases, the Lisp interpreter sets a mark at the current position
of the cursor.
I don’t know why the expression in mark-whole-buffer is written (push-
mark (point)) and the expression in beginning-of-buffer is written
(push-mark). Perhaps whoever wrote the code did not know that the ar-
guments for push-mark are optional and that if push-mark is not passed an
argument, the function automatically sets mark at the location of point by
default. Or perhaps the expression was written so as to parallel the struc-
ture of the next line. In any case, the line causes Emacs to determine the
position of point and set a mark there.
The next line of mark-whole-buffer is (push-mark (point-max). This
expression sets a mark at the point in the buffer that has the highest number.
This will be the end of the buffer (or, if the buffer is narrowed, the end of the
accessible portion of the buffer. See Chapter 6, “Narrowing and Widening”,
page 77, for more about narrowing.)
After this mark has been set, the
previous mark, the one set at point, is no longer set, but Emacs remembers
its position, just as all other recent marks are always remembered. This
means that you can, if you wish, go back to that position by typing C-u
C-⟨
" 3 0) (104.38800048828125 429.9519958496094 121.06800079345703 430.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (104.4000015258789 431.1624450683594 120.9459457397461 439.1325378417969 "SPC
" 5 0) (104.38800048828125 438.47198486328125 121.06800079345703 438.9519958496094 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99981689453125 426.2090759277344 449.3128356933594 466.5072937011719 "⟩ twice.
(In GNU Emacs 21, the (push-mark (point-max) is slightly more com-
plicated than shown here. The line reads
" 7 0) (89.99786376953125 472.2976379394531 449.976318359375 630.787353515625 "(push-mark (point-max) nil t)
(The expression works nearly the same as before.
It sets a mark at the
highest numbered place in the buffer that it can. However, in this version,
push-mark has two additional arguments. The second argument to push-
mark is nil. This tells the function it should display a message that says
‘Mark set’ when it pushes the mark. The third argument is t. This tells
push-mark to activate the mark when Transient Mark mode is turned on.
Transient Mark mode highlights the currently active region. It is usually
turned off.)
Finally, the last line of the function is (goto-char (point-min))). This
is written exactly the same way as it is written in beginning-of-buffer.
The expression moves the cursor to the minimum point in the buffer, that is,
to the beginning of the buffer (or to the beginning of the accessible portion
" 8 0)) (74 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "56
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.99887084960938 77.48908233642578 449.39886474609375 114.66727447509766 "of the buffer). As a result of this, point is placed at the beginning of the
buffer and mark is set at the end of the buffer. The whole buffer is, therefore,
the region.
" 1 0) (89.99887084960938 141.5003662109375 363.90606689453125 155.8735809326172 "4.4 The Definition of append-to-buffer
" 2 0) (89.99874877929688 166.1690673828125 449.48590087890625 215.34727478027344 "The append-to-buffer command is very nearly as simple as the mark-
whole-buffer command. What it does is copy the region (that is, the part
of the buffer between point and mark) from the current buffer to a specified
buffer.
" 3 0) (89.99859619140625 218.60906982421875 450.0857238769531 303.6672668457031 "The append-to-buffer command uses the insert-buffer-substring
function to copy the region. insert-buffer-substring is described by its
name: it takes a string of characters from part of a buffer, a “substring”, and
inserts them into another buffer. Most of append-to-buffer is concerned
with setting up the conditions for insert-buffer-substring to work: the
code must specify both the buffer to which the text will go and the region
that will be copied. Here is the complete text of the function:
" 4 0) (111.59902954101562 311.2575988769531 360.5087585449219 345.06396484375 "(defun append-to-buffer (buffer start end)
\"Append to specified buffer the text of the region.
It is inserted into that buffer before its point.
" 5 0) (111.59835815429688 353.2575988769531 388.7680358886719 449.4641418457031 "When calling from a program, give three arguments:
a buffer or the name of one, and two character numbers
specifying the portion of the current buffer to be copied.\"
(interactive \"BAppend to buffer: \\nr\")
(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
" 6 0) (89.99880981445312 453.3292236328125 449.32196044921875 478.6274108886719 "The function can be understood by looking at it as a series of filled-in
templates.
" 7 0) (89.99908447265625 481.88922119140625 449.3765869140625 507.1874084472656 "The outermost template is for the function definition. In this function,
it looks like this (with several slots filled in):
" 8 0) (111.59933471679688 514.7777709960938 308.9515075683594 561.064208984375 "(defun append-to-buffer (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
body...)
" 9 0) (89.99948120117188 565.0491943359375 449.4534912109375 602.2274169921875 "The first line of the function includes its name and three arguments. The
arguments are the buffer to which the text will be copied, and the start
and end of the region in the current buffer that will be copied.
" 10 0) (89.99887084960938 605.4892578125 449.4425354003906 630.7874755859375 "The next part of the function is the documentation, which is clear and
complete.
" 11 0)) (75 (90.0 47.60907745361328 449.6504821777344 60.90726852416992 "The Body of append-to-buffer
57
" 0 0) (89.99981689453125 78.2418212890625 413.8818054199219 91.35738372802734 "4.4.1 The append-to-buffer Interactive Expression
" 1 0) (89.99908447265625 101.60907745361328 449.7373962402344 150.7872772216797 "Since the append-to-buffer function will be used interactively, the func-
tion must have an interactive expression. (For a review of interactive,
see Section 3.3, “Making a Function Interactive”, page 33.) The expression
reads as follows:
" 2 0) (89.99609375 158.01760864257812 449.4083251953125 323.5873107910156 "(interactive \"BAppend to buffer: \\nr\")
This expression has an argument inside of quotation marks and that argu-
ment has two parts, separated by ‘\\n’.
The first part is ‘BAppend to buffer: ’. Here, the ‘B’ tells Emacs to ask
for the name of the buffer that will be passed to the function. Emacs will
ask for the name by prompting the user in the minibuffer, using the string
following the ‘B’, which is the string ‘Append to buffer: ’.
Emacs then
binds the variable buffer in the function’s argument list to the specified
buffer.
The newline, ‘\\n’, separates the first part of the argument from the second
part. It is followed by an ‘r’ that tells Emacs to bind the two arguments
that follow the symbol buffer in the function’s argument list (that is, start
and end) to the values of point and mark.
" 3 0) (89.99641418457031 343.5618591308594 321.0094909667969 356.67742919921875 "4.4.2 The Body of append-to-buffer
" 4 0) (89.99420166015625 367.0491027832031 449.4703063964844 484.3872985839844 "The body of the append-to-buffer function begins with let.
As we have seen before (see Section 3.6, “let”, page 36), the purpose of
a let expression is to create and give initial values to one or more variables
that will only be used within the body of the let. This means that such
a variable will not be confused with any variable of the same name outside
the let expression.
We can see how the let expression fits into the function as a whole
by showing a template for append-to-buffer with the let expression in
outline:
" 5 0) (111.59420013427734 491.6176452636719 308.94635009765625 550.384033203125 "(defun append-to-buffer (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
(let ((variable value))
body...)
" 6 0) (104.99437713623047 554.0091552734375 291.63775634765625 567.307373046875 "The let expression has three elements:
" 7 0) (95.87387084960938 571.1691284179688 191.51376342773438 584.4673461914062 "1. The symbol let;
" 8 0) (95.87383270263672 588.3291015625 449.2298278808594 613.6273193359375 "2. A varlist containing, in this case, a single two-element list, (variable
value);
" 9 0) (95.87357330322266 617.4891357421875 265.2915954589844 630.787353515625 "3. The body of the let expression.
" 10 0)) (76 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "58
Chapter 4: A Few Buffer–Related Functions
" 0 0) (104.9993896484375 86.24909210205078 398.3338623046875 99.54727935791016 "In the append-to-buffer function, the varlist looks like this:
" 1 0) (111.59976196289062 111.21762084960938 228.67115783691406 120.18400573730469 "(oldbuf (current-buffer))
" 2 0) (89.99960327148438 128.00909423828125 449.46478271484375 177.1873016357422 "In this part of the let expression, the one variable, oldbuf, is bound to the
value returned by the (current-buffer) expression. The variable, oldbuf,
is used to keep track of the buffer in which you are working and from which
you will copy.
" 3 0) (89.99981689453125 184.52911376953125 449.464599609375 233.7073211669922 "The element or elements of a varlist are surrounded by a set of parentheses
so the Lisp interpreter can distinguish the varlist from the body of the let.
As a consequence, the two-element list within the varlist is surrounded by a
circumscribing set of parentheses. The line looks like this:
" 4 0) (111.60049438476562 245.37765502929688 261.50067138671875 266.8240051269531 "(let ((oldbuf (current-buffer)))
... )
" 5 0) (89.99920654296875 274.88909912109375 449.2578125 324.0672912597656 "The two parentheses before oldbuf might surprise you if you did not realize
that the first parenthesis before oldbuf marks the boundary of the varlist
and the second parenthesis marks the beginning of the two-element list,
(oldbuf (current-buffer)).
" 6 0) (89.99931335449219 357.60186767578125 351.45758056640625 370.7174377441406 "4.4.3 save-excursion in append-to-buffer
" 7 0) (89.99945068359375 385.40911865234375 449.45306396484375 410.7073059082031 "The body of the let expression in append-to-buffer consists of a save-
excursion expression.
" 8 0) (89.99969482421875 418.04913330078125 449.4207763671875 479.1073303222656 "The save-excursion function saves the locations of point and mark,
and restores them to those positions after the expressions in the body of the
save-excursion complete execution. In addition, save-excursion keeps
track of the original buffer, and restores it. This is how save-excursion is
used in append-to-buffer.
" 9 0) (90.00015258789062 486.56915283203125 449.4225158691406 547.7473754882812 "Incidentally, it is worth noting here that a Lisp function is normally for-
matted so that everything that is enclosed in a multi-line spread is indented
more to the right than the first symbol. In this function definition, the let
is indented more than the defun, and the save-excursion is indented more
than the let, like this:
" 10 0) (111.60150146484375 559.417724609375 200.54954528808594 630.6640625 "(defun ...
...
...
(let...
(save-excursion
...
" 11 0)) (77 (90.0 47.60907745361328 449.57415771484375 60.90726852416992 "save-excursion in append-to-buffer
59
" 0 0) (89.99896240234375 81.68909454345703 449.3990783691406 130.74729919433594 "This formatting convention makes it easy to see that the two lines in the
body of the save-excursion are enclosed by the parentheses associated
with save-excursion, just as the save-excursion itself is enclosed by the
parentheses associated with the let:
" 1 0) (111.59886169433594 137.85763549804688 341.7973327636719 184.1439666748047 "(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
" 2 0) (89.99932861328125 188.60906982421875 449.3766174316406 213.9072723388672 "The use of the save-excursion function can be viewed as a process of
filling in the slots of a template:
" 3 0) (111.59921264648438 221.01760864257812 226.0409698486328 279.7839050292969 "(save-excursion
first-expression-in-body
second-expression-in-body
...
last-expression-in-body)
" 4 0) (89.99874877929688 284.2490234375 449.3550109863281 309.4272155761719 "In this function, the body of the save-excursion contains only two expres-
sions. The body looks like this:
" 5 0) (89.99810791015625 316.5375671386719 449.7251281738281 498.5472412109375 "(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end)
When the append-to-buffer function is evaluated, the two expressions
in the body of the save-excursion are evaluated in sequence. The value of
the last expression is returned as the value of the save-excursion function;
the other expression is evaluated only for its side effects.
The first line in the body of the save-excursion uses the set-buffer
function to change the current buffer to the one specified in the first argument
to append-to-buffer. (Changing the buffer is the side effect; as we have
said before, in Lisp, a side effect is often the primary thing we want.) The
second line does the primary work of the function.
The set-buffer function changes Emacs’ attention to the buffer to which
the text will be copied and from which save-excursion will return.
The line looks like this:
" 6 0) (89.99884033203125 505.5376281738281 449.6275634765625 630.7872924804688 "(set-buffer (get-buffer-create buffer))
The innermost expression of this list is (get-buffer-create buffer).
This expression uses the get-buffer-create function, which either gets the
named buffer, or if it does not exist, creates one with the given name. This
means you can use append-to-buffer to put text into a buffer that did not
previously exist.
get-buffer-create also keeps set-buffer from getting an unnecessary
error: set-buffer needs a buffer to go to; if you were to specify a buffer that
does not exist, Emacs would baulk. Since get-buffer-create will create a
buffer if none exists, set-buffer is always provided with a buffer.
" 7 0)) (78 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "60
Chapter 4: A Few Buffer–Related Functions
" 0 0) (104.9993896484375 81.68909454345703 449.27874755859375 94.9872817993164 "The last line of append-to-buffer does the work of appending the text:
" 1 0) (89.99887084960938 102.21762084960938 449.83551025390625 231.90733337402344 "(insert-buffer-substring oldbuf start end)
The insert-buffer-substring function copies a string from the buffer
specified as its first argument and inserts the string into the present buffer.
In this case, the argument to insert-buffer-substring is the value of the
variable created and bound by the let, namely the value of oldbuf, which
was the current buffer when you gave the append-to-buffer command.
After insert-buffer-substring has done its work, save-excursion
will restore the action to the original buffer and append-to-buffer will
have done its job.
Written in skeletal form, the workings of the body look like this:
" 2 0) (111.5992431640625 239.0152587890625 392.71527099609375 285.3039855957031 "(let (bind-oldbuf-to-value-of-current-buffer)
(save-excursion
; Keep track of buffer.
change-buffer
insert-substring-from-oldbuf-into-buffer)
" 3 0) (111.59930419921875 301.29522705078125 337.39544677734375 322.7439880371094 "change-back-to-original-buffer-when-finished
let-the-local-meaning-of-oldbuf-disappear-when-finished
" 4 0) (89.99819946289062 338.72906494140625 449.51812744140625 451.8672790527344 "In summary, append-to-buffer works as follows: it saves the value of the
current buffer in the variable called oldbuf. It gets the new buffer, creating
one if need be, and switches Emacs to it. Using the value of oldbuf, it
inserts the region of text from the old buffer into the new buffer; and then
using save-excursion, it brings you back to your original buffer.
In looking at append-to-buffer, you have explored a fairly complex
function. It shows how to use let and save-excursion, and how to change
to and come back from another buffer. Many function definitions use let,
save-excursion, and set-buffer this way.
" 5 0) (89.99848937988281 476.9003601074219 169.8894805908203 491.2608947753906 "4.5 Review
" 6 0) (104.99848937988281 501.2090759277344 449.2343444824219 514.5072631835938 "Here is a brief summary of the various functions discussed in this chapter.
" 7 0) (89.99807739257812 525.252685546875 449.2018127441406 572.5960693359375 "describe-function
describe-variable
Print the documentation for a function or variable. Convention-
ally bound to C-h f and C-h v.
" 8 0) (89.9984130859375 581.609130859375 449.4854736328125 636.6498413085938 "find-tag
Find the file containing the source for a function or variable and
switch buffers to it, positioning point at the beginning of the
item. Conventionally bound to M-. (that’s a period following
the ⟨
" 9 0) (169.30799865722656 620.8720092773438 194.62799072265625 621.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (169.32000732421875 622.0823974609375 194.6065216064453 630.0525512695312 "META
" 11 0) (169.30799865722656 629.3919677734375 194.62799072265625 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (194.0399932861328 617.1290893554688 224.3890838623047 636.289794921875 "⟩ key).
" 13 0)) (79 (90.0 47.60907745361328 449.8256530761719 60.90726852416992 "Exercises
61
" 0 0) (90.0 79.33271789550781 449.3671569824219 126.66727447509766 "save-excursion
Save the location of point and mark and restore their values after
the arguments to save-excursion have been evaluated. Also,
remember the current buffer and return to it.
" 1 0) (89.99972534179688 133.0927276611328 449.4967346191406 192.4272918701172 "push-mark
Set mark at a location and record the value of the previous mark
on the mark ring. The mark is a location in the buffer that will
keep its relative position even if text is added to or removed
from the buffer.
" 2 0) (89.9984359741211 198.8527374267578 449.5509033203125 246.1873016357422 "goto-char
Set point to the location specified by the value of the argument,
which can be a number, a marker, or an expression that returns
the number of a position, such as (point-min).
" 3 0) (89.99832153320312 252.6127471923828 449.38671875 288.0672912597656 "insert-buffer-substring
Copy a region of text from a buffer that is passed to the function
as an argument and insert the region into the current buffer.
" 4 0) (89.99722290039062 294.49273681640625 441.1276550292969 317.95611572265625 "mark-whole-buffer
Mark the whole buffer as a region. Normally bound to C-x h.
" 5 0) (89.9969482421875 324.37274169921875 449.5276184082031 371.7073059082031 "set-buffer
Switch the attention of Emacs to another buffer, but do not
change the window being displayed. Used when the program
rather than a human is to work on a different buffer.
" 6 0) (89.99609375 378.13275146484375 449.46087646484375 437.4673156738281 "get-buffer-create
get-buffer
Find a named buffer or create one if a buffer of that name does
not exist. The get-buffer function returns nil if the named
buffer does not exist.
" 7 0) (89.99528503417969 455.660400390625 183.29995727539062 470.02093505859375 "4.6 Exercises
" 8 0) (98.99493408203125 475.7691345214844 449.3077697753906 550.6928100585938 "• Write your own simplified-end-of-buffer function definition; then
test it to see whether it works.
• Use if and get-buffer to write a function that prints a message telling
you whether a buffer exists.
• Using find-tag, find the source for the copy-to-buffer function.
" 9 0)) (80 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "62
Chapter 4: A Few Buffer–Related Functions
" 0 0)) (81 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "The Definition of copy-to-buffer
63
" 0 0) (90.0001220703125 75.14844512939453 384.7303466796875 92.38106536865234 "5 A Few More Complex Functions
" 1 0) (89.9990234375 107.36908721923828 449.5304260253906 180.4272918701172 "In this chapter, we build on what we have learned in previous chapters by
looking at more complex functions. The copy-to-buffer function illustrates
use of two save-excursion expressions in one definition, while the insert-
buffer function illustrates use of an asterisk in an interactive expression,
use of or, and the important distinction between a name and the object to
which the name refers.
" 2 0) (89.99909210205078 200.06036376953125 349.16363525390625 214.43357849121094 "5.1 The Definition of copy-to-buffer
" 3 0) (89.99795532226562 223.049072265625 449.5188903808594 322.8672790527344 "After understanding how append-to-buffer works, it is easy to under-
stand copy-to-buffer.
This function copies text into a buffer, but in-
stead of adding to the second buffer, it replaces the previous text in the
second buffer.
The code for the copy-to-buffer function is almost the
same as the code for append-to-buffer, except that erase-buffer and
a second save-excursion are used. (See Section 4.4, “The Definition of
append-to-buffer”, page 56, for the description of append-to-buffer.)
The body of copy-to-buffer looks like this
" 4 0) (89.998291015625 328.6576232910156 449.4534606933594 553.6273803710938 "...
(interactive \"BCopy to buffer: \\nr\")
(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(erase-buffer)
(save-excursion
(insert-buffer-substring oldbuf start end)))))
This code is similar to the code in append-to-buffer: it is only after
changing to the buffer to which the text will be copied that the definition
for this function diverges from the definition for append-to-buffer: the
copy-to-buffer function erases the buffer’s former contents. (This is what
is meant by ‘replacement’; to replace text, Emacs erases the previous text
and then inserts new text.) After erasing the previous contents of the buffer,
save-excursion is used for a second time and the new text is inserted.
Why is save-excursion used twice? Consider again what the function
does.
In outline, the body of copy-to-buffer looks like this:
" 5 0) (111.599365234375 559.415283203125 368.859130859375 630.6640625 "(let (bind-oldbuf-to-value-of-current-buffer)
(save-excursion
; First use of save-excursion.
change-buffer
(erase-buffer)
(save-excursion
; Second use of save-excursion.
insert-substring-from-oldbuf-into-buffer)))
" 6 0)) (82 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "64
Chapter 5: A Few More Complex Functions
" 0 0) (89.99850463867188 77.48908233642578 449.857421875 198.3072967529297 "The first use of save-excursion returns Emacs to the buffer from which
the text is being copied. That is clear, and is just like its use in append-
to-buffer.
Why the second use?
The reason is that insert-buffer-
substring always leaves point at the end of the region being inserted. The
second save-excursion causes Emacs to leave point at the beginning of the
text being inserted. In most circumstances, users prefer to find point at the
beginning of inserted text. (Of course, the copy-to-buffer function returns
the user to the original buffer when done—but if the user then switches to
the copied-to buffer, point will go to the beginning of the text. Thus, this
use of a second save-excursion is a little nicety.)
" 1 0) (89.99812316894531 224.06036376953125 341.7313537597656 238.43357849121094 "5.2 The Definition of insert-buffer
" 2 0) (89.9962158203125 248.48907470703125 449.5498352050781 337.8672790527344 "insert-buffer is yet another buffer-related function.
This command
copies another buffer into the current buffer. It is the reverse of append-
to-buffer or copy-to-buffer, since they copy a region of text from the
current buffer to another buffer.
In addition, this code illustrates the use of interactive with a buffer
that might be read-only and the important distinction between the name of
an object and the object actually referred to.
" 3 0) (104.99609375 341.00909423828125 184.80690002441406 354.3072814941406 "Here is the code:
" 4 0) (111.59607696533203 361.6576232910156 341.5971374511719 547.0241088867188 "(defun insert-buffer (buffer)
\"Insert after point the contents of BUFFER.
Puts mark after the inserted text.
BUFFER may be a buffer or a buffer name.\"
(interactive \"*bInsert buffer: \")
(or (bufferp buffer)
(setq buffer (get-buffer buffer)))
(let (start end newmark)
(save-excursion
(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
(insert-buffer-substring buffer start end)
(setq newmark (point)))
(push-mark newmark)))
" 5 0) (89.99786376953125 551.7291259765625 449.3534240722656 577.02734375 "As with other function definitions, you can use a template to see an
outline of the function:
" 6 0) (111.59786987304688 584.2577514648438 276.1382141113281 630.6640625 "(defun insert-buffer (buffer)
\"documentation...\"
(interactive \"*bInsert buffer: \")
body...)
" 7 0)) (83 (90.0 47.60907745361328 449.5639343261719 60.90726852416992 "The Body of the insert-buffer Function
65
" 0 0) (90.00027465820312 78.2418212890625 410.762451171875 91.35738372802734 "5.2.1 The Interactive Expression in insert-buffer
" 1 0) (89.99972534179688 101.48908233642578 449.36712646484375 126.78726959228516 "In insert-buffer, the argument to the interactive declaration has
two parts, an asterisk, ‘*’, and ‘bInsert buffer: ’.
" 2 0) (89.99920654296875 146.40179443359375 216.149658203125 159.5057830810547 "A Read-only Buffer
" 3 0) (89.99893188476562 169.6490478515625 449.48577880859375 242.82725524902344 "The asterisk is for the situation when the buffer is a read-only buffer—
a buffer that cannot be modified. If insert-buffer is called on a buffer
that is read-only, a message to this effect is printed in the echo area and
the terminal may beep or blink at you; you will not be permitted to insert
anything into current buffer. The asterisk does not need to be followed by a
newline to separate it from the next argument.
" 4 0) (89.99984741210938 262.4417724609375 290.81427001953125 275.5573425292969 "‘b’ in an Interactive Expression
" 5 0) (89.998291015625 285.68902587890625 449.85748291015625 406.6272277832031 "The next argument in the interactive expression starts with a lower case
‘b’. (This is different from the code for append-to-buffer, which uses an
upper-case ‘B’.
See Section 4.4, “The Definition of append-to-buffer”,
page 56.) The lower-case ‘b’ tells the Lisp interpreter that the argument for
insert-buffer should be an existing buffer or else its name. (The upper-
case ‘B’ option provides for the possibility that the buffer does not exist.)
Emacs will prompt you for the name of the buffer, offering you a default
buffer, with name completion enabled.
If the buffer does not exist, you
receive a message that says “No match”; your terminal may beep at you as
well.
" 6 0) (89.998291015625 426.3617858886719 387.6724853515625 439.47735595703125 "5.2.2 The Body of the insert-buffer Function
" 7 0) (89.997802734375 449.6090393066406 449.5071105957031 538.8673095703125 "The body of the insert-buffer function has two major parts: an or
expression and a let expression. The purpose of the or expression is to
ensure that the argument buffer is bound to a buffer and not just the name
of a buffer. The body of the let expression contains the code which copies
the other buffer into the current buffer.
In outline, the two expressions fit into the insert-buffer function like
this:
" 8 0) (111.59844207763672 545.8576049804688 276.1387634277344 630.6640014648438 "(defun insert-buffer (buffer)
\"documentation...\"
(interactive \"*bInsert buffer: \")
(or ...
...
(let (varlist)
body-of-let... )
" 9 0)) (84 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "66
Chapter 5: A Few More Complex Functions
" 0 0) (89.99993896484375 77.48908233642578 449.58526611328125 141.0673065185547 "To understand how the or expression ensures that the argument buffer
is bound to a buffer and not to the name of a buffer, it is first necessary to
understand the or function.
Before doing this, let me rewrite this part of the function using if so that
you can see what is done in a manner that will be familiar.
" 1 0) (89.99993896484375 156.0018310546875 399.27911376953125 169.1173858642578 "5.2.3 insert-buffer With an if Instead of an or
" 2 0) (89.99954223632812 177.6890869140625 449.4432678222656 279.7873229980469 "The job to be done is to make sure the value of buffer is a buffer itself
and not the name of a buffer. If the value is the name, then the buffer itself
must be got.
You can imagine yourself at a conference where an usher is wandering
around holding a list with your name on it and looking for you: the usher is
“bound” to your name, not to you; but when the usher finds you and takes
your arm, the usher becomes “bound” to you.
In Lisp, you might describe this situation like this:
" 3 0) (90.00009155273438 285.2176818847656 449.4981994628906 360.3073425292969 "(if (not (holding-on-to-guest))
(find-and-take-arm-of-guest))
We want to do the same thing with a buffer—if we do not have the buffer
itself, we want to get it.
Using a predicate called bufferp that tells us whether we have a buffer
(rather than its name), we can write the code like this:
" 4 0) (90.00030517578125 365.85528564453125 449.466064453125 527.107421875 "(if (not (bufferp buffer))
; if-part
(setq buffer (get-buffer buffer)))
; then-part
Here, the true-or-false-test of the if expression is (not (bufferp buffer));
and the then-part is the expression (setq buffer (get-buffer buffer)).
In the test, the function bufferp returns true if its argument is a buffer—
but false if its argument is the name of the buffer. (The last character of
the function name bufferp is the character ‘p’; as we saw earlier, such use
of ‘p’ is a convention that indicates that the function is a predicate, which is
a term that means that the function will determine whether some property
is true or false. See Section 1.8.4, “Using the Wrong Type Object as an
Argument”, page 14.)
The function not precedes the expression (bufferp buffer), so the true-
or-false-test looks like this:
" 5 0) (89.99822998046875 532.6577758789062 449.35491943359375 630.7874145507812 "(not (bufferp buffer))
not is a function that returns true if its argument is false and false if its
argument is true. So if (bufferp buffer) returns true, the not expression
returns false and vice-versa: what is “not true” is false and what is “not
false” is true.
Using this test, the if expression works as follows: when the value of
the variable buffer is actually a buffer rather then its name, the true-or-
false-test returns false and the if expression does not evaluate the then-part.
" 6 0)) (85 (90.0 47.60907745361328 449.7704772949219 60.90726852416992 "The or in the Body
67
" 0 0) (89.999755859375 77.48908233642578 449.2685241699219 102.66727447509766 "This is fine, since we do not need to do anything to the variable buffer if it
really is a buffer.
" 1 0) (89.99874877929688 108.68909454345703 449.5626525878906 193.74729919433594 "On the other hand, when the value of buffer is not a buffer itself, but
the name of a buffer, the true-or-false-test returns true and the then-part
of the expression is evaluated. In this case, the then-part is (setq buffer
(get-buffer buffer)). This expression uses the get-buffer function to
return an actual buffer itself, given its name. The setq then sets the variable
buffer to the value of the buffer itself, replacing its previous value (which
was the name of the buffer).
" 2 0) (89.9990234375 222.96185302734375 252.7234344482422 236.07740783691406 "5.2.4 The or in the Body
" 3 0) (89.99700927734375 249.4490966796875 449.4409484863281 310.6272888183594 "The purpose of the or expression in the insert-buffer function is to
ensure that the argument buffer is bound to a buffer and not just to the
name of a buffer. The previous section shows how the job could have been
done using an if expression. However, the insert-buffer function actually
uses or. To understand this, it is necessary to understand how or works.
" 4 0) (89.99600219726562 316.52911376953125 449.34100341796875 365.7073059082031 "An or function can have any number of arguments. It evaluates each
argument in turn and returns the value of the first of its arguments that is
not nil. Also, and this is a crucial feature of or, it does not evaluate any
subsequent arguments after returning the first non-nil value.
" 5 0) (104.99609375 371.84912109375 263.3631896972656 385.1473083496094 "The or expression looks like this:
" 6 0) (111.59611511230469 395.3776550292969 290.0478820800781 416.82403564453125 "(or (bufferp buffer)
(setq buffer (get-buffer buffer)))
" 7 0) (89.99453735351562 423.5691223144531 449.4162902832031 496.6273193359375 "The first argument to or is the expression (bufferp buffer). This expres-
sion returns true (a non-nil value) if the buffer is actually a buffer, and
not just the name of a buffer.
In the or expression, if this is the case,
the or expression returns this true value and does not evaluate the next
expression—and this is fine with us, since we do not want to do anything to
the value of buffer if it really is a buffer.
" 8 0) (89.99395751953125 502.5291748046875 449.535888671875 575.58740234375 "On the other hand, if the value of (bufferp buffer) is nil, which it will
be if the value of buffer is the name of a buffer, the Lisp interpreter evaluates
the next element of the or expression. This is the expression (setq buffer
(get-buffer buffer)). This expression returns a non-nil value, which is
the value to which it sets the variable buffer—and this value is a buffer
itself, not the name of a buffer.
" 9 0) (89.99322509765625 581.609130859375 449.42596435546875 630.787353515625 "The result of all this is that the symbol buffer is always bound to a buffer
itself rather than to the name of a buffer. All this is necessary because the
set-buffer function in a following line only works with a buffer itself, not
with the name to a buffer.
" 10 0)) (86 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "68
Chapter 5: A Few More Complex Functions
" 0 0) (90.00039672851562 80.48908233642578 449.2470397949219 105.66727447509766 "Incidentally, using or, the situation with the usher would be written like
this:
" 1 0) (111.60039520263672 111.57760620117188 369.3045349121094 120.54399108886719 "(or (holding-on-to-guest) (find-and-take-arm-of-guest))
" 2 0) (89.99978637695312 137.16180419921875 361.75616455078125 150.27735900878906 "5.2.5 The let Expression in insert-buffer
" 3 0) (89.99856567382812 159.20904541015625 449.4969787597656 271.1472473144531 "After ensuring that the variable buffer refers to a buffer itself and not
just to the name of a buffer, the insert-buffer function continues with a
let expression. This specifies three local variables, start, end, and newmark
and binds them to the initial value nil. These variables are used inside the
remainder of the let and temporarily hide any other occurrence of variables
of the same name in Emacs until the end of the let.
The body of the let contains two save-excursion expressions. First, we
will look at the inner save-excursion expression in detail. The expression
looks like this:
" 4 0) (89.99755859375 277.0575866699219 449.5391845703125 463.8672180175781 "(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
The expression (set-buffer buffer) changes Emacs’ attention from the
current buffer to the one from which the text will copied. In that buffer,
the variables start and end are set to the beginning and end of the buffer,
using the commands point-min and point-max. Note that we have here an
illustration of how setq is able to set two variables in the same expression.
The first argument of setq is set to the value of its second, and its third
argument is set to the value of its fourth.
After the body of the inner save-excursion is evaluated, the save-
excursion restores the original buffer, but start and end remain set to the
values of the beginning and end of the buffer from which the text will be
copied.
The outer save-excursion expression looks like this:
" 5 0) (89.99526977539062 469.7775573730469 449.42938232421875 630.7872314453125 "(save-excursion
(inner-save-excursion-expression
(go-to-new-buffer-and-set-start-and-end)
(insert-buffer-substring buffer start end)
(setq newmark (point)))
The insert-buffer-substring function copies the text into the current
buffer from the region indicated by start and end in buffer. Since the
whole of the second buffer lies between start and end, the whole of the
second buffer is copied into the buffer you are editing. Next, the value of
point, which will be at the end of the inserted text, is recorded in the variable
newmark.
After the body of the outer save-excursion is evaluated, point and mark
are relocated to their original places.
" 6 0)) (87 (90.0 47.60907745361328 449.73797607421875 60.90726852416992 "Optional Arguments
69
" 0 0) (89.9996337890625 77.48908233642578 449.650146484375 156.0497589111328 "However, it is convenient to locate a mark at the end of the newly inserted
text and locate point at its beginning. The newmark variable records the end
of the inserted text. In the last line of the let expression, the (push-mark
newmark) expression function sets a mark to this location. (The previous
location of the mark is still accessible; it is recorded on the mark ring and
you can go back to it with C-u C-⟨
" 1 0) (254.8679962158203 140.6319580078125 271.5480041503906 141.11195373535156 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (254.8800048828125 141.84242248535156 271.42596435546875 149.81253051757812 "SPC
" 3 0) (254.8679962158203 149.1519775390625 271.5480041503906 149.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00015258789062 137.2491455078125 449.7162170410156 174.42735290527344 "⟩.) Meanwhile, point is located at the
beginning of the inserted text, which is where it was before you called the
insert function.
" 5 0) (105.00015258789062 180.80914306640625 299.9017028808594 194.1073455810547 "The whole let expression looks like this:
" 6 0) (111.599609375 204.57766723632812 332.24017333984375 300.7839050292969 "(let (start end newmark)
(save-excursion
(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
(insert-buffer-substring buffer start end)
(setq newmark (point)))
(push-mark newmark))
" 7 0) (90.00018310546875 307.64898681640625 449.41094970703125 356.8271789550781 "Like the append-to-buffer function, the insert-buffer function uses
let, save-excursion, and set-buffer. In addition, the function illustrates
one way to use or. All these functions are building blocks that we will find
and use again and again.
" 8 0) (90.00017547607422 395.4202880859375 426.1179504394531 409.79351806640625 "5.3 Complete Definition of beginning-of-buffer
" 9 0) (90.00003051757812 423.0890197753906 449.3235778808594 460.2672119140625 "The basic structure of the beginning-of-buffer function has already
been discussed. (See Section 4.2, “A Simplified beginning-of-buffer Def-
inition”, page 52.) This section describes the complex part of the definition.
" 10 0) (89.99850463867188 466.4090270996094 449.6725769042969 599.3472900390625 "As previously described, when invoked without an argument, beginning-
of-buffer moves the cursor to the beginning of the buffer, leaving the mark
at the previous position. However, when the command is invoked with a
number between one and ten, the function considers that number to be a
fraction of the length of the buffer, measured in tenths, and Emacs moves
the cursor that fraction of the way from the beginning of the buffer. Thus,
you can either call this function with the key command M-<, which will move
the cursor to the beginning of the buffer, or with a key command such as
C-u 7 M-< which will move the cursor to a point 70% of the way through the
buffer. If a number bigger than ten is used for the argument, it moves to
the end of the buffer.
" 11 0) (89.99862670898438 605.489013671875 449.34417724609375 630.7872314453125 "The beginning-of-buffer function can be called with or without an
argument. The use of the argument is optional.
" 12 0)) (88 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "70
Chapter 5: A Few More Complex Functions
" 0 0) (90.00021362304688 78.2418212890625 259.23736572265625 91.34580993652344 "5.3.1 Optional Arguments
" 1 0) (89.9998779296875 104.12909698486328 449.5845642089844 153.3072967529297 "Unless told otherwise, Lisp expects that a function with an argument in
its function definition will be called with a value for that argument. If that
does not happen, you get an error and a message that says ‘Wrong number
of arguments’.
" 2 0) (89.99942016601562 158.60906982421875 449.5632629394531 219.7872772216797 "However, optional arguments are a feature of Lisp: a keyword may be
used to tell the Lisp interpreter that an argument is optional. The keyword
is &optional. (The ‘&’ in front of ‘optional’ is part of the keyword.) In a
function definition, if an argument follows the keyword &optional, a value
does not need to be passed to that argument when the function is called.
" 3 0) (90.00006103515625 225.20904541015625 449.2474060058594 250.5072479248047 "The first line of the function definition of beginning-of-buffer therefore
looks like this:
" 4 0) (111.60009002685547 260.1376037597656 308.9436340332031 269.1039733886719 "(defun beginning-of-buffer (&optional arg)
" 5 0) (104.99986267089844 275.12908935546875 318.5670166015625 288.4272766113281 "In outline, the whole function looks like this:
" 6 0) (111.59992980957031 298.0576477050781 308.9434814453125 406.6239929199219 "(defun beginning-of-buffer (&optional arg)
\"documentation...\"
(interactive \"P\")
(push-mark)
(goto-char
(if-there-is-an-argument
figure-out-where-to-go
else-go-to
(point-min))))
" 7 0) (89.99911499023438 412.7690734863281 449.50860595703125 461.947265625 "The function is similar to the simplified-beginning-of-buffer func-
tion except that the interactive expression has \"P\" as an argument and
the goto-char function is followed by an if-then-else expression that figures
out where to put the cursor if there is an argument.
" 8 0) (89.9998779296875 467.24908447265625 449.541259765625 510.4097900390625 "The \"P\" in the interactive expression tells Emacs to pass a prefix
argument, if there is one, to the function. A prefix argument is made by
typing the ⟨
" 9 0) (146.86801147460938 494.6319885253906 172.18801879882812 495.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (146.8800048828125 495.8424377441406 172.16651916503906 503.8125305175781 "META
" 11 0) (146.86801147460938 503.1520080566406 172.18801879882812 503.63201904296875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (90.00054931640625 490.8890686035156 449.60711669921875 516.4360961914062 "⟩ key followed by a number, or by typing C-u and then a
number (if you don’t type a number, C-u defaults to 4).
" 13 0) (89.99868774414062 521.84912109375 449.5188293457031 630.787353515625 "The true-or-false-test of the if expression is simple: it is simply the
argument arg. If arg has a value that is not nil, which will be the case if
beginning-of-buffer is called with an argument, then this true-or-false-
test will return true and the then-part of the if expression will be evaluated.
On the other hand, if beginning-of-buffer is not called with an argument,
the value of arg will be nil and the else-part of the if expression will be
evaluated. The else-part is simply point-min, and when this is the outcome,
the whole goto-char expression is (goto-char (point-min)), which is how
we saw the beginning-of-buffer function in its simplified form.
" 14 0)) (89 (90.0 47.60907745361328 449.6610107421875 60.90726852416992 "What happens in a large buffer
71
" 0 0) (89.99935913085938 78.2418212890625 379.2123718261719 91.35738372802734 "5.3.2 beginning-of-buffer with an Argument
" 1 0) (89.99972534179688 100.16907501220703 449.3883972167969 149.34727478027344 "When beginning-of-buffer is called with an argument, an expression is
evaluated which calculates what value to pass to goto-char. This expression
is rather complicated at first sight. It includes an inner if expression and
much arithmetic. It looks like this:
" 2 0) (90.0003662109375 155.13754272460938 449.4223937988281 290.2270812988281 "(if (> (buffer-size) 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg) (/ (buffer-size) 10))
(/
(+ 10
(*
(buffer-size) (prefix-numeric-value arg))) 10))
Like other complex-looking expressions, the conditional expression within
beginning-of-buffer can be disentangled by looking at it as parts of a
template, in this case, the template for an if-then-else expression. In skeletal
form, the expression looks like this:
" 3 0) (90.00009155273438 296.01495361328125 449.466796875 443.8271179199219 "(if (buffer-is-large
divide-buffer-size-by-10-and-multiply-by-arg
else-use-alternate-calculation
The true-or-false-test of this inner if expression checks the size of the
buffer. The reason for this is that the old Version 18 Emacs used numbers
that are no bigger than eight million or so and in the computation that
followed, the programmer feared that Emacs might try to use over-large
numbers if the buffer were large.
The term ‘overflow’, mentioned in the
comment, means numbers that are over large. Version 21 Emacs uses larger
numbers, but this code has not been touched, if only because people now
look at buffers that are far, far larger than ever before.
There are two cases: if the buffer is large and if it is not.
" 4 0) (90.00003051757812 459.481689453125 291.9230041503906 472.585693359375 "What happens in a large buffer
" 5 0) (90.0006103515625 481.5289306640625 449.33489990234375 533.587158203125 "In beginning-of-buffer, the inner if expression tests whether the size
of the buffer is greater than 10,000 characters. To do this, it uses the >
function and the buffer-size function.
The line looks like this:
" 6 0) (89.99990844726562 539.3775024414062 449.3666687011719 575.587158203125 "(if (> (buffer-size) 10000)
When the buffer is large, the then-part of the if expression is evaluated. It
reads like this (after formatting for easy reading):
" 7 0) (89.9999771118164 581.3775024414062 442.1563720703125 630.7871704101562 "(*
(prefix-numeric-value arg)
(/ (buffer-size) 10))
This expression is a multiplication, with two arguments to the function *.
" 8 0)) (90 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "72
Chapter 5: A Few More Complex Functions
" 0 0) (89.9993896484375 77.48908233642578 449.4656066894531 138.5472869873047 "The first argument is (prefix-numeric-value arg). When \"P\" is used
as the argument for interactive, the value passed to the function as its
argument is passed a “raw prefix argument”, and not a number. (It is a
number in a list.) To perform the arithmetic, a conversion is necessary, and
prefix-numeric-value does the job.
" 1 0) (89.99932861328125 143.12908935546875 449.3666076660156 192.3072967529297 "The second argument is (/ (buffer-size) 10). This expression divides
the numeric value of the buffer by ten. This produces a number that tells
how many characters make up one tenth of the buffer size. (In Lisp, / is
used for division, just as * is used for multiplication.)
" 2 0) (89.99911499023438 196.88909912109375 449.3331298828125 222.0673065185547 "In the multiplication expression as a whole, this amount is multiplied by
the value of the prefix argument—the multiplication looks like this:
" 3 0) (111.59896850585938 230.9752197265625 320.8189697265625 252.4239959716797 "(* numeric-value-of-prefix-arg
number-of-characters-in-one-tenth-of-the-buffer)
" 4 0) (89.99862670898438 257.60906982421875 449.3546142578125 282.9072570800781 "If, for example, the prefix argument is ‘7’, the one-tenth value will be mul-
tiplied by 7 to give a position 70% of the way through the buffer.
" 5 0) (89.998291015625 287.48907470703125 449.2565612792969 312.6672668457031 "The result of all this is that if the buffer is large, the goto-char expression
reads like this:
" 6 0) (111.59825897216797 321.5777282714844 299.4787292480469 343.02410888671875 "(goto-char (* (prefix-numeric-value arg)
(/ (buffer-size) 10)))
" 7 0) (104.99807739257812 348.2091979980469 289.9832458496094 361.50738525390625 "This puts the cursor where we want it.
" 8 0) (89.99833679199219 386.4019470214844 294.0572814941406 399.5059509277344 "What happens in a small buffer
" 9 0) (89.99761962890625 411.4491882324219 449.4306335449219 472.50738525390625 "If the buffer contains fewer than 10,000 characters, a slightly different
computation is performed.
You might think this is not necessary, since
the first computation could do the job.
However, in a small buffer, the
first method may not put the cursor on exactly the desired line; the second
method does a better job.
" 10 0) (104.99754333496094 477.2091979980469 220.85206604003906 490.50738525390625 "The code looks like this:
" 11 0) (111.59766387939453 499.2977294921875 388.8701477050781 508.26409912109375 "(/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
" 12 0) (89.9962158203125 513.3292236328125 449.4185485839844 550.5074462890625 "This is code in which you figure out what happens by discovering how the
functions are embedded in parentheses. It is easier to read if you reformat
it with each expression indented more deeply than its enclosing expression:
" 13 0) (120.95587158203125 559.4177856445312 276.04156494140625 630.6641845703125 "(/
(+ 10
(*
(buffer-size)
(prefix-numeric-value arg)))
10))
" 14 0)) (91 (90.0 47.60907745361328 449.5965576171875 60.90726852416992 "The Complete beginning-of-buffer
73
" 0 0) (89.99990844726562 80.00910186767578 449.55206298828125 117.18729400634766 "Looking at parentheses, we see that the innermost operation is (prefix-
numeric-value arg), which converts the raw argument to a number. This
number is multiplied by the buffer size in the following expression:
" 1 0) (89.99945068359375 122.61764526367188 449.4430847167969 220.7473602294922 "(* (buffer-size) (prefix-numeric-value arg)
This multiplication creates a number that may be larger than the size of
the buffer—seven times larger if the argument is 7, for example.
Ten is
then added to this number and finally the large number is divided by ten to
provide a value that is one character larger than the percentage position in
the buffer.
The number that results from all this is passed to goto-char and the
cursor is moved to that point.
" 2 0) (90.000244140625 235.44189453125 351.8075256347656 248.5574493408203 "5.3.3 The Complete beginning-of-buffer
" 3 0) (105.00023651123047 257.129150390625 414.5348205566406 270.4273376464844 "Here is the complete text of the beginning-of-buffer function:
" 4 0) (111.59982299804688 275.8576965332031 323.009033203125 396.9041748046875 "(defun beginning-of-buffer (&optional arg)
\"Move point to the beginning of the buffer;
leave mark at previous position.
With arg N, put point N/10 of the way
from the true beginning.
Don’t use this in Lisp programs!
\\(goto-char (point-min)) is faster
and does not set the mark.\"
(interactive \"P\")
(push-mark)
" 5 0) (120.96048736572266 401.497802734375 323.555908203125 472.6241760253906 "(goto-char
(if arg
(if (> (buffer-size) 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg)
(/ (buffer-size) 10))
" 6 0) (90.00030517578125 477.2178039550781 449.400146484375 589.5075073242188 "(/ (+ 10 (* (buffer-size)
(prefix-numeric-value arg)))
10))
(point-min)))
(if arg (forward-line 1)))
Except for two small points, the previous discussion shows how this function
works. The first point deals with a detail in the documentation string, and
the second point concerns the last line of the function.
In the documentation string, there is reference to an expression:
" 7 0) (90.00033569335938 594.9378662109375 449.37799072265625 630.7875366210938 "\\(goto-char (point-min))
A ‘\\\\u2019 is used before the first parenthesis of this expression. This ‘\\\\u2019 tells
the Lisp interpreter that the expression should be printed as shown in the
" 8 0)) (92 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "74
Chapter 5: A Few More Complex Functions
" 0 0) (90.00021362304688 77.48908233642578 449.34564208984375 141.5472869873047 "documentation rather than evaluated as a symbolic expression, which is what
it looks like.
Finally, the last line of the beginning-of-buffer command says to move
point to the beginning of the next line if the command is invoked with an
argument:
" 1 0) (90.00003051757812 147.45761108398438 449.4874267578125 219.4272918701172 "(if arg (forward-line 1)))
This puts the cursor at the beginning of the first line after the appropriate
tenths position in the buffer. This is a flourish that means that the cursor is
always located at least the requested tenths of the way through the buffer,
which is a nicety that is, perhaps, not necessary, but which, if it did not
occur, would be sure to draw complaints.
" 2 0) (89.99974060058594 239.30035400390625 169.89073181152344 253.660888671875 "5.4 Review
" 3 0) (104.99974060058594 262.2890625 437.1813049316406 275.5872497558594 "Here is a brief summary of some of the topics covered in this chapter.
" 4 0) (90.00003051757812 281.96905517578125 449.48760986328125 343.0272521972656 "or
Evaluate each argument in sequence, and return the value of
the first argument that is not nil; if none return a value that
is not nil, return nil. In brief, return the first true value of
the arguments; return a true value if one or any of the other are
true.
" 5 0) (90.00080108642578 349.4090576171875 449.5203552246094 398.5872497558594 "and
Evaluate each argument in sequence, and if any are nil, return
nil; if none are nil, return the value of the last argument. In
brief, return a true value only if all the arguments are true;
return a true value if one and each of the others is true.
" 6 0) (90.00076293945312 406.81268310546875 449.488037109375 454.1472473144531 "&optional
A keyword used to indicate that an argument to a function defi-
nition is optional; this means that the function can be evaluated
without the argument, if desired.
" 7 0) (90.00105285644531 462.252685546875 449.7936706542969 497.7072448730469 "prefix-numeric-value
Convert the ‘raw prefix argument’ produced by (interactive
\"P\") to a numeric value.
" 8 0) (90.00175476074219 505.81268310546875 449.7944641113281 577.0272827148438 "forward-line
Move point forward to the beginning of the next line, or if the
argument is greater than one, forward that many lines.
If it
can’t move as far forward as it is supposed to, forward-line
goes forward as far as it can and then returns a count of the
number of additional lines it was supposed to move but couldn’t.
" 9 0) (90.00173950195312 585.252685546875 373.3979187011719 608.707275390625 "erase-buffer
Delete the entire contents of the current buffer.
" 10 0) (90.00173950195312 615.0890502929688 424.12506103515625 628.3872680664062 "bufferp
Return t if its argument is a buffer; otherwise return nil.
" 11 0)) (93 (90.0 47.60907745361328 449.6620178222656 60.90726852416992 "optional Argument Exercise
75
" 0 0) (90.0003662109375 77.30034637451172 318.1007385253906 91.67356872558594 "5.5 optional Argument Exercise
" 1 0) (90.000244140625 99.32910919189453 449.43304443359375 148.50730895996094 "Write an interactive function with an optional argument that tests
whether its argument, a number, is greater or less than the value of fill-
column, and tells you which, in a message. However, if you do not pass an
argument to the function, use 56 as a default value.
" 2 0)) (94 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "76
Chapter 5: A Few More Complex Functions
" 0 0)) (95 (90.0 47.60907745361328 449.5958557128906 60.90726852416992 "The save-restriction Special Form
77
" 0 0) (89.99920654296875 75.14844512939453 324.1742858886719 92.38106536865234 "6 Narrowing and Widening
" 1 0) (89.9981689453125 117.92908477783203 449.35504150390625 155.10728454589844 "Narrowing is a feature of Emacs that makes it possible for you to focus
on a specific part of a buffer, and work without accidentally changing other
parts. Narrowing is normally disabled since it can confuse novices.
" 2 0) (89.99758911132812 158.72906494140625 449.4089660644531 255.67608642578125 "With narrowing, the rest of a buffer is made invisible, as if it weren’t
there. This is an advantage if, for example, you want to replace a word in
one part of a buffer but not in another: you narrow to the part you want
and the replacement is carried out only in that section, not in the rest of
the buffer. Searches will only work within a narrowed region, not outside of
one, so if you are fixing a part of a document, you can keep yourself from
accidentally finding parts you do not need to fix by narrowing just to the
region you want. (The key binding for narrow-to-region is C-x n n.)
" 3 0) (89.99505615234375 259.2890625 449.5495300292969 344.3560791015625 "However, narrowing does make the rest of the buffer invisible, which can
scare people who inadvertently invoke narrowing and think they have deleted
a part of their file. Moreover, the undo command (which is usually bound
to C-x u) does not turn off narrowing (nor should it), so people can become
quite desperate if they do not know that they can return the rest of a buffer
to visibility with the widen command. (The key binding for widen is C-x n
w.)
" 4 0) (89.99188232421875 347.84906005859375 449.5561218261719 456.7872619628906 "Narrowing is just as useful to the Lisp interpreter as to a human. Often,
an Emacs Lisp function is designed to work on just part of a buffer; or
conversely, an Emacs Lisp function needs to work on all of a buffer that
has been narrowed.
The what-line function, for example, removes the
narrowing from a buffer, if it has any narrowing and when it has finished its
job, restores the narrowing to what it was. On the other hand, the count-
lines function, which is called by what-line, uses narrowing to restrict
itself to just that portion of the buffer in which it is interested and then
restores the previous situation.
" 5 0) (89.99147033691406 484.8203430175781 366.9673156738281 499.1935729980469 "6.1 The save-restriction Special Form
" 6 0) (89.99102783203125 509.84906005859375 449.4242248535156 630.7872924804688 "In Emacs Lisp, you can use the save-restriction special form to keep
track of whatever narrowing is in effect, if any. When the Lisp interpreter
meets with save-restriction, it executes the code in the body of the save-
restriction expression, and then undoes any changes to narrowing that the
code caused. If, for example, the buffer is narrowed and the code that follows
save-restriction gets rid of the narrowing, save-restriction returns the
buffer to its narrowed region afterwards. In the what-line command, any
narrowing the buffer may have is undone by the widen command that im-
mediately follows the save-restriction command. Any original narrowing
is restored just before the completion of the function.
" 7 0)) (96 (90.0 47.60907745361328 449.7270202636719 60.90726852416992 "78
Chapter 6: Narrowing and Widening
" 0 0) (104.999755859375 80.60907745361328 390.3377380371094 93.90726470947266 "The template for a save-restriction expression is simple:
" 1 0) (89.99880981445312 99.81759643554688 449.5189208984375 223.6272430419922 "(save-restriction
body... )
The body of the save-restriction is one or more expressions that will be
evaluated in sequence by the Lisp interpreter.
Finally, a point to note: when you use both save-excursion and save-
restriction, one right after the other, you should use save-excursion out-
ermost. If you write them in reverse order, you may fail to record narrowing
in the buffer to which Emacs switches after calling save-excursion. Thus,
when written together, save-excursion and save-restriction should be
written like this:
" 2 0) (89.99862670898438 229.53756713867188 449.7917785644531 318.0671691894531 "(save-excursion
(save-restriction
body...))
In other circumstances, when not written together, the save-excursion
and save-restriction special forms must be written in the order appro-
priate to the function.
For example,
" 3 0) (120.95866394042969 323.9776306152344 200.5467071533203 370.384033203125 "(save-restriction
(widen)
(save-excursion
body...))
" 4 0) (89.99861145019531 389.42041015625 185.49827575683594 403.79364013671875 "6.2 what-line
" 5 0) (89.99871826171875 412.5291442871094 449.74725341796875 449.70733642578125 "The what-line command tells you the number of the line in which the
cursor is located. The function illustrates the use of the save-restriction
and save-excursion commands. Here is the text of the function in full:
" 6 0) (89.99655151367188 455.7377014160156 449.4836730957031 630.7874145507812 "(defun what-line ()
\"Print the current line number (in the buffer) of point.\"
(interactive)
(save-restriction
(widen)
(save-excursion
(beginning-of-line)
(message \"Line %d\"
(1+ (count-lines 1 (point)))))))
The function has a documentation line and is interactive, as you would
expect. The next two lines use the functions save-restriction and widen.
The save-restriction special form notes whatever narrowing is in ef-
fect, if any, in the current buffer and restores that narrowing after the code
in the body of the save-restriction has been evaluated.
" 7 0)) (97 (90.0 47.60907745361328 449.6940612792969 60.90726852416992 "Exercise with Narrowing
79
" 0 0) (89.99636840820312 77.48908233642578 449.9323425292969 288.1872253417969 "The save-restriction special form is followed by widen. This function
undoes any narrowing the current buffer may have had when what-line
was called.
(The narrowing that was there is the narrowing that save-
restriction remembers.)
This widening makes it possible for the line
counting commands to count from the beginning of the buffer. Otherwise,
they would have been limited to counting within the accessible region. Any
original narrowing is restored just before the completion of the function by
the save-restriction special form.
The call to widen is followed by save-excursion, which saves the loca-
tion of the cursor (i.e., of point) and of the mark, and restores them after
the code in the body of the save-excursion uses the beginning-of-line
function to move point.
(Note that the (widen) expression comes between the save-restriction
and save-excursion special forms.
When you write the two save- ...
expressions in sequence, write save-excursion outermost.)
The last two lines of the what-line function are functions to count the
number of lines in the buffer and then print the number in the echo area.
" 1 0) (89.99569702148438 293.1376037597656 449.43963623046875 403.02734375 "(message \"Line %d\"
(1+ (count-lines 1 (point)))))))
The message function prints a one-line message at the bottom of the
Emacs screen. The first argument is inside of quotation marks and is printed
as a string of characters. However, it may contain ‘%d’, ‘%s’, or ‘%c’ to print
arguments that follow the string. ‘%d’ prints the argument as a decimal, so
the message will say something such as ‘Line 243’.
The number that is printed in place of the ‘%d’ is computed by the last
line of the function:
" 2 0) (89.99578857421875 408.0976867675781 449.48358154296875 517.1473999023438 "(1+ (count-lines 1 (point)))
What this does is count the lines from the first position of the buffer, indi-
cated by the 1, up to (point), and then add one to that number. (The 1+
function adds one to its argument.) We add one to it because line 2 has only
one line before it, and count-lines counts only the lines before the current
line.
After count-lines has done its job, and the message has been printed in
the echo area, the save-excursion restores point and mark to their original
positions; and save-restriction restores the original narrowing, if any.
" 3 0) (89.99539184570312 533.5404663085938 293.41778564453125 547.9010009765625 "6.3 Exercise with Narrowing
" 4 0) (89.99453735351562 555.689208984375 449.53631591796875 616.7474365234375 "Write a function that will display the first 60 characters of the current
buffer, even if you have narrowed the buffer to its latter half so that the first
line is inaccessible. Restore point, mark, and narrowing. For this exercise,
you need to use save-restriction, widen, goto-char, point-min, buffer-
substring, message, and other functions, a whole potpourri.
" 5 0)) (98 (90.0 47.60907745361328 449.7270202636719 60.90726852416992 "80
Chapter 6: Narrowing and Widening
" 0 0)) (99 (90.0 47.60907745361328 449.8250427246094 60.90726852416992 "car and cdr
81
" 0 0) (89.9993896484375 75.14844512939453 434.5227966308594 92.39627838134766 "7 car, cdr, cons: Fundamental Functions
" 1 0) (89.99911499023438 124.28907012939453 449.2903747558594 161.46726989746094 "In Lisp, car, cdr, and cons are fundamental functions. The cons function
is used to construct lists, and the car and cdr functions are used to take
them apart.
" 2 0) (89.9986572265625 166.2890625 449.32257080078125 203.46726989746094 "In the walk through of the copy-region-as-kill function, we will see
cons as well as two variants on cdr, namely, setcdr and nthcdr.
(See
Section 8.5, “copy-region-as-kill”, page 102.)
" 3 0) (89.9974365234375 208.2890625 449.4090881347656 353.1072692871094 "The name of the cons function is not unreasonable: it is an abbreviation
of the word ‘construct’. The origins of the names for car and cdr, on the
other hand, are esoteric: car is an acronym from the phrase ‘Contents of
the Address part of the Register’; and cdr (pronounced ‘could-er’) is an
acronym from the phrase ‘Contents of the Decrement part of the Register’.
These phrases refer to specific pieces of hardware on the very early computer
on which the original Lisp was developed. Besides being obsolete, the phrases
have been completely irrelevant for more than 25 years to anyone thinking
about Lisp. Nonetheless, although a few brave scholars have begun to use
more reasonable names for these functions, the old terms are still in use. In
particular, since the terms are used in the Emacs Lisp source code, we will
use them in this introduction.
" 4 0) (89.99783325195312 386.18035888671875 199.543701171875 400.5535888671875 "7.1 car and cdr
" 5 0) (89.99740600585938 412.5291748046875 449.451904296875 437.7073669433594 "The car of a list is, quite simply, the first item in the list. Thus the car
of the list (rose violet daisy buttercup) is rose.
" 6 0) (89.99795532226562 442.649169921875 449.2989807128906 467.9473571777344 "If you are reading this in Info in GNU Emacs, you can see this by evalu-
ating the following:
" 7 0) (111.59794616699219 477.09771728515625 280.5611877441406 486.0640869140625 "(car ’(rose violet daisy buttercup))
" 8 0) (89.998046875 491.3691711425781 406.93951416015625 504.6673583984375 "After evaluating the expression, rose will appear in the echo area.
" 9 0) (89.9986572265625 509.4891357421875 449.4852600097656 534.787353515625 "Clearly, a more reasonable name for the car function would be first
and this is often suggested.
" 10 0) (89.9981689453125 539.609130859375 449.37591552734375 576.787353515625 "car does not remove the first item from the list; it only reports what it
is. After car has been applied to a list, the list is still the same as it was. In
the jargon, car is ‘non-destructive’. This feature turns out to be important.
" 11 0) (89.99746704101562 581.609130859375 449.451904296875 630.787353515625 "The cdr of a list is the rest of the list, that is, the cdr function returns
the part of the list that follows the first item. Thus, while the car of the
list ’(rose violet daisy buttercup) is rose, the rest of the list, the value
returned by the cdr function, is (violet daisy buttercup).
" 12 0)) (100 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "82
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (105.00006103515625 80.72907257080078 399.5671081542969 94.02725982666016 "You can see this by evaluating the following in the usual way:
" 1 0) (89.99603271484375 100.17758178710938 449.50537109375 379.5072326660156 "(cdr ’(rose violet daisy buttercup))
When you evaluate this, (violet daisy buttercup) will appear in the echo
area.
Like car, cdr does not remove any elements from the list—it just returns
a report of what the second and subsequent elements are.
Incidentally, in the example, the list of flowers is quoted. If it were not, the
Lisp interpreter would try to evaluate the list by calling rose as a function.
In this example, we do not want to do that.
Clearly, a more reasonable name for cdr would be rest.
(There is a lesson here: when you name new functions, consider very
carefully what you are doing, since you may be stuck with the names for far
longer than you expect. The reason this document perpetuates these names
is that the Emacs Lisp source code uses them, and if I did not use them,
you would have a hard time reading the code; but do, please, try to avoid
using these terms yourself. The people who come after you will be grateful
to you.)
When car and cdr are applied to a list made up of symbols, such as the
list (pine fir oak maple), the element of the list returned by the function
car is the symbol pine without any parentheses around it. pine is the first
element in the list. However, the cdr of the list is a list itself, (fir oak
maple), as you can see by evaluating the following expressions in the usual
way:
" 2 0) (111.59603118896484 385.6575927734375 238.39585876464844 394.62396240234375 "(car ’(pine fir oak maple))
" 3 0) (89.99554443359375 410.6175842285156 449.4280090332031 471.1872253417969 "(cdr ’(pine fir oak maple))
On the other hand, in a list of lists, the first element is itself a list. car
returns this first element as a list. For example, the following list contains
three sub-lists, a list of carnivores, a list of herbivores and a list of sea
mammals:
" 4 0) (89.995849609375 477.33758544921875 449.592041015625 550.9873046875 "(car ’((lion tiger cheetah)
(gazelle antelope zebra)
(whale dolphin seal)))
In this example, the first element or car of the list is the list of carnivores,
(lion tiger cheetah), and the rest of the list is ((gazelle antelope
zebra) (whale dolphin seal)).
" 5 0) (89.99578857421875 557.1376342773438 449.3960266113281 630.7872924804688 "(cdr ’((lion tiger cheetah)
(gazelle antelope zebra)
(whale dolphin seal)))
It is worth saying again that car and cdr are non-destructive—that is,
they do not modify or change lists to which they are applied. This is very
important for how they are used.
" 6 0)) (101 (90.0 47.60907745361328 449.8796691894531 60.90726852416992 "cons
83
" 0 0) (89.99908447265625 77.48908233642578 449.39910888671875 198.3072967529297 "Also, in the first chapter, in the discussion about atoms, I said that in
Lisp, “certain kinds of atom, such as an array, can be separated into parts;
but the mechanism for doing this is different from the mechanism for splitting
a list. As far as Lisp is concerned, the atoms of a list are unsplittable.”
(See Section 1.1.1, “Lisp Atoms”, page 1.) The car and cdr functions are
used for splitting lists and are considered fundamental to Lisp. Since they
cannot split or gain access to the parts of an array, an array is considered an
atom. Conversely, the other fundamental function, cons, can put together
or construct a list, but not an array. (Arrays are handled by array-specific
functions. See section “Arrays” in The GNU Emacs Lisp Reference Manual.)
" 1 0) (89.99948120117188 215.660400390625 148.34246826171875 230.0336151123047 "7.2 cons
" 2 0) (89.99945068359375 238.04913330078125 449.1919250488281 275.2273254394531 "The cons function constructs lists; it is the inverse of car and cdr. For
example, cons can be used to make a four element list from the three element
list, (fir oak maple):
" 3 0) (89.99906921386719 280.4175720214844 268.2425537109375 304.1472473144531 "(cons ’pine ’(fir oak maple))
After evaluating this list, you will see
" 4 0) (89.997802734375 309.4576110839844 449.58367919921875 426.0127258300781 "(pine fir oak maple)
appear in the echo area. cons puts a new element at the beginning of a list;
it attaches or pushes elements onto the list.
cons must have a list to attach to.1 You cannot start from absolutely
nothing. If you are building a list, you need to provide at least an empty
list at the beginning. Here is a series of cons expressions that build up a list
of flowers. If you are reading this in Info in GNU Emacs, you can evaluate
each of the expressions in the usual way; the value is printed in this text
after ‘⇒’, which you may read as ‘evaluates to’.
" 5 0) (111.59840393066406 424.1776428222656 205.56089782714844 451.36981201171875 "(cons ’buttercup ())
⇒ (buttercup)
" 6 0) (111.59838104248047 453.6976623535156 233.4697723388672 480.88983154296875 "(cons ’daisy ’(buttercup))
⇒ (daisy buttercup)
" 7 0) (111.59847259521484 483.3376770019531 266.4187927246094 510.52984619140625 "(cons ’violet ’(daisy buttercup))
⇒ (violet daisy buttercup)
" 8 0) (89.99783325195312 512.8577270507812 449.4844665527344 585.0673828125 "(cons ’rose ’(violet daisy buttercup))
⇒ (rose violet daisy buttercup)
In the first example, the empty list is shown as () and a list made up
of buttercup followed by the empty list is constructed. As you can see,
the empty list is not shown in the list that was constructed. All that you
see is (buttercup). The empty list is not counted as an element of a list
" 9 0) (89.98799896240234 594.5919799804688 233.98800659179688 595.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (95.87999725341797 595.5352172851562 449.7353515625 630.3015747070312 "1 Actually, you can cons an element to an atom to produce a dotted pair. Dotted pairs
are not discussed here; see section “Dotted Pair Notation” in The GNU Emacs Lisp
Reference Manual.
" 11 0)) (102 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "84
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (89.99978637695312 77.48908233642578 449.4430236816406 153.9072723388672 "because there is nothing in an empty list. Generally speaking, an empty list
is invisible.
The second example, (cons ’daisy ’(buttercup)) constructs a new,
two element list by putting daisy in front of buttercup; and the third
example constructs a three element list by putting violet in front of daisy
and buttercup.
" 1 0) (90.00016021728516 171.601806640625 342.6677551269531 184.7173614501953 "7.2.1 Find the Length of a List: length
" 2 0) (90.00006103515625 194.24908447265625 449.4648132324219 219.4272918701172 "You can find out how many elements there are in a list by using the Lisp
function length, as in the following examples:
" 3 0) (111.59971618652344 225.93765258789062 209.98521423339844 253.0098419189453 "(length ’(buttercup))
⇒ 1
" 4 0) (111.59981536865234 255.45761108398438 238.2627410888672 282.6497802734375 "(length ’(daisy buttercup))
⇒ 2
" 5 0) (90.00047302246094 284.9775695800781 449.4336242675781 361.9871826171875 "(length (cons ’violet ’(daisy buttercup)))
⇒ 3
In the third example, the cons function is used to construct a three element
list which is then passed to the length function as its argument.
We can also use length to count the number of elements in an empty
list:
" 6 0) (90.00161743164062 368.3775329589844 449.4566650390625 445.1471862792969 "(length ())
⇒ 0
As you would expect, the number of elements in an empty list is zero.
An interesting experiment is to find out what happens if you try to find
the length of no list at all; that is, if you try to call length without giving
it an argument, not even an empty list:
" 7 0) (90.0020751953125 451.65753173828125 353.7944641113281 476.5871887207031 "(length )
What you see, if you evaluate this, is the error message
" 8 0) (90.00070190429688 482.9775390625 449.422607421875 630.7872314453125 "Wrong number of arguments: #<subr length>, 0
This means that the function receives the wrong number of arguments, zero,
when it expects some other number of arguments. In this case, one argument
is expected, the argument being a list whose length the function is measuring.
(Note that one list is one argument, even if the list has many elements inside
it.)
The part of the error message that says ‘#<subr length>’ is the name of
the function. This is written with a special notation, ‘#<subr’, that indicates
that the function length is one of the primitive functions written in C rather
than in Emacs Lisp. (‘subr’ is an abbreviation for ‘subroutine’.) See section
“What Is a Function?” in The GNU Emacs Lisp Reference Manual, for more
about subroutines.
" 9 0)) (103 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "nthcdr
85
" 0 0) (90.0 77.30034637451172 163.20565795898438 91.67356872558594 "7.3 nthcdr
" 1 0) (89.99871826171875 99.80908966064453 450.03179931640625 237.42735290527344 "The nthcdr function is associated with the cdr function. What it does
is take the cdr of a list repeatedly.
If you take the cdr of the list (pine fir oak maple), you will be returned
the list (fir oak maple).
If you repeat this on what was returned, you
will be returned the list (oak maple). (Of course, repeated cdring on the
original list will just give you the original cdr since the function does not
change the list. You need to evaluate the cdr of the cdr and so on.) If you
continue this, eventually you will be returned an empty list, which in this
case, instead of being shown as () is shown as nil.
For review, here is a series of repeated cdrs, the text following the ‘⇒’
shows what is returned.
" 2 0) (111.59909057617188 242.85769653320312 238.39891052246094 269.92987060546875 "(cdr ’(pine fir oak maple))
⇒(fir oak maple)
" 3 0) (111.59908294677734 272.3777770996094 214.7930145263672 299.5699462890625 "(cdr ’(fir oak maple))
⇒ (oak maple)
" 4 0) (111.59908294677734 301.8977355957031 196.09861755371094 329.08990478515625 "(cdr ’(oak maple))
⇒(maple)
" 5 0) (111.59907531738281 331.5377197265625 177.16415405273438 358.7298889160156 "(cdr ’(maple))
⇒ nil
" 6 0) (111.5990982055664 361.0577392578125 163.3294219970703 388.2499084472656 "(cdr ’nil)
⇒ nil
" 7 0) (89.99932861328125 390.69775390625 449.2679443359375 440.107421875 "(cdr ())
⇒ nil
You can also do several cdrs without printing the values in between, like
this:
" 8 0) (89.9970703125 445.41778564453125 449.45233154296875 603.907470703125 "(cdr (cdr ’(pine fir oak maple)))
⇒ (oak maple)
In this example, the Lisp interpreter evaluates the innermost list first. The
innermost list is quoted, so it just passes the list as it is to the innermost cdr.
This cdr passes a list made up of the second and subsequent elements of the
list to the outermost cdr, which produces a list composed of the third and
subsequent elements of the original list. In this example, the cdr function is
repeated and returns a list that consists of the original list without its first
two elements.
The nthcdr function does the same as repeating the call to cdr. In the
following example, the argument 2 is passed to the function nthcdr, along
with the list, and the value returned is the list without its first two items,
which is exactly the same as repeating cdr twice on the list:
" 9 0) (111.59686279296875 609.2178344726562 261.8825988769531 636.4099731445312 "(nthcdr 2 ’(pine fir oak maple))
⇒ (oak maple)
" 10 0)) (104 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "86
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (89.99990844726562 84.92908477783203 449.3125915527344 110.2272720336914 "Using the original four element list, we can see what happens when various
numeric arguments are passed to nthcdr, including 0, 1, and 5:
" 1 0) (111.60033416748047 120.45520782470703 261.8860778808594 160.12977600097656 ";; Leave the list as it was.
(nthcdr 0 ’(pine fir oak maple))
⇒ (pine fir oak maple)
" 2 0) (111.60026550292969 162.57513427734375 288.8662109375 202.1297149658203 ";; Return a copy without the first element.
(nthcdr 1 ’(pine fir oak maple))
⇒ (fir oak maple)
" 3 0) (111.60029602050781 204.5750732421875 322.9229736328125 244.24964904785156 ";; Return a copy of the list without three elements.
(nthcdr 3 ’(pine fir oak maple))
⇒ (maple)
" 4 0) (111.60054779052734 246.57501220703125 286.4632263183594 286.24957275390625 ";; Return a copy lacking all four elements.
(nthcdr 4 ’(pine fir oak maple))
⇒ nil
" 5 0) (111.60079193115234 288.574951171875 267.28466796875 328.24951171875 ";; Return a copy lacking all elements.
(nthcdr 5 ’(pine fir oak maple))
⇒ nil
" 6 0) (90.00125122070312 359.06005859375 140.91290283203125 373.43328857421875 "7.4 nth
" 7 0) (90.00137329101562 386.48876953125 449.30267333984375 423.7869567871094 "The nthcdr function takes the cdr of a list repeatedly. The nth function
takes the car of the result returned by nthcdr. It returns the Nth element
of the list.
" 8 0) (90.00167846679688 429.80877685546875 449.346435546875 455.1069641113281 "Thus, if it were not defined in C for speed, the definition of nth would
be:
" 9 0) (111.60151672363281 465.4573059082031 412.1624755859375 511.7436828613281 "(defun nth (n list)
\"Returns the Nth element of LIST.
N counts from zero.
If LIST is not that long, nil is returned.\"
(car (nthcdr n list)))
" 10 0) (90.00147247314453 519.0887451171875 449.281005859375 544.386962890625 "(Originally, nth was defined in Emacs Lisp in ‘subr.el’, but its definition
was redone in C in the 1980s.)
" 11 0) (90.00204467773438 550.4088134765625 449.4012145996094 575.5870361328125 "The nth function returns a single element of a list. This can be very
convenient.
" 12 0) (90.00192260742188 581.6087646484375 449.3797302246094 630.7869873046875 "Note that the elements are numbered from zero, not one.
That is to
say, the first element of a list, its car is the zeroth element. This is called
‘zero-based’ counting and often bothers people who are accustomed to the
first element in a list being number one, which is ‘one-based’.
" 13 0)) (105 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "setcdr
87
" 0 0) (105.0 80.84906768798828 166.4837188720703 94.14725494384766 "For example:
" 1 0) (111.60000610351562 100.29757690429688 252.4142303466797 127.48975372314453 "(nth 0 ’(\"one\" \"two\" \"three\"))
⇒ \"one\"
" 2 0) (90.00054931640625 137.61758422851562 449.31256103515625 198.90721130371094 "(nth 1 ’(\"one\" \"two\" \"three\"))
⇒ \"two\"
It is worth mentioning that nth, like nthcdr and cdr, does not change
the original list—the function is non-destructive. This is in sharp contrast
to the setcar and setcdr functions.
" 3 0) (90.0003662109375 220.22027587890625 163.20602416992188 234.59349060058594 "7.5 setcar
" 4 0) (90.00042724609375 243.5689697265625 449.44384765625 331.8671569824219 "As you might guess from their names, the setcar and setcdr functions
set the car or the cdr of a list to a new value. They actually change the
original list, unlike car and cdr which leave the original list as it was. One
way to find out how this works is to experiment. We will start with the
setcar function.
First, we can make a list and then set the value of a variable to the list,
using the setq function. Here is a list of animals:
" 5 0) (89.99884033203125 338.13751220703125 449.4419250488281 437.8271484375 "(setq animals ’(antelope giraffe lion tiger))
If you are reading this in Info inside of GNU Emacs, you can evaluate this
expression in the usual fashion, by positioning the cursor after the expression
and typing C-x C-e.
(I’m doing this right here as I write this.
This is
one of the advantages of having the interpreter built into the computing
environment.)
When we evaluate the variable animals, we see that it is bound to the
list (antelope giraffe lion tiger):
" 6 0) (89.997314453125 443.9775085449219 449.5286865234375 544.2672119140625 "animals
⇒ (antelope giraffe lion tiger)
Put another way, the variable animals points to the list (antelope giraffe
lion tiger).
Next, evaluate the function setcar while passing it two arguments, the
variable animals and the quoted symbol hippopotamus; this is done by
writing the three element list (setcar animals ’hippopotamus) and then
evaluating it in the usual fashion:
" 7 0) (89.9971923828125 550.5375366210938 449.12408447265625 587.2271728515625 "(setcar animals ’hippopotamus)
After evaluating this expression, evaluate the variable animals again. You
will see that the list of animals has changed:
" 8 0) (89.99752807617188 593.4974975585938 420.6189880371094 630.7871704101562 "animals
⇒ (hippopotamus giraffe lion tiger)
The first element on the list, antelope is replaced by hippopotamus.
" 9 0)) (106 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "88
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (90.00006103515625 77.48908233642578 449.4975891113281 102.66727447509766 "So we can see that setcar did not add a new element to the list as cons
would have; it replaced giraffe with hippopotamus; it changed the list.
" 1 0) (90.0001220703125 119.18035125732422 163.20578002929688 133.55357360839844 "7.6 setcdr
" 2 0) (89.999755859375 141.2091064453125 449.41064453125 204.4272918701172 "The setcdr function is similar to the setcar function, except that the
function replaces the second and subsequent elements of a list rather than
the first element.
To see how this works, set the value of the variable to a list of domesti-
cated animals by evaluating the following expression:
" 3 0) (89.99969482421875 209.49765014648438 449.4212951660156 244.86729431152344 "(setq domesticated-animals ’(horse cow sheep goat))
If you now evaluate the list, you will be returned the list (horse cow sheep
goat):
" 4 0) (89.9986572265625 249.93765258789062 449.322509765625 310.8672790527344 "domesticated-animals
⇒ (horse cow sheep goat)
Next, evaluate setcdr with two arguments, the name of the variable
which has a list as its value, and the list to which the cdr of the first list
will be set;
" 5 0) (89.9986572265625 315.9376525878906 449.27886962890625 375.18731689453125 "(setcdr domesticated-animals ’(cat dog))
If you evaluate this expression, the list (cat dog) will appear in the echo
area. This is the value returned by the function. The result we are inter-
ested in is the “side effect”, which we can see by evaluating the variable
domesticated-animals:
" 6 0) (89.99832153320312 380.1376647949219 449.5284118652344 428.2274169921875 "domesticated-animals
⇒ (horse cat dog)
Indeed, the list is changed from (horse cow sheep goat) to (horse cat
dog). The cdr of the list is changed from (cow sheep goat) to (cat dog).
" 7 0) (89.99771118164062 444.6205139160156 176.97572326660156 458.9810485839844 "7.7 Exercise
" 8 0) (89.99710083007812 466.76922607421875 449.5281982421875 515.8274536132812 "Construct a list of four birds by evaluating several expressions with cons.
Find out what happens when you cons a list onto itself. Replace the first
element of the list of four birds with a fish. Replace the rest of that list with
a list of other fish.
" 9 0)) (107 (90.0 47.60907745361328 449.80364990234375 60.90726852416992 "zap-to-char
89
" 0 0) (90.0 75.14844512939453 325.3755187988281 92.38106536865234 "8 Cutting and Storing Text
" 1 0) (89.99948120117188 112.28907012939453 449.3558349609375 264.6672058105469 "Whenever you cut or clip text out of a buffer with a ‘kill’ command in
GNU Emacs, it is stored in a list and you can bring it back with a ‘yank’
command.
(The use of the word ‘kill’ in Emacs for processes which specifically do
not destroy the values of the entities is an unfortunate historical accident.
A much more appropriate word would be ‘clip’ since that is what the kill
commands do; they clip text out of a buffer and put it into storage from
which it can be brought back. I have often been tempted to replace globally
all occurrences of ‘kill’ in the Emacs sources with ‘clip’ and all occurrences
of ‘killed’ with ‘clipped’.)
When text is cut out of a buffer, it is stored on a list. Successive pieces
of text are stored on the list successively, so the list might look like this:
" 2 0) (90.00041198730469 271.4175720214844 440.9891357421875 296.7072448730469 "(\"a piece of text\" \"previous piece\")
The function cons can be used to add a piece of text to the list, like this:
" 3 0) (111.60003662109375 303.4576110839844 318.2345886230469 324.9039611816406 "(cons \"another piece\"
’(\"a piece of text\" \"previous piece\"))
" 4 0) (89.999755859375 329.0090637207031 449.3665771484375 354.3072509765625 "If you evaluate this expression, a list of three elements will appear in the
echo area:
" 5 0) (89.99966430664062 361.0576171875 449.464599609375 422.1072692871094 "(\"another piece\" \"a piece of text\" \"previous piece\")
With the car and nthcdr functions, you can retrieve whichever piece of
text you want. For example, in the following code, nthcdr 1 ... returns
the list with the first item removed; and the car returns the first element of
that remainder—the second element of the original list:
" 6 0) (89.99789428710938 428.9776306152344 449.49700927734375 630.787353515625 "(car (nthcdr 1 ’(\"another piece\"
\"a piece of text\"
\"previous piece\")))
⇒ \"a piece of text\"
The actual functions in Emacs are more complex than this, of course.
The code for cutting and retrieving text has to be written so that Emacs
can figure out which element in the list you want—the first, second, third,
or whatever. In addition, when you get to the end of the list, Emacs should
give you the first element of the list, rather than nothing at all.
The list that holds the pieces of text is called the kill ring. This chapter
leads up to a description of the kill ring and how it is used by first tracing how
the zap-to-char function works. This function uses (or ‘calls’) a function
that invokes a function that manipulates the kill ring. Thus, before reaching
the mountains, we climb the foothills.
A subsequent chapter describes how text that is cut from the buffer is
retrieved. See Chapter 10, “Yanking Text Back”, page 117.
" 7 0)) (108 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "90
Chapter 8: Cutting and Storing Text
" 0 0) (90.00033569335938 77.30034637451172 200.3626708984375 91.67356872558594 "8.1 zap-to-char
" 1 0) (90.0001220703125 99.68909454345703 449.5314025878906 427.62738037109375 "The zap-to-char function barely changed between GNU Emacs version
19 and GNU Emacs version 21. However, zap-to-char calls another func-
tion, kill-region, which enjoyed a major rewrite on the way to version
21.
The kill-region function in Emacs 19 is complex, but does not use code
that is important at this time. We will skip it.
The kill-region function in Emacs 21 is easier to read than the same
function in Emacs 19 and introduces a very important concept, that of error
handling. We will walk through the function.
But first, let us look at the interactive zap-to-char function.
The GNU Emacs version 19 and version 21 implementations of the zap-
to-char function are nearly identical in form, and they work alike. The
function removes the text in the region between the location of the cursor
(i.e., of point) up to and including the next occurrence of a specified charac-
ter. The text that zap-to-char removes is put in the kill ring; and it can be
retrieved from the kill ring by typing C-y (yank). If the command is given
an argument, it removes text through that number of occurrences. Thus, if
the cursor were at the beginning of this sentence and the character were ‘s’,
‘Thus’ would be removed. If the argument were two, ‘Thus, if the curs’
would be removed, up to and including the ‘s’ in ‘cursor’.
If the specified character is not found, zap-to-char will say “Search
failed”, tell you the character you typed, and not remove any text.
In order to determine how much text to remove, zap-to-char uses a
search function. Searches are used extensively in code that manipulates text,
and we will focus attention on them as well as on the deletion command.
Here is the complete text of the version 19 implementation of the function:
" 2 0) (111.60002136230469 432.937744140625 388.7780456542969 541.504150390625 "(defun zap-to-char (arg char)
; version 19 implementation
\"Kill up to and including ARG’th occurrence of CHAR.
Goes backward if ARG is negative; error if CHAR not found.\"
(interactive \"*p\\ncZap to char: \")
(kill-region (point)
(progn
(search-forward
(char-to-string char) nil nil arg)
(point))))
" 3 0) (90.00065612792969 555.1220092773438 305.991943359375 568.237548828125 "8.1.1 The interactive Expression
" 4 0) (105.00074768066406 576.5692138671875 449.378662109375 589.867431640625 "The interactive expression in the zap-to-char command looks like this:
" 5 0) (90.0003662109375 595.1777954101562 449.4113464355469 630.7874755859375 "(interactive \"*p\\ncZap to char: \")
The part within quotation marks, \"*p\\ncZap to char: \", specifies three
different things. First, and most simply, the asterisk, ‘*’, causes an error to
" 6 0)) (109 (90.0 47.60907745361328 449.6512756347656 60.90726852416992 "The search-forward Function
91
" 0 0) (89.996826171875 77.48908233642578 449.75799560546875 491.1073303222656 "be signalled if the buffer is read-only. This means that if you try zap-to-
char in a read-only buffer you will not be able to remove text, and you will
receive a message that says “Buffer is read-only”; your terminal may beep
at you as well.
The version 21 implementation does not have the asterisk, ‘*’. The func-
tion works the same as in version 19: in both cases, it cannot remove text
from a read-only buffer but the function does copy the text that would have
been removed to the kill ring. Also, in both cases, you see an error message.
However, the version 19 implementation copies text from a read-only
buffer only because of a mistake in the implementation of interactive.
According to the documentation for interactive, the asterisk, ‘*’, should
prevent the zap-to-char function from doing anything at all when the buffer
is read only. The function should not copy the text to the kill ring. It is a
bug that it does.
In version 21, interactive is implemented correctly. So the asterisk, ‘*’,
had to be removed from the interactive specification. If you insert an ‘*’ and
evaluate the function definition, then the next time you run the zap-to-char
function on a read-only buffer, you will not copy any text.
That change aside, and a change to the documentation, the two versions
of the zap-to-char function are identical.
Let us continue with the interactive specification.
The second part of \"*p\\ncZap to char: \" is the ‘p’. This part is sepa-
rated from the next part by a newline, ‘\\n’. The ‘p’ means that the first
argument to the function will be passed the value of a ‘processed prefix’.
The prefix argument is passed by typing C-u and a number, or M- and a
number. If the function is called interactively without a prefix, 1 is passed
to this argument.
The third part of \"*p\\ncZap to char: \" is ‘cZap to char: ’. In this part,
the lower case ‘c’ indicates that interactive expects a prompt and that the
argument will be a character. The prompt follows the ‘c’ and is the string
‘Zap to char: ’ (with a space after the colon to make it look good).
What all this does is prepare the arguments to zap-to-char so they are
of the right type, and give the user a prompt.
" 1 0) (89.99653625488281 505.201904296875 287.4314270019531 518.3174438476562 "8.1.2 The Body of zap-to-char
" 2 0) (89.99456787109375 526.649169921875 449.4059143066406 575.827392578125 "The body of the zap-to-char function contains the code that kills (that
is, removes) the text in the region from the current position of the cursor
up to and including the specified character. The first part of the code looks
like this:
" 3 0) (89.9947509765625 581.0177612304688 449.42657470703125 630.7874145507812 "(kill-region (point) ...
(point) is the current position of the cursor.
The next part of the code is an expression using progn. The body of the
progn consists of calls to search-forward and point.
" 4 0)) (110 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "92
Chapter 8: Cutting and Storing Text
" 0 0) (89.9998779296875 77.48908233642578 449.56365966796875 102.66727447509766 "It is easier to understand how progn works after learning about search-
forward, so we will look at search-forward and then at progn.
" 1 0) (90.00009155273438 129.121826171875 313.0802001953125 142.2373809814453 "8.1.3 The search-forward Function
" 2 0) (89.9996337890625 154.64910888671875 449.69476318359375 239.7073211669922 "The search-forward function is used to locate the zapped-for-character
in zap-to-char. If the search is successful, search-forward leaves point
immediately after the last character in the target string. (In zap-to-char,
the target string is just one character long.)
If the search is backwards,
search-forward leaves point just before the first character in the target.
Also, search-forward returns t for true. (Moving point is therefore a ‘side
effect’.)
" 3 0) (104.9996337890625 244.76910400390625 401.5850524902344 258.0672912597656 "In zap-to-char, the search-forward function looks like this:
" 4 0) (111.5999755859375 267.4576721191406 346.4523620605469 276.4240417480469 "(search-forward (char-to-string char) nil nil arg)
" 5 0) (104.99958801269531 281.84912109375 356.56317138671875 295.1473083496094 "The search-forward function takes four arguments:
" 6 0) (95.87928771972656 301.16912841796875 449.43157958984375 326.4673156738281 "1. The first argument is the target, what is searched for. This must be a
string, such as ‘\"z\"’.
" 7 0) (111.5980224609375 332.4891357421875 449.845458984375 465.3073425292969 "As it happens, the argument passed to zap-to-char is a single charac-
ter. Because of the way computers are built, the Lisp interpreter may
treat a single character as being different from a string of characters.
Inside the computer, a single character has a different electronic format
than a string of one character. (A single character can often be recorded
in the computer using exactly one byte; but a string may be longer, and
the computer needs to be ready for this.) Since the search-forward
function searches for a string, the character that the zap-to-char func-
tion receives as its argument must be converted inside the computer
from one format to the other; otherwise the search-forward function
will fail. The char-to-string function is used to make this conversion.
" 8 0) (95.87811279296875 471.32916259765625 449.462890625 508.5073547363281 "2. The second argument bounds the search; it is specified as a position in
the buffer. In this case, the search can go to the end of the buffer, so
no bound is set and the second argument is nil.
" 9 0) (95.87823486328125 514.5291748046875 449.5177001953125 563.7073974609375 "3. The third argument tells the function what it should do if the search
fails—it can signal an error (and print a message) or it can return nil.
A nil as the third argument causes the function to signal an error when
the search fails.
" 10 0) (95.87736511230469 569.6091918945312 449.3532409667969 630.7874145507812 "4. The fourth argument to search-forward is the repeat count—how
many occurrences of the string to look for. This argument is optional
and if the function is called without a repeat count, this argument is
passed the value 1. If this argument is negative, the search goes back-
wards.
" 11 0)) (111 (90.0 47.60907745361328 449.7053527832031 60.90726852416992 "Summing up zap-to-char
93
" 0 0) (104.99969482421875 79.64905548095703 406.3742370605469 92.9472427368164 "In template form, a search-forward expression looks like this:
" 1 0) (105.00001525878906 98.13507843017578 286.3546447753906 159.30711364746094 "(search-forward \"target-string\"
limit-of-search
what-to-do-if-search-fails
repeat-count)
We will look at progn next.
" 2 0) (90.00045776367188 173.04168701171875 280.1197509765625 186.15724182128906 "8.1.4 The progn Special Form
" 3 0) (89.999755859375 194.24896240234375 449.3123474121094 257.5871276855469 "progn is a special form that causes each of its arguments to be evaluated
in sequence and then returns the value of the last one. The preceding ex-
pressions are evaluated only for the side effects they perform. The values
produced by them are discarded.
The template for a progn expression is very simple:
" 4 0) (89.998779296875 262.7774963378906 449.704345703125 458.5872802734375 "(progn
body...)
In zap-to-char, the progn expression has to do two things: put point
in exactly the right position; and return the location of point so that kill-
region will know how far to kill to.
The first argument to the progn is search-forward. When search-
forward finds the string, the function leaves point immediately after the
last character in the target string. (In this case the target string is just one
character long.) If the search is backwards, search-forward leaves point
just before the first character in the target. The movement of point is a side
effect.
The second and last argument to progn is the expression (point). This
expression returns the value of point, which in this case will be the location
to which it has been moved by search-forward. This value is returned
by the progn expression and is passed to kill-region as kill-region’s
second argument.
" 5 0) (89.99905395507812 472.44183349609375 288.1344299316406 485.5574035644531 "8.1.5 Summing up zap-to-char
" 6 0) (89.99838256835938 493.6490783691406 449.6391906738281 630.7872924804688 "Now that we have seen how search-forward and progn work, we can
see how the zap-to-char function works as a whole.
The first argument to kill-region is the position of the cursor when the
zap-to-char command is given—the value of point at that time. Within
the progn, the search function then moves point to just after the zapped-
to-character and point returns the value of this location. The kill-region
function puts together these two values of point, the first one as the beginning
of the region and the second one as the end of the region, and removes the
region.
The progn special form is necessary because the kill-region command
takes two arguments; and it would fail if search-forward and point ex-
" 7 0)) (112 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "94
Chapter 8: Cutting and Storing Text
" 0 0) (90.00021362304688 77.48908233642578 449.4110107421875 114.66727447509766 "pressions were written in sequence as two additional arguments. The progn
expression is a single argument to kill-region and returns the one value
that kill-region needs for its second argument.
" 1 0) (90.0006103515625 167.66033935546875 200.36294555664062 182.03355407714844 "8.2 kill-region
" 2 0) (89.9998779296875 198.80908203125 449.291259765625 236.10728454589844 "The zap-to-char function uses the kill-region function. This function
clips text from a region and copies that text to the kill ring, from which it
may be retrieved.
" 3 0) (90.00021362304688 245.84906005859375 449.4758605957031 283.0272521972656 "The Emacs 21 version of that function uses condition-case and copy-
region-as-kill, both of which we will explain.
condition-case is an
important special form.
" 4 0) (90.00009155273438 292.8890380859375 449.4002685546875 342.0672302246094 "In essence, the kill-region function calls condition-case, which takes
three arguments. In this function, the first argument does nothing. The
second argument contains the code that does the work when all goes well.
The third argument contains the code that is called in the event of an error.
" 5 0) (89.99957275390625 351.92913818359375 449.4868469238281 377.1073303222656 "We will go through the condition-case code in a moment. First, let us
look at the complete definition of kill-region, with comments added:
" 6 0) (111.59980010986328 391.2976989746094 337.14312744140625 437.5840759277344 "(defun kill-region (beg end)
\"Kill between point and mark.
The text is deleted but saved in the kill ring.\"
(interactive \"r\")
" 7 0) (120.95938873291016 445.7777099609375 355.9999084472656 504.5440979003906 ";; 1. ‘condition-case’ takes three arguments.
;;
If the first argument is nil, as it is here,
;;
information about the error signal is not
;;
stored for use by another function.
(condition-case nil
" 8 0) (139.79957580566406 512.7377319335938 435.9376220703125 534.1841430664062 ";; 2. The second argument to ‘condition-case’
;;
tells the Lisp interpreter what to do when all goes well.
" 9 0) (139.79937744140625 542.2577514648438 440.60906982421875 588.6641845703125 ";;
The ‘delete-and-extract-region’ function usually does the
;;
work.
If the beginning and ending of the region are both
;;
the same, then the variable ‘string’ will be empty, or nil
(let ((string (delete-and-extract-region beg end)))
" 10 0) (149.27886962890625 596.73779296875 431.00848388671875 630.6641845703125 ";; ‘when’ is an ‘if’ clause that cannot take an ‘else-part’.
;; Emacs normally sets the value of ‘last-command’ to the
;; previous command.
" 11 0)) (113 (90.0 47.60907745361328 449.7706604003906 60.90726852416992 "condition-case
95
" 0 0) (149.27999877929688 81.33761596679688 431.1384582519531 177.4238739013672 ";; ‘kill-append’ concatenates the new string and the old.
;; ‘kill-new’ inserts text into a new item in the kill ring.
(when string
(if (eq last-command ’kill-region)
;; if true, prepend string
(kill-append string (< end beg))
(kill-new string)))
(setq this-command ’kill-region))
" 1 0) (130.440185546875 185.61746215820312 440.310302734375 296.2236022949219 ";; 3. The third argument to ‘condition-case’ tells the interpreter
;;
what to do with an error.
;;
The third argument has a conditions part and a body part.
;;
If the conditions are met (in this case,
;;
if text or buffer is read-only)
;;
then the body is executed.
((buffer-read-only text-read-only) ;; this is the if-part
;; then...
(copy-region-as-kill beg end)
" 2 0) (135.1208038330078 300.8172302246094 435.96441650390625 372.0635986328125 "(if kill-read-only-ok
;; usually this variable is nil
(message \"Read only text copied to kill ring\")
;; or else, signal an error if the buffer is read-only;
(barf-if-buffer-read-only)
;; and, in any case, signal that the text is read-only.
(signal ’text-read-only (list (current-buffer)))))))
" 3 0) (90.00175476074219 388.2014465332031 221.70285034179688 401.3170166015625 "8.2.1 condition-case
" 4 0) (90.00003051757812 410.60870361328125 449.4218444824219 550.1469116210938 "As we have seen earlier (see Section 1.3, “Generate an Error Message”,
page 4), when the Emacs Lisp interpreter has trouble evaluating an expres-
sion, it provides you with help; in the jargon, this is called “signaling an
error”. Usually, the computer stops the program and shows you a message.
However, some programs undertake complicated actions. They should not
simply stop on an error. In the kill-region function, the most likely error
is that you will try to kill text that is read-only and cannot be removed. So
the kill-region function contains code to handle this circumstance. This
code, which makes up the body of the kill-region function, is inside of a
condition-case special form.
The template for condition-case looks like this:
" 5 0) (90.00027465820312 556.5372924804688 449.7052917480469 630.786865234375 "(condition-case
var
bodyform
error-handler...)
The second argument, bodyform, is straightforward. The condition-
case special form causes the Lisp interpreter to evaluate the code in body-
" 6 0)) (114 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "96
Chapter 8: Cutting and Storing Text
" 0 0) (89.999267578125 77.48908233642578 449.72637939453125 336.9071350097656 "form.
If no error occurs, the special form returns the code’s value and
produces the side-effects, if any.
In short, the bodyform part of a condition-case expression determines
what should happen when everything works correctly.
However, if an error occurs, among its other actions, the function gener-
ating the error signal will define one or more error condition names.
An error handler is the third argument to condition case. An error
handler has two parts, a condition-name and a body. If the condition-name
part of an error handler matches a condition name generated by an error,
then the body part of the error handler is run.
As you will expect, the condition-name part of an error handler may be
either a single condition name or a list of condition names.
Also, a complete condition-case expression may contain more than one
error handler. When an error occurs, the first applicable handler is run.
Lastly, the first argument to the condition-case expression, the var
argument, is sometimes bound to a variable that contains information about
the error. However, if that argument is nil, as is the case in kill-region,
that information is discarded.
In brief, in the kill-region function, the code condition-case works
like this:
" 1 0) (111.59928894042969 342.5750732421875 276.3894348144531 364.02386474609375 "If no errors, run only this code
but, if errors, run this other code.
" 2 0) (89.99909973144531 378.3616943359375 295.57220458984375 391.4772644042969 "8.2.2 delete-and-extract-region
" 3 0) (89.99850463867188 400.1689453125 449.39874267578125 463.9871520996094 "A condition-case expression has two parts, a part that is evaluated in
the expectation that all will go well, but which may generate an error; and
a part that is evaluated when there is an error.
First, let us look at the code in kill-region that is run in the expectation
that all goes well. This is the core of the function. The code looks like this:
" 4 0) (89.99673461914062 469.7774963378906 449.7135925292969 630.7871704101562 "(let ((string (delete-and-extract-region beg end)))
(when string
(if (eq last-command ’kill-region)
(kill-append string (< end beg))
(kill-new string)))
(setq this-command ’kill-region))
It looks complicated because we have the new functions delete-and-
extract-region, kill-append, and kill-new as well as the new variables,
last-command and this-command.
The delete-and-extract-region function is straightforward.
It is a
built-in function that deletes the text in a region (a side effect) and also
returns that text. This is the function that actually removes the text. (And
if it cannot do that, it signals the error.)
" 5 0)) (115 (90.0 47.60907745361328 449.4761047363281 60.90726852416992 "delete-and-extract-region: Digressing into C
97
" 0 0) (89.9990234375 77.48908233642578 449.3990478515625 138.5472869873047 "In this let expression, the text that delete-and-extract-region re-
turns is placed in the local variable called ‘string’. This is the text that is
removed from the buffer. (To be more precise, the variable is set to point
to the address of the extracted text; to say it is ‘placed in’ the variable is
simply a shorthand.)
" 1 0) (89.99948120117188 142.64910888671875 449.2574768066406 167.9473114013672 "If the variable ‘string’ does point to text, that text is added to the kill
ring. The variable will have a nil value if no text was removed.
" 2 0) (89.9990234375 171.92913818359375 449.45355224609375 233.1073455810547 "The code uses when to determine whether the variable ‘string’ points
to text. A when statement is simply a programmers’ convenience. A when
statement is an if statement without the possibility of an else clause. In
your mind, you can replace when with if and understand what goes on.
That is what the Lisp interpreter does.
" 3 0) (89.99856567382812 237.08917236328125 449.4315490722656 334.1473693847656 "Technically speaking, when is a Lisp macro. A Lisp macro enables you to
define new control constructs and other language features. It tells the inter-
preter how to compute another Lisp expression which will in turn compute
the value. In this case, the ‘other expression’ is an if expression. For more
about Lisp macros, see section “Macros” in The GNU Emacs Lisp Reference
Manual. The C programming language also provides macros.
These are
different, but also useful. We will briefly look at C macros in Section 8.3,
“delete-and-extract-region: Digressing into C”, page 98.
" 4 0) (89.99832153320312 338.2491760253906 449.2127685546875 363.54736328125 "If the string has content, then another conditional expression is executed.
This is an if with both a then-part and an else-part.
" 5 0) (111.59770202636719 371.85772705078125 280.7150573730469 405.78411865234375 "(if (eq last-command ’kill-region)
(kill-append string (< end beg))
(kill-new string)))
" 6 0) (89.99758911132812 410.60919189453125 449.2992248535156 435.7873840332031 "The then-part is evaluated if the previous command was another call to
kill-region; if not, the else-part is evaluated.
" 7 0) (89.99685668945312 439.8891906738281 449.3205871582031 477.0673828125 "last-command is a variable that comes with Emacs that we have not seen
before. Normally, whenever a function is executed, Emacs sets the value of
last-command to the previous command.
" 8 0) (89.99752807617188 481.2891845703125 449.4083557128906 506.4673767089844 "In this segment of the definition, the if expression checks whether the
previous command was kill-region. If it was,
" 9 0) (111.59761047363281 514.8977661132812 261.8748474121094 523.8641357421875 "(kill-append string (< end beg))
" 10 0) (89.99722290039062 528.3292236328125 449.6584777832031 577.5074462890625 "concatenates a copy of the newly clipped text to the just previously clipped
text in the kill ring. (If the (< end beg)) expression is true, kill-append
prepends the string to the just previously clipped text. For a detailed dis-
cussion, see “The kill-append function”, page 104.)
" 11 0) (89.99578857421875 581.6091918945312 449.3963317871094 630.7874145507812 "If you then yank back the text, i.e., ‘paste’ it, you get both pieces of
text at once. That way, if you delete two words in a row, and then yank
them back, you get both words, in their proper order, with one yank. (The
(< end beg)) expression makes sure the order is correct.)
" 12 0)) (116 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "98
Chapter 8: Cutting and Storing Text
" 0 0) (90.00030517578125 77.48908233642578 449.37811279296875 114.66727447509766 "On the other hand, if the previous command is not kill-region, then
the kill-new function is called, which adds the text to the kill ring as the
latest item, and sets the kill-ring-yank-pointer variable to point to it.
" 1 0) (90.00042724609375 129.5003662109375 438.4172668457031 143.8735809326172 "8.3 delete-and-extract-region: Digressing into C
" 2 0) (89.99966430664062 151.52911376953125 450.0542907714844 326.3471984863281 "The zap-to-char command uses the delete-and-extract-region func-
tion, which in turn uses two other functions, copy-region-as-kill and
del_range_1. The copy-region-as-kill function will be described in a
following section; it puts a copy of the region in the kill ring so it can be
yanked back. (See Section 8.5, “copy-region-as-kill”, page 102.)
The delete-and-extract-region function removes the contents of a
region and you cannot get them back.
Unlike the other code discussed here, delete-and-extract-region is
not written in Emacs Lisp; it is written in C and is one of the primitives of
the GNU Emacs system. Since it is very simple, I will digress briefly from
Lisp and describe it here.
Like many of the other Emacs primitives, delete-and-extract-region
is written as an instance of a C macro, a macro being a template for code.
The complete macro looks like this:
" 3 0) (89.99880981445312 331.41754150390625 449.7698974609375 630.7874145507812 "DEFUN (\"delete-and-extract-region\", Fdelete_and_extract_region,
Sdelete_and_extract_region, 2, 2, 0,
\"Delete the text between START and END and return it.\")
(start, end)
Lisp_Object start, end;
{
validate_region (&start, &end);
return del_range_1 (XINT (start), XINT (end), 1, 1);
}
Without going into the details of the macro writing process, let me point
out that this macro starts with the word DEFUN. The word DEFUN was chosen
since the code serves the same purpose as defun does in Lisp. The word
DEFUN is followed by seven parts inside of parentheses:
• The first part is the name given to the function in Lisp, delete-and-
extract-region.
• The second part is the name of the function in C, Fdelete_and_
extract_region. By convention, it starts with ‘F’. Since C does not
use hyphens in names, underscores are used instead.
• The third part is the name for the C constant structure that records
information on this function for internal use.
It is the name of the
function in C but begins with an ‘S’ instead of an ‘F’.
• The fourth and fifth parts specify the minimum and maximum number
of arguments the function can have. This function demands exactly 2
arguments.
" 4 0)) (117 (90.0 47.60907745361328 449.4761047363281 60.90726852416992 "delete-and-extract-region: Digressing into C
99
" 0 0) (98.99945068359375 77.48908233642578 449.6716613769531 138.5472869873047 "• The sixth part is nearly like the argument that follows the interactive
declaration in a function written in Lisp: a letter followed, perhaps, by
a prompt. The only difference from the Lisp is when the macro is called
with no arguments. Then you write a 0 (which is a ‘null string’), as in
this macro.
" 1 0) (111.59991455078125 141.9290771484375 449.4319152832031 191.10728454589844 "If you were to specify arguments, you would place them between quo-
tation marks. The C macro for goto-char includes \"NGoto char: \" in
this position to indicate that the function expects a raw prefix, in this
case, a numerical location in a buffer, and provides a prompt.
" 2 0) (98.99966430664062 194.48907470703125 449.4976501464844 231.7872772216797 "• The seventh part is a documentation string, just like the one for a func-
tion written in Emacs Lisp, except that every newline must be written
explicitly as ‘\\n’ followed by a backslash and carriage return.
" 3 0) (111.59991455078125 235.2890625 449.3341064453125 260.4672546386719 "Thus, the first two lines of documentation for goto-char are written
like this:
" 4 0) (133.1998291015625 268.1777038574219 433.7183532714844 289.6240539550781 "\"Set point to POSITION, a number or marker.\\n\\
Beginning of buffer is position (point-min), end is (point-max).
" 5 0) (89.99935913085938 298.52911376953125 449.5086669921875 347.7073059082031 "In a C macro, the formal parameters come next, with a statement of
what kind of object they are, followed by what might be called the ‘body’
of the macro. For delete-and-extract-region the ‘body’ consists of the
following two lines:
" 6 0) (89.99679565429688 354.4576721191406 449.6374816894531 590.2274780273438 "validate_region (&start, &end);
return del_range_1 (XINT (start), XINT (end), 1, 1);
The first function, validate_region checks whether the values passed
as the beginning and end of the region are the proper type and are within
range. The second function, del_range_1, actually deletes the text.
del_range_1 is a complex function we will not look into. It updates the
buffer and does other things.
However, it is worth looking at the two arguments passed to del_range.
These are XINT (start) and XINT (end).
As far as the C language is concerned, start and end are two integers
that mark the beginning and end of the region to be deleted1.
In early versions of Emacs, these two numbers were thirty-two bits long,
but the code is slowly being generalized to handle other lengths. Three of
the available bits are used to specify the type of information and a fourth
bit is used for handling the computer’s memory; the remaining bits are used
as ‘content’.
‘XINT’ is a C macro that extracts the relevant number from the longer
collection of bits; the four other bits are discarded.
" 7 0) (89.98799896240234 605.5120239257812 233.98800659179688 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (95.87999725341797 606.5751953125 449.67626953125 630.3015747070312 "1 More precisely, and requiring more expert knowledge to understand, the two integers
are of type ‘Lisp
" 9 0) (171.70799255371094 627.5919799804688 174.58799743652344 628.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (174.4290008544922 621.335205078125 433.0134582519531 630.3015747070312 "Object’, which can also be a C union instead of an integer type.
" 11 0)) (118 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "100
Chapter 8: Cutting and Storing Text
" 0 0) (104.99929809570312 82.76905059814453 404.72625732421875 96.0672378540039 "The command in delete-and-extract-region looks like this:
" 1 0) (111.59918212890625 104.25759887695312 323.1026916503906 113.22398376464844 "del_range_1 (XINT (start), XINT (end), 1, 1);
" 2 0) (89.9990234375 117.44904327392578 449.3660888671875 142.7472381591797 "It deletes the region between the beginning position, start, and the ending
position, end.
" 3 0) (89.99874877929688 146.6090087890625 449.4092712402344 183.78721618652344 "From the point of view of the person writing Lisp, Emacs is all very
simple; but hidden underneath is a great deal of complexity to make it all
work.
" 4 0) (89.99874877929688 212.9002685546875 357.9072265625 227.2734832763672 "8.4 Initializing a Variable with defvar
" 5 0) (89.99795532226562 238.16900634765625 449.7906799316406 299.2272033691406 "Unlike the delete-and-extract-region function, the copy-region-as-
kill function is written in Emacs Lisp.
Two functions within it, kill-
append and kill-new, copy a region in a buffer and save it in a variable
called the kill-ring. This section describes how the kill-ring variable is
created and initialized using the defvar special form.
" 6 0) (89.99807739257812 303.0889892578125 449.3757019042969 340.2671813964844 "(Again we note that the term kill-ring is a misnomer. The text that
is clipped out of the buffer can be brought back; it is not a ring of corpses,
but a ring of resurrectable text.)
" 7 0) (89.99722290039062 344.12908935546875 449.3753356933594 381.3072814941406 "In Emacs Lisp, a variable such as the kill-ring is created and given an
initial value by using the defvar special form. The name comes from “define
variable”.
" 8 0) (89.99661254882812 385.1690979003906 449.5492858886719 446.227294921875 "The defvar special form is similar to setq in that it sets the value of a
variable. It is unlike setq in two ways: first, it only sets the value of the
variable if the variable does not already have a value. If the variable already
has a value, defvar does not override the existing value. Second, defvar
has a documentation string.
" 9 0) (89.99578857421875 450.089111328125 449.3742370605469 487.2673034667969 "(Another special form, defcustom, is designed for variables that people
customize. It has more features than defvar. (See Section 16.2, “Setting
Variables with defcustom”, page 214.)
" 10 0) (89.9957275390625 491.1291198730469 449.41754150390625 534.1698608398438 "You can see the current value of a variable, any variable, by using the
describe-variable function, which is usually invoked by typing C-h v. If
you type C-h v and then kill-ring (followed by ⟨
" 11 0) (324.8280029296875 518.3919677734375 342.947998046875 518.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (324.8399963378906 519.6023559570312 342.94012451171875 527.572509765625 "RET
" 13 0) (324.8280029296875 526.9119873046875 342.947998046875 527.3919677734375 "<image: None, width: 1, height: 1, bpc: 1>" 14 1) (90.00027465820312 515.009033203125 449.7708435058594 576.187255859375 "⟩) when prompted, you
will see what is in your current kill ring—this may be quite a lot! Conversely,
if you have been doing nothing this Emacs session except read this document,
you may have nothing in it. Also, you will see the documentation for kill-
ring:
" 15 0) (111.600341796875 584.2576293945312 435.6134033203125 630.6640014648438 "Documentation:
List of killed text sequences.
Since the kill ring is supposed to interact nicely with cut-and-paste
facilities offered by window systems, use of this variable should
" 16 0)) (119 (90.0 47.60907745361328 449.70574951171875 60.90726852416992 "copy-region-as-kill
101
" 0 0) (111.59962463378906 81.33761596679688 440.53277587890625 140.1039276123047 "interact nicely with ‘interprogram-cut-function’ and
‘interprogram-paste-function’.
The functions ‘kill-new’,
‘kill-append’, and ‘current-kill’ are supposed to implement this
interaction; you may want to use them instead of manipulating the kill
ring directly.
" 1 0) (105.00000762939453 144.68902587890625 377.5415344238281 157.9872283935547 "The kill ring is defined by a defvar in the following way:
" 2 0) (111.5997314453125 165.21755981445312 266.4454650878906 199.02391052246094 "(defvar kill-ring nil
\"List of killed text sequences.
...\")
" 3 0) (89.99899291992188 202.64898681640625 449.410400390625 299.71600341796875 "In this variable definition, the variable is given an initial value of nil, which
makes sense, since if you have saved nothing, you want nothing back if you
give a yank command. The documentation string is written just like the
documentation string of a defun. As with the documentation string of the
defun, the first line of the documentation should be a complete sentence,
since some commands, like apropos, print only the first line of documenta-
tion. Succeeding lines should not be indented; otherwise they look odd when
you use C-h v (describe-variable).
" 4 0) (89.9993896484375 319.6817626953125 270.5360412597656 332.7973327636719 "8.4.1 defvar and an asterisk
" 5 0) (89.996826171875 343.04901123046875 449.37518310546875 456.1872253417969 "In the past, Emacs used the defvar special form both for internal vari-
ables that you would not expect a user to change and for variables that you
do expect a user to change. Although you can still use defvar for user cus-
tomizable variables, please use defcustom instead, since that special form
provides a path into the Customization commands. (See Section 16.2, “Set-
ting Variables with defcustom”, page 214.)
When you specified a variable using the defvar special form, you could
distinguish a readily settable variable from others by typing an asterisk, ‘*’,
in the first column of its documentation string. For example:
" 6 0) (111.5960693359375 463.4175720214844 360.48828125 497.22393798828125 "(defvar shell-command-default-error-buffer nil
\"*Buffer name for ‘shell-command’ ... error output.
... \")
" 7 0) (89.99478149414062 501.44903564453125 449.4049987792969 630.7872314453125 "This means that you could (and still can) use the edit-options command
to change the value of shell-command-default-error-buffer temporarily.
However, options set using edit-options are set only for the duration
of your editing session.
The new values are not saved between sessions.
Each time Emacs starts, it reads the original value, unless you change the
value within your ‘.emacs’ file, either by setting it manually or by using
customize. See Chapter 16, “Your ‘.emacs’ File”, page 213.
For me, the major use of the edit-options command is to suggest vari-
ables that I might want to set in my ‘.emacs’ file. I urge you to look through
the list. (See section “Editing Variable Values” in The GNU Emacs Manual.)
" 8 0)) (120 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "102
Chapter 8: Cutting and Storing Text
" 0 0) (89.99929809570312 77.30034637451172 259.45269775390625 91.67356872558594 "8.5 copy-region-as-kill
" 1 0) (89.99923706054688 102.08905792236328 449.4429931640625 127.38724517822266 "The copy-region-as-kill function copies a region of text from a buffer
and (via either kill-append or kill-new) saves it in the kill-ring.
" 2 0) (89.99862670898438 130.649169921875 449.4093017578125 203.70738220214844 "If you call copy-region-as-kill immediately after a kill-region com-
mand, Emacs appends the newly copied text to the previously copied text.
This means that if you yank back the text, you get it all, from both this and
the previous operation. On the other hand, if some other command precedes
the copy-region-as-kill, the function copies the text into a separate entry
in the kill ring.
" 3 0) (89.9993896484375 207.20916748046875 449.5195007324219 232.5073699951172 "Here is the complete text of the version 21 copy-region-as-kill func-
tion:
" 4 0) (111.59811401367188 240.09768676757812 355.91387939453125 311.3439636230469 "(defun copy-region-as-kill (beg end)
\"Save the region as if killed, but don’t kill it.
In Transient Mark mode, deactivate the mark.
If ‘interprogram-cut-function’ is non-nil, also save
the text for a window system cut and paste.\"
(interactive \"r\")
" 5 0) (120.95783233642578 315.9375915527344 384.1217041015625 349.74395751953125 "(if (eq last-command ’kill-region)
(kill-append (buffer-substring beg end) (< end beg))
(kill-new (buffer-substring beg end)))
" 6 0) (120.95694732666016 354.33758544921875 257.23724365234375 388.1439514160156 "(if transient-mark-mode
(setq deactivate-mark t))
nil)
" 7 0) (104.9969482421875 393.20904541015625 409.851318359375 406.5072326660156 "As usual, this function can be divided into its component parts:
" 8 0) (111.59716796875 414.2151794433594 301.55157470703125 460.50396728515625 "(defun copy-region-as-kill (argument-list)
\"documentation...\"
(interactive \"r\")
body...)
" 9 0) (89.9969482421875 464.60906982421875 449.51690673828125 513.7872924804688 "The arguments are beg and end and the function is interactive with \"r\",
so the two arguments must refer to the beginning and end of the region.
If you have been reading though this document from the beginning, under-
standing these parts of a function is almost becoming routine.
" 10 0) (89.99630737304688 517.1690673828125 449.4075622558594 566.3472900390625 "The documentation is somewhat confusing unless you remember that the
word ‘kill’ has a meaning different from its usual meaning. The ‘Transient
Mark’ and interprogram-cut-function comments explain certain side-
effects.
" 11 0) (89.99679565429688 569.6090698242188 449.3855895996094 630.7872924804688 "After you once set a mark, a buffer always contains a region.
If you
wish, you can use Transient Mark mode to highlight the region temporarily.
(No one wants to highlight the region all the time, so Transient Mark mode
highlights it only at appropriate times. Many people turn off Transient Mark
mode, so the region is never highlighted.)
" 12 0)) (121 (90.0 47.60907745361328 449.6075744628906 60.90726852416992 "The Body of copy-region-as-kill
103
" 0 0) (90.00048828125 77.48908233642578 449.7930603027344 126.66727447509766 "Also, a windowing system allows you to copy, cut, and paste among differ-
ent programs. In the X windowing system, for example, the interprogram-
cut-function function is x-select-text, which works with the windowing
system’s equivalent of the Emacs kill ring.
" 1 0) (90.00155639648438 135.80908203125 449.5647888183594 208.86729431152344 "The body of the copy-region-as-kill function starts with an if
clause.
What this clause does is distinguish between two different situa-
tions: whether or not this command is executed immediately after a previ-
ous kill-region command. In the first case, the new region is appended
to the previously copied text. Otherwise, it is inserted into the beginning of
the kill ring as a separate piece of text from the previous piece.
" 2 0) (90.00198364257812 218.12908935546875 449.3362731933594 243.4272918701172 "The last two lines of the function prevent the region from lighting up if
Transient Mark mode is turned on.
" 3 0) (105.00215148925781 252.5689697265625 406.0276794433594 265.8671569824219 "The body of copy-region-as-kill merits discussion in detail.
" 4 0) (90.00238037109375 305.04168701171875 341.162353515625 318.1572570800781 "8.5.1 The Body of copy-region-as-kill
" 5 0) (90.00070190429688 334.7689514160156 449.4456787109375 431.7071533203125 "The copy-region-as-kill function works in much the same way as the
kill-region function (see Section 8.2, “kill-region”, page 94). Both are
written so that two or more kills in a row combine their text into a single
entry. If you yank back the text from the kill ring, you get it all in one piece.
Moreover, kills that kill forward from the current position of the cursor are
added to the end of the previously copied text and commands that copy text
backwards add it to the beginning of the previously copied text. This way,
the words in the text stay in the proper order.
" 6 0) (90.00054931640625 440.9689636230469 449.411376953125 466.14715576171875 "Like kill-region, the copy-region-as-kill function makes use of the
last-command variable that keeps track of the previous Emacs command.
" 7 0) (90.00006103515625 475.4089660644531 449.6722412109375 524.587158203125 "Normally, whenever a function is executed, Emacs sets the value of this-
command to the function being executed (which in this case would be copy-
region-as-kill). At the same time, Emacs sets the value of last-command
to the previous value of this-command.
" 8 0) (89.99954223632812 533.72900390625 449.7159118652344 630.7872314453125 "In the first part of the body of the copy-region-as-kill function, an if
expression determines whether the value of last-command is kill-region.
If so, the then-part of the if expression is evaluated; it uses the kill-append
function to concatenate the text copied at this call to the function with the
text already in the first element (the car) of the kill ring. On the other
hand, if the value of last-command is not kill-region, then the copy-
region-as-kill function attaches a new element to the kill ring using the
kill-new function.
" 9 0)) (122 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "104
Chapter 8: Cutting and Storing Text
" 0 0) (89.99917602539062 80.36908721923828 449.2677917480469 105.66727447509766 "The if expression reads as follows; it uses eq, which is a function we have
not yet seen:
" 1 0) (89.99847412109375 111.45761108398438 449.4857482910156 272.2273864746094 "(if (eq last-command ’kill-region)
;; then-part
(kill-append (buffer-substring beg end) (< end beg))
;; else-part
(kill-new (buffer-substring beg end)))
The eq function tests whether its first argument is the same Lisp object as
its second argument. The eq function is similar to the equal function in
that it is used to test for equality, but differs in that it determines whether
two representations are actually the same object inside the computer, but
with different names. equal determines whether the structure and contents
of two expressions are the same.
If the previous command was kill-region, then the Emacs Lisp inter-
preter calls the kill-append function
" 2 0) (89.99858093261719 288.001953125 251.68435668945312 301.1175231933594 "The kill-append function
" 3 0) (104.99858093261719 310.0491943359375 304.929443359375 323.3473815917969 "The kill-append function looks like this:
" 4 0) (89.99673461914062 329.1377258300781 449.5290832519531 515.8274536132812 "(defun kill-append (string before-p)
\"Append STRING to the end of the latest kill in the kill ring.
If BEFORE-P is non-nil, prepend STRING to the kill.
If ‘interprogram-cut-function’ is set, pass the resulting kill to
it.\"
(kill-new (if before-p
(concat string (car kill-ring))
(concat (car kill-ring) string))
t))
The kill-append function is fairly straightforward. It uses the kill-new
function, which we will discuss in more detail in a moment.
First, let us look at the conditional that is one of the two arguments to
kill-new. It uses concat to concatenate the new text to the car of the kill
ring. Whether it prepends or appends the text depends on the results of an
if expression:
" 5 0) (89.99578857421875 521.6153564453125 449.46099853515625 630.7874755859375 "(if before-p
; if-part
(concat string (car kill-ring))
; then-part
(concat (car kill-ring) string))
; else-part
If the region being killed is before the region that was killed in the last
command, then it should be prepended before the material that was saved
in the previous kill; and conversely, if the killed text follows what was just
killed, it should be appended after the previous text. The if expression
depends on the predicate before-p to decide whether the newly saved text
should be put before or after the previously saved text.
" 6 0)) (123 (90.0 47.60907745361328 449.7056579589844 60.90726852416992 "The kill-new function
105
" 0 0) (89.99661254882812 77.48908233642578 449.5302734375 248.9473114013672 "The symbol before-p is the name of one of the arguments to kill-
append. When the kill-append function is evaluated, it is bound to the
value returned by evaluating the actual argument. In this case, this is the ex-
pression (< end beg). This expression does not directly determine whether
the killed text in this command is located before or after the kill text of the
last command; what is does is determine whether the value of the variable
end is less than the value of the variable beg. If it is, it means that the
user is most likely heading towards the beginning of the buffer. Also, the
result of evaluating the predicate expression, (< end beg), will be true and
the text will be prepended before the previous text. On the other hand, if
the value of the variable end is greater than the value of the variable beg,
the text will be appended after the previous text.
When the newly saved text will be prepended, then the string with the
new text will be concatenated before the old text:
" 1 0) (89.99690246582031 254.73764038085938 447.55267333984375 278.9472961425781 "(concat string (car kill-ring))
But if the text will be appended, it will be concatenated after the old text:
" 2 0) (89.99627685546875 284.6176452636719 449.53839111328125 332.7073059082031 "(concat (car kill-ring) string))
To understand how this works, we first need to review the concat func-
tion. The concat function links together or unites two strings of text. The
result is a string. For example:
" 3 0) (111.596435546875 338.3776550292969 205.43896484375 365.56982421875 "(concat \"abc\" \"def\")
⇒ \"abcdef\"
" 4 0) (111.59651947021484 367.8976745605469 346.3886413574219 407.5698547363281 "(concat \"new \"
(car ’(\"first element\" \"second element\")))
⇒ \"new first element\"
" 5 0) (89.99771118164062 417.81768798828125 449.44061279296875 502.8673400878906 "(concat (car
’(\"first element\" \"second element\")) \" modified\")
⇒ \"first element modified\"
We can now make sense of kill-append: it modifies the contents of the
kill ring. The kill ring is a list, each element of which is saved text. The
kill-append function uses the kill-new function which in turn uses the
setcar function.
" 6 0) (89.99771118164062 518.4019165039062 231.4165802001953 531.5174560546875 "The kill-new function
" 7 0) (104.9977035522461 540.4490966796875 287.8011474609375 553.747314453125 "The kill-new function looks like this:
" 8 0) (111.5980224609375 559.4176635742188 445.1855163574219 630.6640625 "(defun kill-new (string &optional replace)
\"Make STRING the latest kill in the kill ring.
Set the kill-ring-yank pointer to point to it.
If ‘interprogram-cut-function’ is non-nil, apply it to STRING.
Optional second argument REPLACE non-nil means that STRING will replace
the front of the kill ring, rather than being added to the list.\"
" 9 0)) (124 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "106
Chapter 8: Cutting and Storing Text
" 0 0) (120.96026611328125 81.33761596679688 449.64434814453125 166.02391052246094 "(and (fboundp ’menu-bar-update-yank-menu)
(menu-bar-update-yank-menu string (and replace (car kill-ring))))
(if (and replace kill-ring)
(setcar kill-ring string)
(setq kill-ring (cons string kill-ring))
(if (> (length kill-ring) kill-ring-max)
(setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
" 1 0) (104.99983215332031 170.61752319335938 412.13623046875 236.1071014404297 "(setq kill-ring-yank-pointer kill-ring)
(if interprogram-cut-function
(funcall interprogram-cut-function string (not replace))))
As usual, we can look at this function in parts.
The first line of the documentation makes sense:
" 2 0) (89.9996337890625 242.49746704101562 449.53057861328125 310.2670593261719 "Make STRING the latest kill in the kill ring.
Let’s skip over the rest of the documentation for the moment.
Also, let’s skip over the first two lines of code, those involving menu-bar-
update-yank-menu. We will explain them below.
The critical lines are these:
" 3 0) (89.99771118164062 316.6574401855469 449.551025390625 519.6673583984375 "(if (and replace kill-ring)
;; then
(setcar kill-ring string)
;; else
(setq kill-ring (cons string kill-ring))
(if (> (length kill-ring) kill-ring-max)
;; avoid overly long kill ring
(setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
(setq kill-ring-yank-pointer kill-ring)
(if interprogram-cut-function
(funcall interprogram-cut-function string (not replace))))
The conditional test is (and replace kill-ring). This will be true when
two conditions are met: the kill ring has something in it, and the replace
variable is true.
The kill-append function sets replace to be true; then, when the kill
ring has at least one item in it, the setcar expression is executed:
" 4 0) (89.99749755859375 526.1776733398438 449.56103515625 590.3472900390625 "(setcar kill-ring string)
The setcar function actually changes the first element of the kill-ring
list to the value of string. It replaces the first element.
On the other hand, if the kill ring is empty, or replace is false, the else-part
of the condition is executed:
" 5 0) (111.59748840332031 596.7376098632812 369.9618225097656 630.6640014648438 "(setq kill-ring (cons string kill-ring))
(if (> (length kill-ring) kill-ring-max)
(setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
" 6 0)) (125 (90.0 47.60907745361328 449.7056579589844 60.90726852416992 "The kill-new function
107
" 0 0) (89.99853515625 77.48908233642578 449.60662841796875 173.82725524902344 "This expression first constructs a new version of the kill ring by prepending
string to the existing kill ring as a new element. Then it executes a second
if clause. This second if clause keeps the kill ring from growing too long.
Let’s look at these two expressions in order.
The setq line of the else-part sets the new value of the kill ring to what
results from adding the string being killed to the old kill ring.
We can see how this works with an example:
" 1 0) (89.99884033203125 180.45761108398438 449.54071044921875 217.62730407714844 "(setq example-list ’(\"here is a clause\" \"another clause\"))
After evaluating this expression with C-x C-e, you can evaluate example-
list and see what it returns:
" 2 0) (111.59883880615234 224.37765502929688 322.9218444824219 251.56983947753906 "example-list
⇒ (\"here is a clause\" \"another clause\")
" 3 0) (89.99874877929688 249.9290771484375 449.18060302734375 275.2272644042969 "Now, we can add a new element on to this list by evaluating the following
expression:
" 4 0) (89.99903869628906 281.8576354980469 374.48858642578125 307.1473083496094 "(setq example-list (cons \"a third clause\" example-list))
When we evaluate example-list, we find its value is:
" 5 0) (89.99884033203125 313.8976745605469 449.43133544921875 379.3872375488281 "example-list
⇒ (\"a third clause\" \"here is a clause\" \"another clause\")
Thus, the third clause was added to the list by cons.
This is exactly similar to what the setq and cons do in the function.
Here is the line again:
" 6 0) (89.99850463867188 386.1376037597656 449.27850341796875 423.3072509765625 "(setq kill-ring (cons string kill-ring))
Now for the second part of the if clause. This expression keeps the kill
ring from growing too long. It looks like this:
" 7 0) (89.99661254882812 430.0576171875 449.4943542480469 630.787353515625 "(if (> (length kill-ring) kill-ring-max)
(setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
The code checks whether the length of the kill ring is greater than the
maximum permitted length. This is the value of kill-ring-max (which is
60, by default). If the length of the kill ring is too long, then this code sets
the last element of the kill ring to nil. It does this by using two functions,
nthcdr and setcdr.
We looked at setcdr earlier (see Section 7.6, “setcdr”, page 88). It sets
the cdr of a list, just as setcar sets the car of a list. In this case, however,
setcdr will not be setting the cdr of the whole kill ring; the nthcdr function
is used to cause it to set the cdr of the next to last element of the kill ring—
this means that since the cdr of the next to last element is the last element
of the kill ring, it will set the last element of the kill ring.
The nthcdr function works by repeatedly taking the cdr of a list—it
takes the cdr of the cdr of the cdr . . . It does this N times and returns
the results.
" 8 0)) (126 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "108
Chapter 8: Cutting and Storing Text
" 0 0) (89.99761962890625 77.48908233642578 449.5075378417969 153.5472869873047 "Thus, if we had a four element list that was supposed to be three elements
long, we could set the cdr of the next to last element to nil, and thereby
shorten the list.
You can see this by evaluating the following three expressions in turn.
First set the value of trees to (maple oak pine birch), then set the cdr
of its second cdr to nil and then find the value of trees:
" 1 0) (111.5970458984375 159.57760620117188 280.6887512207031 186.64979553222656 "(setq trees ’(maple oak pine birch))
⇒ (maple oak pine birch)
" 2 0) (111.59774017333984 189.09756469726562 247.86065673828125 216.2897491455078 "(setcdr (nthcdr 2 trees) nil)
⇒ nil
" 3 0) (89.9969482421875 226.41757202148438 449.4081115722656 341.9472351074219 "trees
⇒ (maple oak pine)
(The value returned by the setcdr expression is nil since that is what the
cdr is set to.)
To repeat, in kill-new, the nthcdr function takes the cdr a number of
times that is one less than the maximum permitted size of the kill ring and
sets the cdr of that element (which will be the rest of the elements in the
kill ring) to nil. This prevents the kill ring from growing too long.
The next to last expression in the kill-new function is
" 4 0) (89.99649047851562 347.97760009765625 449.4188232421875 462.187255859375 "(setq kill-ring-yank-pointer kill-ring)
The kill-ring-yank-pointer is a global variable that is set to be the
kill-ring.
Even though the kill-ring-yank-pointer is called a ‘pointer’, it is
a variable just like the kill ring. However, the name has been chosen to
help humans understand how the variable is used. The variable is used in
functions such as yank and yank-pop (see Chapter 10, “Yanking Text Back”,
page 117).
Now, to return to the first two lines in the body of the function:
" 5 0) (89.99502563476562 468.09759521484375 449.787841796875 630.7872924804688 "(and (fboundp ’menu-bar-update-yank-menu)
(menu-bar-update-yank-menu string (and replace (car kill-ring))))
This is an expression whose first element is the function and.
The and special form evaluates each of its arguments until one of the
arguments returns a value of nil, in which case the and expression returns
nil; however, if none of the arguments returns a value of nil, the value
resulting from evaluating the last argument is returned. (Since such a value
is not nil, it is considered true in Emacs Lisp.) In other words, an and
expression returns a true value only if all its arguments are true.
In this case, the expression tests first to see whether menu-bar-update-
yank-menu exists as a function, and if so, calls it. The fboundp function
returns true if the symbol it is testing has a function definition that ‘is not
void’. If the symbol’s function definition were void, we would receive an error
" 6 0)) (127 (90.0 47.60907745361328 449.8467712402344 60.90726852416992 "Review
109
" 0 0) (89.99984741210938 77.48908233642578 449.2468566894531 102.66727447509766 "message, as we did when we created errors intentionally (see Section 1.3,
“Generate an Error Message”, page 4).
" 1 0) (105.000244140625 106.88910675048828 387.5562438964844 120.18729400634766 "Essentially, the and is an if expression that reads like this:
" 2 0) (111.60015869140625 128.615234375 241.45623779296875 150.0640106201172 "if the-menu-bar-function-exists
then execute-it
" 3 0) (89.99859619140625 154.88897705078125 449.4098815917969 204.0671844482422 "menu-bar-update-yank-menu is one of the functions that make it possi-
ble to use the ‘Select and Paste’ menu in the Edit item of a menu bar; using
a mouse, you can look at the various pieces of text you have saved and select
one piece to paste.
" 4 0) (89.997802734375 208.16900634765625 449.39788818359375 281.2272033691406 "Finally, the last expression in the kill-new function adds the newly
copied string to whatever facility exists for copying and pasting among dif-
ferent programs running in a windowing system. In the X Windowing sys-
tem, for example, the x-select-text function takes the string and stores
it in memory operated by X. You can paste the string in another program,
such as an Xterm.
" 5 0) (104.99807739257812 285.44903564453125 248.26699829101562 298.7472229003906 "The expression looks like this:
" 6 0) (120.95789337158203 307.1775817871094 412.13360595703125 328.6239318847656 "(if interprogram-cut-function
(funcall interprogram-cut-function string (not replace))))
" 7 0) (89.99664306640625 333.44903564453125 449.6152648925781 394.5072326660156 "If an interprogram-cut-function exists, then Emacs executes funcall,
which in turn calls its first argument as a function and passes the remaining
arguments to it. (Incidentally, as far as I can see, this if expression could
be replaced by an and expression similar to the one in the first part of the
function.)
" 8 0) (89.99575805664062 398.6090393066406 449.5272216796875 435.7872314453125 "We are not going to discuss windowing systems and other programs fur-
ther, but merely note that this is a mechanism that enables GNU Emacs to
work easily and well with other programs.
" 9 0) (89.99566650390625 439.8890380859375 449.3954772949219 513.0672607421875 "This code for placing text in the kill ring, either concatenated with an
existing element or as a new element, leads us to the code for bringing back
text that has been cut out of the buffer—the yank commands. However,
before discussing the yank commands, it is better to learn how lists are
implemented in a computer. This will make clear such mysteries as the use
of the term ‘pointer’.
" 10 0) (89.99583435058594 543.1403198242188 169.88682556152344 557.5008544921875 "8.6 Review
" 11 0) (104.99583435058594 568.76904296875 405.0611267089844 582.0672607421875 "Here is a brief summary of some recently introduced functions.
" 12 0) (89.99554443359375 595.45263671875 449.3626403808594 630.7872314453125 "car
cdr
car returns the first element of a list; cdr returns the second
and subsequent elements of a list.
" 13 0)) (128 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "110
Chapter 8: Cutting and Storing Text
" 0 0) (147.59930419921875 80.36908721923828 209.08302307128906 93.66727447509766 "For example:
" 1 0) (169.19931030273438 99.57760620117188 272.547119140625 151.6098175048828 "(car ’(1 2 3 4 5 6 7))
⇒ 1
(cdr ’(1 2 3 4 5 6 7))
⇒ (2 3 4 5 6 7)
" 2 0) (89.99894714355469 151.049072265625 449.3876647949219 191.10728454589844 "cons
cons constructs a list by prepending its first argument to its
second argument.
For example:
" 3 0) (169.19931030273438 197.01760864257812 249.10398864746094 224.2097930908203 "(cons 1 ’(2 3 4))
⇒ (1 2 3 4)
" 4 0) (89.99916076660156 222.61268615722656 450.1190185546875 264.9072570800781 "nthcdr
Return the result of taking cdr ‘n’ times on a list. The nth cdr.
The ‘rest of the rest’, as it were.
For example:
" 5 0) (169.19923400878906 270.8175964355469 296.032958984375 297.88983154296875 "(nthcdr 3 ’(1 2 3 4 5 6 7))
⇒ (4 5 6 7)
" 6 0) (89.99903869628906 297.61260986328125 449.4313659667969 347.8271789550781 "setcar
setcdr
setcar changes the first element of a list; setcdr changes the
second and subsequent elements of a list.
For example:
" 7 0) (169.19808959960938 353.7375183105469 272.5205078125 362.7038879394531 "(setq triple ’(1 2 3))
" 8 0) (169.1981201171875 378.5775146484375 258.36920166015625 387.54388427734375 "(setcar triple ’37)
" 9 0) (169.19821166992188 403.5375061035156 244.42286682128906 430.72967529296875 "triple
⇒ (37 2 3)
" 10 0) (169.1982421875 440.8575134277344 310.004150390625 449.8238830566406 "(setcdr triple ’(\"foo\" \"bar\"))
" 11 0) (169.19793701171875 465.8175048828125 281.9144592285156 493.0096740722656 "triple
⇒ (37 \"foo\" \"bar\")
" 12 0) (89.99771118164062 492.3289794921875 449.3211669921875 532.5072021484375 "progn
Evaluate each argument in sequence and then return the value
of the last.
For example:
" 13 0) (169.197265625 538.2975463867188 239.69931030273438 565.4896850585938 "(progn 1 2 3 4)
⇒ 4
" 14 0) (89.99727630615234 565.8126220703125 449.4185485839844 601.147216796875 "save-restriction
Record whatever narrowing is in effect in the current buffer, if
any, and restore that narrowing after evaluating the arguments.
" 15 0) (89.99667358398438 607.3326416015625 423.46551513671875 630.7872314453125 "search-forward
Search for a string, and if the string is found, move point.
" 16 0)) (129 (90.0 47.60907745361328 449.7166442871094 60.90726852416992 "Searching Exercises
111
" 0 0) (147.59988403320312 80.60907745361328 449.3992614746094 177.5472869873047 "Takes four arguments:
1. The string to search for.
2. Optionally, the limit of the search.
3. Optionally, what to do if the search fails, return nil or an
error message.
4. Optionally, how many times to repeat the search; if nega-
tive, the search goes backwards.
" 1 0) (89.99986267089844 183.9727325439453 449.53033447265625 332.9472961425781 "kill-region
delete-region
copy-region-as-kill
kill-region cuts the text between point and mark from the
buffer and stores that text in the kill ring, so you can get it back
by yanking.
delete-and-extract-region removes the text between point
and mark from the buffer and throws it away. You cannot get
it back.
copy-region-as-kill copies the text between point and mark
into the kill ring, from which you can get it by yanking. The
function does not cut or remove the text from the buffer.
" 2 0) (90.00003051757812 351.140380859375 256.5700988769531 365.50091552734375 "8.7 Searching Exercises
" 3 0) (98.99893188476562 371.2491149902344 449.8245544433594 471.30731201171875 "• Write an interactive function that searches for a string. If the search
finds the string, leave point after it and display a message that says
“Found!”. (Do not use search-forward for the name of this function;
if you do, you will overwrite the existing version of search-forward
that comes with Emacs. Use a name such as test-search instead.)
• Write a function that prints the third element of the kill ring in the echo
area, if any; if the kill ring does not contain a third element, print an
appropriate message.
" 4 0)) (130 (90.0 47.60907745361328 449.5741271972656 60.90726852416992 "112
Chapter 8: Cutting and Storing Text
" 0 0)) (131 (90.0 47.60907745361328 449.6723327636719 60.90726852416992 "How Lists are Implemented
113
" 0 0) (89.99957275390625 75.14844512939453 343.7232971191406 92.38106536865234 "9 How Lists are Implemented
" 1 0) (89.99710083007812 117.32910919189453 449.40826416015625 226.26731872558594 "In Lisp, atoms are recorded in a straightforward fashion; if the implemen-
tation is not straightforward in practice, it is, nonetheless, straightforward
in theory. The atom ‘rose’, for example, is recorded as the four contiguous
letters ‘r’, ‘o’, ‘s’, ‘e’. A list, on the other hand, is kept differently. The
mechanism is equally simple, but it takes a moment to get used to the idea.
A list is kept using a series of pairs of pointers. In the series, the first pointer
in each pair points to an atom or to another list, and the second pointer in
each pair points to the next pair, or to the symbol nil, which marks the end
of the list.
" 2 0) (89.99755859375 229.64910888671875 449.2771911621094 254.9473114013672 "A pointer itself is quite simply the electronic address of what is pointed
to. Hence, a list is kept as a series of electronic addresses.
" 3 0) (89.99618530273438 258.4490966796875 449.39727783203125 343.3872985839844 "For example, the list (rose violet buttercup) has three elements,
‘rose’, ‘violet’, and ‘buttercup’. In the computer, the electronic address
of ‘rose’ is recorded in a segment of computer memory along with the ad-
dress that gives the electronic address of where the atom ‘violet’ is located;
and that address (the one that tells where ‘violet’ is located) is kept along
with an address that tells where the address for the atom ‘buttercup’ is
located.
" 4 0) (104.99618530273438 347.0091247558594 449.27545166015625 360.30731201171875 "This sounds more complicated than it is and is easier seen in a diagram:
" 5 0) (190.1649932861328 433.68182373046875 396.4893798828125 444.2663269042969 "rose
violet
buttercup
" 6 0) (360.60198974609375 406.68182373046875 377.814453125 416.7033386230469 "nil
" 7 0) (89.997802734375 487.7685852050781 449.4200744628906 584.706787109375 "In the diagram, each box represents a word of computer memory that holds
a Lisp object, usually in the form of a memory address. The boxes, i.e.
the addresses, are in pairs. Each arrow points to what the address is the
address of, either an atom or another pair of addresses. The first box is the
electronic address of ‘rose’ and the arrow points to ‘rose’; the second box
is the address of the next pair of boxes, the first part of which is the address
of ‘violet’ and the second part of which is the address of the next pair. The
very last box points to the symbol nil, which marks the end of the list.
" 8 0) (89.99813842773438 588.32861328125 449.39794921875 613.5068359375 "When a variable is set to a list with a function such as setq, it stores the
address of the first box in the variable. Thus, evaluation of the expression
" 9 0) (111.59860229492188 621.337158203125 294.5763244628906 630.3035278320312 "(setq bouquet ’(rose violet buttercup))
" 10 0)) (132 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "114
Chapter 9: How Lists are Implemented
" 0 0) (89.99954223632812 79.52906036376953 221.51950073242188 92.8272476196289 "creates a situation like this:
" 1 0) (119.99949645996094 118.18231201171875 160.16201782226562 128.2038116455078 "bouquet
" 2 0) (215.625 167.11981201171875 421.94940185546875 177.7033233642578 "rose
violet
buttercup
" 3 0) (386.06201171875 140.11981201171875 403.27447509765625 150.1413116455078 "nil
" 4 0) (89.99981689453125 206.24908447265625 449.3343505859375 257.5872497558594 "In this example, the symbol bouquet holds the address of the first pair of
boxes.
This same list can be illustrated in a different sort of box notation like
this:
" 5 0) (130.559814453125 283.2998046875 170.7223358154297 293.3213195800781 "bouquet
" 6 0) (184.55999755859375 310.2998046875 201.7725067138672 320.3213195800781 "car
" 7 0) (184.55999755859375 328.2998046875 207.510009765625 338.3213195800781 "rose
" 8 0) (220.55999755859375 310.2998046875 280.5224609375 320.8833312988281 "cdr
car
" 9 0) (261.05999755859375 328.86181640625 295.48492431640625 338.8833312988281 "violet
" 10 0) (299.30999755859375 310.86181640625 382.222412109375 344.5088195800781 "cdr
car
butter-
cup
" 11 0) (390.99749755859375 311.9873046875 408.7724609375 335.5088195800781 "cdr
nil
" 12 0) (89.99853515625 372.9290771484375 449.4094543457031 507.78729248046875 "(Symbols consist of more than pairs of addresses, but the structure of
a symbol is made up of addresses. Indeed, the symbol bouquet consists of
a group of address-boxes, one of which is the address of the printed word
‘bouquet’, a second of which is the address of a function definition attached
to the symbol, if any, a third of which is the address of the first pair of
address-boxes for the list (rose violet buttercup), and so on. Here we
are showing that the symbol’s third address-box points to the first pair of
address-boxes for the list.)
If a symbol is set to the cdr of a list, the list itself is not changed; the
symbol simply has an address further down the list. (In the jargon, car and
cdr are ‘non-destructive’.) Thus, evaluation of the following expression
" 13 0) (89.99790954589844 512.7376708984375 242.9410858154297 536.227294921875 "(setq flowers (cdr bouquet))
produces this:
" 14 0) (225.52000427246094 615.4918212890625 431.8443908691406 626.0762939453125 "rose
violet
buttercup
" 15 0) (395.9570007324219 588.4918212890625 413.1694641113281 598.5133056640625 "nil
" 16 0) (109.6449966430664 564.3043212890625 222.36952209472656 574.3262939453125 "flowers
bouquet
" 17 0)) (133 (90.0 47.60907745361328 449.6505126953125 60.90726852416992 "Symbols as a Chest of Drawers
115
" 0 0) (89.99887084960938 77.48908233642578 449.442626953125 202.5072479248047 "The value of flowers is (violet buttercup), which is to say, the symbol
flowers holds the address of the pair of address-boxes, the first of which
holds the address of violet, and the second of which holds the address of
buttercup.
A pair of address-boxes is called a cons cell or dotted pair. See section
“List Type ” in The GNU Emacs Lisp Reference Manual, and section “Dot-
ted Pair Notation” in The GNU Emacs Lisp Reference Manual, for more
information about cons cells and dotted pairs.
The function cons adds a new pair of addresses to the front of a series of
addresses like that shown above. For example, evaluating the expression
" 1 0) (89.99844360351562 207.45761108398438 275.890625 230.94725036621094 "(setq bouquet (cons ’lily bouquet))
produces:
" 2 0) (331.3949890136719 311.1697998046875 365.8199157714844 321.1913146972656 "violet
" 3 0) (212.70700073242188 259.4197998046875 252.86952209472656 269.4413146972656 "flowers
" 4 0) (407.8949890136719 281.9197998046875 425.1074523925781 291.9413146972656 "nil
" 5 0) (392.1449890136719 300.4822998046875 443.7823791503906 310.5038146972656 "buttercup
" 6 0) (194.70700073242188 315.6697998046875 294.7199401855469 331.8783264160156 "rose
lily
" 7 0) (98.5198974609375 259.4197998046875 138.6824188232422 269.4413146972656 "bouquet
" 8 0) (89.99945068359375 361.7690734863281 449.3011169433594 387.0672607421875 "However, this does not change the value of the symbol flowers, as you can
see by evaluating the following,
" 9 0) (89.99810791015625 392.0176086425781 449.50653076171875 566.9473876953125 "(eq (cdr (cdr bouquet)) flowers)
which returns t for true.
Until it is reset, flowers still has the value (violet buttercup); that
is, it has the address of the cons cell whose first address is of violet. Also,
this does not alter any of the pre-existing cons cells; they are all still there.
Thus, in Lisp, to get the cdr of a list, you just get the address of the
next cons cell in the series; to get the car of a list, you get the address of
the first element of the list; to cons a new element on a list, you add a new
cons cell to the front of the list. That is all there is to it! The underlying
structure of Lisp is brilliantly simple!
And what does the last address in a series of cons cells refer to? It is the
address of the empty list, of nil.
In summary, when a Lisp variable is set to a value, it is provided with
the address of the list to which the variable refers.
" 10 0) (89.99845886230469 583.3404541015625 337.6324462890625 597.7009887695312 "9.1 Symbols as a Chest of Drawers
" 11 0) (89.99862670898438 605.4891357421875 449.38720703125 630.787353515625 "In an earlier section, I suggested that you might imagine a symbol as
being a chest of drawers. The function definition is put in one drawer, the
" 12 0)) (134 (90.0 47.60907745361328 449.5851745605469 60.90726852416992 "116
Chapter 9: How Lists are Implemented
" 0 0) (89.9967041015625 77.48908233642578 449.3753662109375 228.30723571777344 "value in another, and so on. What is put in the drawer holding the value can
be changed without affecting the contents of the drawer holding the function
definition, and vice-versa.
Actually, what is put in each drawer is the address of the value or function
definition. It is as if you found an old chest in the attic, and in one of its
drawers you found a map giving you directions to where the buried treasure
lies.
(In addition to its name, symbol definition, and variable value, a symbol
has a ‘drawer’ for a property list which can be used to record other infor-
mation. Property lists are not discussed here; see section “Property Lists”
in The GNU Emacs Lisp Reference Manual.)
Here is a fanciful representation:
" 1 0) (149.48399353027344 318.36480712890625 212.59652709960938 328.3863220214844 "symbol name
" 2 0) (135.14028930664062 255.92730712890625 393.55255126953125 265.9488220214844 "Chest of Drawers
Contents of Drawers
" 3 0) (284.540283203125 322.86480712890625 324.70269775390625 332.8863220214844 "bouquet
" 4 0) (284.540283203125 356.61480712890625 318.9652099609375 366.6363220214844 "[none]
" 5 0) (284.540283203125 389.80230712890625 416.50250244140625 399.8238220214844 "(rose violet buttercup)
" 6 0) (284.540283203125 422.42730712890625 399.2900390625 432.4488220214844 "[not described here]
" 7 0) (152.5570068359375 305.48919677734375 315.56915283203125 321.69537353515625 "directions to
map to
" 8 0) (287.91552734375 376.92669677734375 318.38165283203125 389.19537353515625 "map to
" 9 0) (131.70953369140625 340.92669677734375 229.24708557128906 362.6988220214844 "symbol definition
directions to
" 10 0) (143.7469482421875 377.48919677734375 218.33448791503906 398.1363220214844 "variable name
directions to
" 11 0) (143.7469482421875 412.92669677734375 218.33448791503906 433.5738220214844 "property list
directions to
" 12 0) (90.00052642822266 486.740234375 176.97854614257812 501.10076904296875 "9.2 Exercise
" 13 0) (90.00064086914062 508.888916015625 449.4986267089844 546.067138671875 "Set flowers to violet and buttercup. Cons two more flowers on to this
list and set this new list to more-flowers. Set the car of flowers to a fish.
What does the more-flowers list now contain?
" 14 0)) (135 (90.0 47.60907745361328 449.55303955078125 60.90726852416992 "The kill-ring-yank-pointer Variable
117
" 0 0) (90.00027465820312 75.14844512939453 281.0294189453125 92.38106536865234 "10 Yanking Text Back
" 1 0) (89.997802734375 105.80908966064453 449.4217834472656 276.9073181152344 "Whenever you cut text out of a buffer with a ‘kill’ command in GNU
Emacs, you can bring it back with a ‘yank’ command. The text that is cut
out of the buffer is put in the kill ring and the yank commands insert the
appropriate contents of the kill ring back into a buffer (not necessarily the
original buffer).
A simple C-y (yank) command inserts the first item from the kill ring into
the current buffer. If the C-y command is followed immediately by M-y, the
first element is replaced by the second element. Successive M-y commands
replace the second element with the third, fourth, or fifth element, and so
on. When the last element in the kill ring is reached, it is replaced by the
first element and the cycle is repeated. (Thus the kill ring is called a ‘ring’
rather than just a ‘list’. However, the actual data structure that holds the
text is a list. See Appendix B, “Handling the Kill Ring”, page 243, for the
details of how the list is handled as a ring.)
" 2 0) (89.99736022949219 295.22039794921875 263.0539855957031 309.5809326171875 "10.1 Kill Ring Overview
" 3 0) (104.99686431884766 317.84912109375 416.4182434082031 331.1473083496094 "The kill ring is a list of textual strings. This is what it looks like:
" 4 0) (89.9959716796875 336.5776672363281 449.51605224609375 499.3872985839844 "(\"some text\" \"a different piece of text\" \"yet more text\")
If this were the contents of my kill ring and I pressed C-y, the string
of characters saying ‘some text’ would be inserted in this buffer where my
cursor is located.
The yank command is also used for duplicating text by copying it. The
copied text is not cut from the buffer, but a copy of it is put on the kill ring
and is inserted by yanking it back.
Three functions are used for bringing text back from the kill ring: yank,
which is usually bound to C-y; yank-pop, which is usually bound to M-y;
and rotate-yank-pointer, which is used by the two other functions.
These functions refer to the kill ring through a variable called the kill-
ring-yank-pointer. Indeed, the insertion code for both the yank and yank-
pop functions is:
" 5 0) (89.99673461914062 504.9376525878906 449.69091796875 552.6673583984375 "(insert (car kill-ring-yank-pointer))
To begin to understand how yank and yank-pop work, it is first necessary
to look at the kill-ring-yank-pointer variable and the rotate-yank-
pointer function.
" 6 0) (89.99674224853516 570.9803466796875 385.566162109375 585.3535766601562 "10.2 The kill-ring-yank-pointer Variable
" 7 0) (89.99710083007812 593.609130859375 449.2554931640625 630.787353515625 "kill-ring-yank-pointer is a variable, just as kill-ring is a variable.
It points to something by being bound to the value of what it points to, like
any other Lisp variable.
" 8 0)) (136 (90.0 47.60907745361328 449.4651794433594 60.90726852416992 "118
Chapter 10: Yanking Text Back
" 0 0) (105.00018310546875 81.92908477783203 274.7453918457031 95.2272720336914 "Thus, if the value of the kill ring is:
" 1 0) (90.00045776367188 102.45761108398438 449.312744140625 140.22727966308594 "(\"some text\" \"a different piece of text\" \"yet more text\")
and the kill-ring-yank-pointer points to the second clause, the value of
kill-ring-yank-pointer is:
" 2 0) (90.00018310546875 147.57760620117188 450.0982360839844 232.98728942871094 "(\"a different piece of text\" \"yet more text\")
As explained in the previous chapter (see Chapter 9, “List Implementa-
tion”, page 113), the computer does not keep two different copies of the text
being pointed to by both the kill-ring and the kill-ring-yank-pointer.
The words “a different piece of text” and “yet more text” are not duplicated.
Instead, the two Lisp variables point to the same pieces of text. Here is a
diagram:
" 3 0) (272.60198974609375 331.8148193359375 416.0391845703125 341.8363342285156 "a different piece of text
" 4 0) (192.7270050048828 272.1898193359375 318.951904296875 282.2113342285156 "kill-ring-yank-pointer
" 5 0) (362.0400085449219 303.1278076171875 379.2524719238281 313.1493225097656 "nil
" 6 0) (333.3525085449219 321.6903076171875 407.9398498535156 331.7118225097656 "yet more text
" 7 0) (225.9149932861328 343.0648193359375 277.5524597167969 353.0863342285156 "some text
" 8 0) (128.0399932861328 272.1898193359375 179.67752075195312 282.2113342285156 "kill-ring
" 9 0) (89.99942016601562 393.6890869140625 450.0433349609375 630.787353515625 "Both the variable kill-ring and the variable kill-ring-yank-pointer
are pointers. But the kill ring itself is usually described as if it were actually
what it is composed of. The kill-ring is spoken of as if it were the list
rather than that it points to the list.
Conversely, the kill-ring-yank-
pointer is spoken of as pointing to a list.
These two ways of talking about the same thing sound confusing at first
but make sense on reflection. The kill ring is generally thought of as the
complete structure of data that holds the information of what has recently
been cut out of the Emacs buffers. The kill-ring-yank-pointer on the
other hand, serves to indicate—that is, to ‘point to’—that part of the kill
ring of which the first element (the car) will be inserted.
The rotate-yank-pointer function changes the element in the kill ring
to which the kill-ring-yank-pointer points; when the pointer is set to
point to the next element beyond the end of the kill ring, it automatically
sets it to point to the first element of the kill ring. This is how the list
is transformed into a ring. The rotate-yank-pointer function itself is not
difficult, but contains many details. It and the much simpler yank and yank-
pop functions are described in an appendix. See Appendix B, “Handling the
Kill Ring”, page 243.
" 10 0)) (137 (90.0 47.60907745361328 449.6283264160156 60.90726852416992 "Exercises with yank and nthcdr
119
" 0 0) (89.99957275390625 94.10033416748047 344.1437683105469 108.47355651855469 "10.3 Exercises with yank and nthcdr
" 1 0) (98.99966430664062 114.20905303955078 449.4647216796875 202.1472625732422 "• Using C-h v (describe-variable), look at the value of your kill ring.
Add several items to your kill ring; look at its value again. Using M-y
(yank-pop), move all the way around the kill ring. How many items
were in your kill ring? Find the value of kill-ring-max. Was your kill
ring full, or could you have kept more blocks of text within it?
• Using nthcdr and car, construct a series of expressions to return the
first, second, third, and fourth elements of a list.
" 2 0)) (138 (90.0 47.60907745361328 449.4651794433594 60.90726852416992 "120
Chapter 10: Yanking Text Back
" 0 0)) (139 (90.0 47.60907745361328 449.8577575683594 60.90726852416992 "while
121
" 0 0) (90.0 75.14844512939453 296.935546875 92.38106536865234 "11 Loops and Recursion
" 1 0) (89.99856567382812 103.04920196533203 449.4757995605469 239.82737731933594 "Emacs Lisp has two primary ways to cause an expression, or a series
of expressions, to be evaluated repeatedly: one uses a while loop, and the
other uses recursion.
Repetition can be very valuable.
For example, to move forward four
sentences, you need only write a program that will move forward one sentence
and then repeat the process four times. Since a computer does not get bored
or tired, such repetitive action does not have the deleterious effects that
excessive or the wrong kinds of repetition can have on humans.
People mostly write Emacs Lisp functions using while loops and their
kin; but you can use recursion, which provides a very powerful way to think
about and then to solve problems1.
" 2 0) (89.99853515625 255.9803466796875 163.80686950683594 270.35357666015625 "11.1 while
" 3 0) (89.99761962890625 278.129150390625 449.5387268066406 415.02734375 "The while special form tests whether the value returned by evaluating
its first argument is true or false. This is similar to what the Lisp interpreter
does with an if; what the interpreter does next, however, is different.
In a while expression, if the value returned by evaluating the first argu-
ment is false, the Lisp interpreter skips the rest of the expression (the body
of the expression) and does not evaluate it. However, if the value is true, the
Lisp interpreter evaluates the body of the expression and then again tests
whether the first argument to while is true or false. If the value returned
by evaluating the first argument is again true, the Lisp interpreter again
evaluates the body of the expression.
The template for a while expression looks like this:
" 4 0) (89.99716186523438 420.09527587890625 449.4409484863281 553.867431640625 "(while true-or-false-test
body...)
So long as the true-or-false-test of the while expression returns a true
value when it is evaluated, the body is repeatedly evaluated. This process
is called a loop since the Lisp interpreter repeats the same thing again and
again, like an airplane doing a loop. When the result of evaluating the true-
or-false-test is false, the Lisp interpreter does not evaluate the rest of the
while expression and ‘exits the loop’.
Clearly, if the value returned by evaluating the first argument to while
is always true, the body following will be evaluated again and again . . .
and again . . . forever. Conversely, if the value returned is never true, the
" 5 0) (89.98799896240234 561.7120361328125 233.98800659179688 562.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (95.87999725341797 562.6552124023438 449.8249206542969 630.3040161132812 "1 You can write recursive functions to be frugal or wasteful of mental or computer
resources; as it happens, methods that people find easy—that are frugal of ‘mental
resources’—sometimes use considerable computer resources. Emacs was designed to
run on machines that we now consider limited and its default settings are conservative.
You may want to increase the values of max-specpdl-size and max-lisp-eval-depth.
In my ‘.emacs’ file, I set them to 15 and 30 times their default value.
" 7 0)) (140 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "122
Chapter 11: Loops and Recursion
" 0 0) (89.9970703125 77.48908233642578 449.3988342285156 237.3072967529297 "expressions in the body will never be evaluated. The craft of writing a while
loop consists of choosing a mechanism such that the true-or-false-test returns
true just the number of times that you want the subsequent expressions to
be evaluated, and then have the test return false.
The value returned by evaluating a while is the value of the true-or-false-
test. An interesting consequence of this is that a while loop that evaluates
without error will return nil or false regardless of whether it has looped 1 or
100 times or none at all. A while expression that evaluates successfully never
returns a true value! What this means is that while is always evaluated for
its side effects, which is to say, the consequences of evaluating the expressions
within the body of the while loop. This makes sense. It is not the mere act
of looping that is desired, but the consequences of what happens when the
expressions in the loop are repeatedly evaluated.
" 1 0) (89.99700927734375 253.68182373046875 291.5620422363281 266.7973937988281 "11.1.1 A while Loop and a List
" 2 0) (89.996826171875 275.968994140625 449.407958984375 426.9071960449219 "A common way to control a while loop is to test whether a list has any
elements. If it does, the loop is repeated; but if it does not, the repetition is
ended. Since this is an important technique, we will create a short example
to illustrate it.
A simple way to test whether a list has elements is to evaluate the list:
if it has no elements, it is an empty list and will return the empty list, (),
which is a synonym for nil or false. On the other hand, a list with elements
will return those elements when it is evaluated. Since Emacs Lisp considers
as true any value that is not nil, a list that returns elements will test true
in a while loop.
For example, you can set the variable empty-list to nil by evaluating
the following setq expression:
" 3 0) (89.99749755859375 432.93756103515625 449.5176696777344 481.2760314941406 "(setq empty-list ())
After evaluating the setq expression, you can evaluate the variable empty-
list in the usual way, by placing the cursor after the symbol and typing
C-x C-e; nil will appear in your echo area:
" 4 0) (89.99752807617188 487.2975769042969 449.4297180175781 535.6272583007812 "empty-list
On the other hand, if you set a variable to be a list with elements, the
list will appear when you evaluate the variable, as you can see by evaluating
the following two expressions:
" 5 0) (111.59770202636719 541.6576538085938 318.1813049316406 550.6240234375 "(setq animals ’(gazelle giraffe lion tiger))
" 6 0) (89.99752807617188 566.4976196289062 449.33209228515625 603.187255859375 "animals
Thus, to create a while loop that tests whether there are any items in
the list animals, the first part of the loop will be written like this:
" 7 0) (111.597900390625 609.2175903320312 177.28302001953125 630.6640014648438 "(while animals
...
" 8 0)) (141 (90.0 47.60907745361328 449.56365966796875 60.90726852416992 "An Example: print-elements-of-list
123
" 0 0) (89.99810791015625 77.48908233642578 449.5508728027344 238.5072479248047 "When the while tests its first argument, the variable animals is evaluated.
It returns a list. So long as the list has elements, the while considers the
results of the test to be true; but when the list is empty, it considers the
results of the test to be false.
To prevent the while loop from running forever, some mechanism needs
to be provided to empty the list eventually. An oft-used technique is to have
one of the subsequent forms in the while expression set the value of the list
to be the cdr of the list. Each time the cdr function is evaluated, the list
will be made shorter, until eventually only the empty list will be left. At
this point, the test of the while loop will return false, and the arguments to
the while will no longer be evaluated.
For example, the list of animals bound to the variable animals can be
set to be the cdr of the original list with the following expression:
" 1 0) (89.99755859375 243.57760620117188 449.36456298828125 340.8671569824219 "(setq animals (cdr animals))
If you have evaluated the previous expressions and then evaluate this ex-
pression, you will see (giraffe lion tiger) appear in the echo area. If you
evaluate the expression again, (lion tiger) will appear in the echo area. If
you evaluate it again and yet again, (tiger) appears and then the empty
list, shown by nil.
A template for a while loop that uses the cdr function repeatedly to
cause the true-or-false-test eventually to test false looks like this:
" 2 0) (89.99737548828125 346.05511474609375 449.2766418457031 406.6271667480469 "(while test-whether-list-is-empty
body...
set-list-to-cdr-of-list)
This test and use of cdr can be put together in a function that goes
through a list and prints each element of the list on a line of its own.
" 3 0) (89.99697875976562 420.3617248535156 374.22027587890625 433.477294921875 "11.1.2 An Example: print-elements-of-list
" 4 0) (89.99591064453125 441.68896484375 449.4292297363281 574.3696899414062 "The print-elements-of-list function illustrates a while loop with a
list.
The function requires several lines for its output. If you are reading this
in Emacs 21 or a later version, you can evaluate the following expression
inside of Info, as usual.
If you are using an earlier version of Emacs, you need to copy the neces-
sary expressions to your ‘*scratch*’ buffer and evaluate them there. This
is because the echo area had only one line in the earlier versions.
You can copy the expressions by marking the beginning of the region with
C-⟨
" 5 0) (104.38800048828125 558.9520263671875 121.06800079345703 559.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (104.4000015258789 560.1624145507812 120.9459457397461 568.132568359375 "SPC
" 7 0) (104.38800048828125 567.4719848632812 121.06800079345703 567.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99960327148438 555.2091064453125 449.5413818359375 630.796142578125 "⟩ (set-mark-command), moving the cursor to the end of the region
and then copying the region using M-w (copy-region-as-kill).
In the
‘*scratch*’ buffer, you can yank the expressions back by typing C-y (yank).
After you have copied the expressions to the ‘*scratch*’ buffer, evaluate
each expression in turn. Be sure to evaluate the last expression, (print-
elements-of-list animals), by typing C-u C-x C-e, that is, by giving an
" 9 0)) (142 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "124
Chapter 11: Loops and Recursion
" 0 0) (89.99749755859375 77.48908233642578 449.3542785644531 166.1472625732422 "argument to eval-last-sexp.
This will cause the result of the evalua-
tion to be printed in the ‘*scratch*’ buffer instead of being printed in
the echo area.
(Otherwise you will see something like this in your echo
area: ^Jgiraffe^J^Jgazelle^J^Jlion^J^Jtiger^Jnil, in which each ‘^J’
stands for a ‘newline’.)
If you are using Emacs 21 or later, you can evaluate these expressions
directly in the Info buffer, and the echo area will grow to show the results.
" 1 0) (111.59710693359375 172.65762329101562 318.18072509765625 181.62400817871094 "(setq animals ’(gazelle giraffe lion tiger))
" 2 0) (111.59751892089844 197.49765014648438 355.97320556640625 256.3839416503906 "(defun print-elements-of-list (list)
\"Print each element of LIST on a line of its own.\"
(while list
(print (car list))
(setq list (cdr list))))
" 3 0) (111.59794616699219 272.2575988769531 261.7296447753906 281.2239685058594 "(print-elements-of-list animals)
" 4 0) (89.99794006347656 285.08905029296875 428.626708984375 298.3872375488281 "When you evaluate the three expressions in sequence, you will see this:
" 5 0) (111.59762573242188 305.0176086425781 144.33387756347656 313.9839782714844 "giraffe
" 6 0) (111.59762573242188 329.85760498046875 144.33387756347656 338.823974609375 "gazelle
" 7 0) (111.59762573242188 354.8175964355469 130.31942749023438 363.7839660644531 "lion
" 8 0) (89.99725341796875 379.6575927734375 449.4190979003906 453.7872619628906 "tiger
nil
Each element of the list is printed on a line of its own (that is what the
function print does) and then the value returned by the function is printed.
Since the last expression in the function is the while loop, and since while
loops always return nil, a nil is printed after the last element of the list.
" 9 0) (89.99700927734375 471.7218322753906 384.15179443359375 484.8258361816406 "11.1.3 A Loop with an Incrementing Counter
" 10 0) (89.99618530273438 494.36907958984375 449.5599670410156 630.787353515625 "A loop is not useful unless it stops when it ought. Besides controlling
a loop with a list, a common way of stopping a loop is to write the first
argument as a test that returns false when the correct number of repetitions
are complete. This means that the loop must have a counter—an expression
that counts how many times the loop repeats itself.
The test can be an expression such as (< count desired-number) which
returns t for true if the value of count is less than the desired-number of
repetitions and nil for false if the value of count is equal to or is greater
than the desired-number. The expression that increments the count can
be a simple setq such as (setq count (1+ count)), where 1+ is a built-
in function in Emacs Lisp that adds 1 to its argument. (The expression
" 11 0)) (143 (90.0 47.60907745361328 449.5850524902344 60.90726852416992 "Example with incrementing counter
125
" 0 0) (89.99920654296875 77.48908233642578 449.453125 130.1472625732422 "(1+ count) has the same result as (+ count 1), but is easier for a human
to read.)
The template for a while loop controlled by an incrementing counter
looks like this:
" 1 0) (89.99919128417969 136.53509521484375 440.0168151855469 198.90708923339844 "set-count-to-initial-value
(while (< count desired-number)
; true-or-false-test
body...
(setq count (1+ count)))
; incrementer
Note that you need to set the initial value of count; usually it is set to 1.
" 2 0) (89.99899291992188 216.48162841796875 321.0447998046875 229.5856170654297 "Example with incrementing counter
" 3 0) (89.99725341796875 239.0089111328125 449.3760070800781 276.1871032714844 "Suppose you are playing on the beach and decide to make a triangle of
pebbles, putting one pebble in the first row, two in the second row, three in
the third row and so on, like this:
" 4 0) (168.11724853515625 290.9729309082031 200.6706085205078 343.8495788574219 "•
• •
• • •
• • • •
" 5 0) (89.9937744140625 352.8888854980469 449.5350036621094 630.7872314453125 "(About 2500 years ago, Pythagoras and others developed the beginnings of
number theory by considering questions such as this.)
Suppose you want to know how many pebbles you will need to make a
triangle with 7 rows?
Clearly, what you need to do is add up the numbers from 1 to 7. There
are two ways to do this; start with the smallest number, one, and add up
the list in sequence, 1, 2, 3, 4 and so on; or start with the largest number
and add the list going down: 7, 6, 5, 4 and so on. Because both mechanisms
illustrate common ways of writing while loops, we will create two examples,
one counting up and the other counting down. In this first example, we will
start with 1 and add 2, 3, 4 and so on.
If you are just adding up a short list of numbers, the easiest way to do it
is to add up all the numbers at once. However, if you do not know ahead of
time how many numbers your list will have, or if you want to be prepared
for a very long list, then you need to design your addition so that what you
do is repeat a simple process many times instead of doing a more complex
process once.
For example, instead of adding up all the pebbles all at once, what you
can do is add the number of pebbles in the first row, 1, to the number in the
second row, 2, and then add the total of those two rows to the third row, 3.
Then you can add the number in the fourth row, 4, to the total of the first
three rows; and so on.
" 6 0)) (144 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "126
Chapter 11: Loops and Recursion
" 0 0) (89.99905395507812 77.48908233642578 449.3450622558594 162.5472869873047 "The critical characteristic of the process is that each repetitive action is
simple. In this case, at each step we add only two numbers, the number of
pebbles in the row and the total already found. This process of adding two
numbers is repeated again and again until the last row has been added to
the total of all the preceding rows. In a more complex loop the repetitive
action might not be so simple, but it will be simpler than doing everything
all at once.
" 1 0) (89.99919128417969 190.32183837890625 318.3243103027344 203.4258270263672 "The parts of the function definition
" 2 0) (89.99899291992188 216.2091064453125 449.4204406738281 253.50730895996094 "The preceding analysis gives us the bones of our function definition: first,
we will need a variable that we can call total that will be the total number
of pebbles. This will be the value returned by the function.
" 3 0) (89.99917602539062 258.9290771484375 449.42108154296875 296.1072692871094 "Second, we know that the function will require an argument: this ar-
gument will be the total number of rows in the triangle. It can be called
number-of-rows.
" 4 0) (89.99884033203125 301.64910888671875 449.44207763671875 350.7073059082031 "Finally, we need a variable to use as a counter. We could call this vari-
able counter, but a better name is row-number.
That is because what
the counter does is count rows, and a program should be written to be as
understandable as possible.
" 5 0) (89.99844360351562 356.2491149902344 449.4098205566406 429.30731201171875 "When the Lisp interpreter first starts evaluating the expressions in the
function, the value of total should be set to zero, since we have not added
anything to it. Then the function should add the number of pebbles in the
first row to the total, and then add the number of pebbles in the second to
the total, and then add the number of pebbles in the third row to the total,
and so on, until there are no more rows left to add.
" 6 0) (89.99850463867188 434.7291259765625 449.6817321777344 495.9073181152344 "Both total and row-number are used only inside the function, so they
can be declared as local variables with let and given initial values. Clearly,
the initial value for total should be 0. The initial value of row-number
should be 1, since we start with the first row. This means that the let
statement will look like this:
" 7 0) (120.95903015136719 505.6576843261719 219.7555389404297 539.5841064453125 "(let ((total 0)
(row-number 1))
body...)
" 8 0) (89.99783325195312 545.7291259765625 449.4095458984375 630.787353515625 "After the internal variables are declared and bound to their initial values,
we can begin the while loop. The expression that serves as the test should
return a value of t for true so long as the row-number is less than or equal
to the number-of-rows. (If the expression tests true only so long as the
row number is less than the number of rows in the triangle, the last row will
never be added to the total; hence the row number has to be either less than
or equal to the number of rows.)
" 9 0)) (145 (90.0 47.60907745361328 449.53106689453125 60.90726852416992 "Putting the function definition together
127
" 0 0) (89.99911499023438 80.00910186767578 449.5304870605469 129.1873016357422 "Lisp provides the <= function that returns true if the value of its first
argument is less than or equal to the value of its second argument and false
otherwise. So the expression that the while will evaluate as its test should
look like this:
" 1 0) (89.99813842773438 134.73764038085938 449.551513671875 230.3473358154297 "(<= row-number number-of-rows)
The total number of pebbles can be found by repeatedly adding the num-
ber of pebbles in a row to the total already found. Since the number of
pebbles in the row is equal to the row number, the total can be found by
adding the row number to the total. (Clearly, in a more complex situation,
the number of pebbles in the row might be related to the row number in
a more complicated way; if this were the case, the row number would be
replaced by the appropriate expression.)
" 2 0) (89.99673461914062 235.77767944335938 449.5052490234375 384.307373046875 "(setq total (+ total row-number))
What this does is set the new value of total to be equal to the sum of
adding the number of pebbles in the row to the previous total.
After setting the value of total, the conditions need to be established for
the next repetition of the loop, if there is one. This is done by incrementing
the value of the row-number variable, which serves as a counter.
After
the row-number variable has been incremented, the true-or-false-test at the
beginning of the while loop tests whether its value is still less than or equal
to the value of the number-of-rows and if it is, adds the new value of the
row-number variable to the total of the previous repetition of the loop.
The built-in Emacs Lisp function 1+ adds 1 to a number, so the row-
number variable can be incremented with this expression:
" 3 0) (111.59684753417969 389.85772705078125 266.4170227050781 398.8240966796875 "(setq row-number (1+ row-number))
" 4 0) (89.99642181396484 414.1219482421875 346.5849304199219 427.2259521484375 "Putting the function definition together
" 5 0) (89.99676513671875 435.8092041015625 449.5276184082031 475.62738037109375 "We have created the parts for the function definition; now we need to put
them together.
First, the contents of the while expression:
" 6 0) (89.99642944335938 481.0553283691406 449.5602111816406 630.7874755859375 "(while (<= row-number number-of-rows)
; true-or-false-test
(setq total (+ total row-number))
(setq row-number (1+ row-number)))
; incrementer
Along with the let expression varlist, this very nearly completes the body
of the function definition. However, it requires one final element, the need
for which is somewhat subtle.
The final touch is to place the variable total on a line by itself after the
while expression. Otherwise, the value returned by the whole function is
the value of the last expression that is evaluated in the body of the let, and
this is the value returned by the while, which is always nil.
This may not be evident at first sight. It almost looks as if the incre-
menting expression is the last expression of the whole function. But that
" 7 0)) (146 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "128
Chapter 11: Loops and Recursion
" 0 0) (89.99908447265625 77.48908233642578 449.3006286621094 114.66727447509766 "expression is part of the body of the while; it is the last element of the list
that starts with the symbol while. Moreover, the whole of the while loop
is a list within the body of the let.
" 1 0) (104.99940490722656 125.72907257080078 303.9484558105469 139.0272674560547 "In outline, the function will look like this:
" 2 0) (111.599365234375 154.295166015625 369.76629638671875 225.5438690185547 "(defun name-of-function (argument-list)
\"documentation...\"
(let (varlist)
(while (true-or-false-test)
body-of-while... )
... )
; Need final expression here.
" 3 0) (89.99880981445312 237.20892333984375 449.4533996582031 346.1471252441406 "The result of evaluating the let is what is going to be returned by the
defun since the let is not embedded within any containing list, except for
the defun as a whole. However, if the while is the last element of the let
expression, the function will always return nil. This is not what we want!
Instead, what we want is the value of the variable total. This is returned
by simply placing the symbol as the last element of the list starting with
let. It gets evaluated after the preceding elements of the list are evaluated,
which means it gets evaluated after it has been assigned the correct value
for the total.
" 4 0) (89.99807739257812 357.08892822265625 449.4306945800781 406.2671203613281 "It may be easier to see this by printing the list starting with let all on one
line. This format makes it evident that the varlist and while expressions are
the second and third elements of the list starting with let, and the total
is the last element:
" 5 0) (111.59806823730469 421.5350646972656 399.3865661621094 430.50384521484375 "(let (varlist) (while (true-or-false-test) body-of-while... ) total)
" 6 0) (89.9981689453125 443.1289367675781 449.24481201171875 468.4271240234375 "Putting everything together, the triangle function definition looks like
this:
" 7 0) (111.59761047363281 483.695068359375 384.2080383300781 554.8238525390625 "(defun triangle (number-of-rows)
; Version with
;
incrementing counter.
\"Add up the number of pebbles in a triangle.
The first row has one pebble, the second row two pebbles,
the third row three pebbles, and so on.
The argument is NUMBER-OF-ROWS.\"
" 8 0) (120.95764923095703 559.4175415039062 303.9436950683594 630.6638793945312 "(let ((total 0)
(row-number 1))
(while (<= row-number number-of-rows)
(setq total (+ total row-number))
(setq row-number (1+ row-number)))
total))
" 9 0)) (147 (90.0 47.60907745361328 449.5850524902344 60.90726852416992 "Example with decrementing counter
129
" 0 0) (89.99920654296875 80.00910186767578 449.3118591308594 105.30728912353516 "After you have installed triangle by evaluating the function, you can
try it out. Here are two examples:
" 1 0) (111.59920501708984 110.73764038085938 167.9413299560547 119.70402526855469 "(triangle 4)
" 2 0) (89.99905395507812 135.69772338867188 449.45343017578125 171.7872772216797 "(triangle 7)
The sum of the first four numbers is 10 and the sum of the first seven numbers
is 28.
" 3 0) (89.99905395507812 186.4818115234375 364.244873046875 199.58580017089844 "11.1.4 Loop with a Decrementing Counter
" 4 0) (89.99728393554688 208.1690673828125 449.5936584472656 369.90728759765625 "Another common way to write a while loop is to write the test so that
it determines whether a counter is greater than zero. So long as the counter
is greater than zero, the loop is repeated. But when the counter is equal to
or less than zero, the loop is stopped. For this to work, the counter has to
start out greater than zero and then be made smaller and smaller by a form
that is evaluated repeatedly.
The test will be an expression such as (> counter 0) which returns t
for true if the value of counter is greater than zero, and nil for false if the
value of counter is equal to or less than zero. The expression that makes the
number smaller and smaller can be a simple setq such as (setq counter
(1- counter)), where 1- is a built-in function in Emacs Lisp that subtracts
1 from its argument.
The template for a decrementing while loop looks like this:
" 5 0) (111.59707641601562 375.3352355957031 375.4742736816406 409.2640380859375 "(while (> counter 0)
; true-or-false-test
body...
(setq counter (1- counter)))
; decrementer
" 6 0) (89.9969482421875 423.48187255859375 323.6871337890625 436.58587646484375 "Example with decrementing counter
" 7 0) (89.99493408203125 445.16912841796875 449.4512023925781 630.787353515625 "To illustrate a loop with a decrementing counter, we will rewrite the
triangle function so the counter decreases to zero.
This is the reverse of the earlier version of the function. In this case, to
find out how many pebbles are needed to make a triangle with 3 rows, add
the number of pebbles in the third row, 3, to the number in the preceding
row, 2, and then add the total of those two rows to the row that precedes
them, which is 1.
Likewise, to find the number of pebbles in a triangle with 7 rows, add the
number of pebbles in the seventh row, 7, to the number in the preceding row,
which is 6, and then add the total of those two rows to the row that precedes
them, which is 5, and so on. As in the previous example, each addition only
involves adding two numbers, the total of the rows already added up and the
number of pebbles in the row that is being added to the total. This process
of adding two numbers is repeated again and again until there are no more
pebbles to add.
" 8 0)) (148 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "130
Chapter 11: Loops and Recursion
" 0 0) (89.99935913085938 77.48908233642578 449.4537048339844 126.66727447509766 "We know how many pebbles to start with: the number of pebbles in the
last row is equal to the number of rows. If the triangle has seven rows, the
number of pebbles in the last row is 7. Likewise, we know how many pebbles
are in the preceding row: it is one less than the number in the row.
" 1 0) (90.00039672851562 142.32183837890625 318.32550048828125 155.4258270263672 "The parts of the function definition
" 2 0) (89.99960327148438 164.24908447265625 450.0101013183594 290.7073059082031 "We start with three variables: the total number of rows in the triangle;
the number of pebbles in a row; and the total number of pebbles, which is
what we want to calculate. These variables can be named number-of-rows,
number-of-pebbles-in-row, and total, respectively.
Both total and number-of-pebbles-in-row are used only inside the
function and are declared with let. The initial value of total should, of
course, be zero. However, the initial value of number-of-pebbles-in-row
should be equal to the number of rows in the triangle, since the addition will
start with the longest row.
This means that the beginning of the let expression will look like this:
" 3 0) (89.99893188476562 296.4976501464844 449.40985107421875 369.7872619628906 "(let ((total 0)
(number-of-pebbles-in-row number-of-rows))
body...)
The total number of pebbles can be found by repeatedly adding the num-
ber of pebbles in a row to the total already found, that is, by repeatedly
evaluating the following expression:
" 4 0) (89.99795532226562 375.5776062011719 449.56256103515625 474.1871643066406 "(setq total (+ total number-of-pebbles-in-row))
After the number-of-pebbles-in-row is added to the total, the number-
of-pebbles-in-row should be decremented by one, since the next time the
loop repeats, the preceding row will be added to the total.
The number of pebbles in a preceding row is one less than the number
of pebbles in a row, so the built-in Emacs Lisp function 1- can be used to
compute the number of pebbles in the preceding row. This can be done with
the following expression:
" 5 0) (89.99722290039062 479.9775085449219 449.3976135253906 540.7872314453125 "(setq number-of-pebbles-in-row
(1- number-of-pebbles-in-row))
Finally, we know that the while loop should stop making repeated addi-
tions when there are no pebbles in a row. So the test for the while loop is
simply:
" 6 0) (111.59722137451172 546.4575805664062 285.4638366699219 555.4239501953125 "(while (> number-of-pebbles-in-row 0)
" 7 0) (89.99801635742188 571.6817016601562 346.5865173339844 584.7857055664062 "Putting the function definition together
" 8 0) (89.99832153320312 593.6090087890625 449.3216247558594 630.7872314453125 "We can put these expressions together to create a function definition that
works. However, on examination, we find that one of the local variables is
unneeded!
" 9 0)) (149 (90.0 47.60907745361328 449.5965270996094 60.90726852416992 "Save your time: dolist and dotimes
131
" 0 0) (105.00076293945312 79.52906036376953 286.83331298828125 92.8272476196289 "The function definition looks like this:
" 1 0) (89.99978637695312 97.89521026611328 449.8262634277344 347.22705078125 ";;; First subtractive version.
(defun triangle (number-of-rows)
\"Add up the number of pebbles in a triangle.\"
(let ((total 0)
(number-of-pebbles-in-row number-of-rows))
(while (> number-of-pebbles-in-row 0)
(setq total (+ total number-of-pebbles-in-row))
(setq number-of-pebbles-in-row
(1- number-of-pebbles-in-row)))
total))
As written, this function works.
However, we do not need number-of-pebbles-in-row.
When the triangle function is evaluated, the symbol number-of-rows
will be bound to a number, giving it an initial value. That number can be
changed in the body of the function as if it were a local variable, without
any fear that such a change will effect the value of the variable outside of
the function.
This is a very useful characteristic of Lisp; it means that
the variable number-of-rows can be used anywhere in the function where
number-of-pebbles-in-row is used.
Here is a second version of the function written a bit more cleanly:
" 2 0) (95.87958526611328 352.29498291015625 449.3999938964844 543.1871337890625 "(defun triangle (number)
; Second version.
\"Return sum of numbers 1 through NUMBER inclusive.\"
(let ((total 0))
(while (> number 0)
(setq total (+ total number))
(setq number (1- number)))
total))
In brief, a properly written while loop will consist of three parts:
1. A test that will return false after the loop has repeated itself the correct
number of times.
2. An expression the evaluation of which will return the value desired after
being repeatedly evaluated.
3. An expression to change the value passed to the true-or-false-test so
that the test returns false after the loop has repeated itself the right
number of times.
" 3 0) (89.99995422363281 559.460205078125 377.7007141113281 573.8334350585938 "11.2 Save your time: dolist and dotimes
" 4 0) (90.00054931640625 581.60888671875 449.3127746582031 630.787109375 "In addition to while, both dolist and dotimes provide for looping.
Sometimes these are quicker to write than the equivalent while loop. Both
are Lisp macros. (See section “Macros” in The GNU Emacs Lisp Reference
Manual. )
" 5 0)) (150 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "132
Chapter 11: Loops and Recursion
" 0 0) (89.99923706054688 77.48908233642578 449.3118896484375 128.58726501464844 "dolist works like a while loop that ‘cdrs down a list’: dolist auto-
matically shortens the list each time it loops—takes the cdr of the list—and
binds the car of each shorter version of the list to the first of its arguments.
dotimes loops a specific number of time: you specify the number.
" 1 0) (89.99917602539062 142.081787109375 206.38824462890625 155.1973419189453 "The dolist Macro
" 2 0) (89.99874877929688 163.1690673828125 449.2789611816406 202.5072479248047 "Suppose, for example, you want to reverse a list, so that “first” “second”
“third” becomes “third” “second” “first”.
In practice, you would use the reverse function, like this:
" 3 0) (111.59822082519531 207.57760620117188 318.18182373046875 216.5439910888672 "(setq animals ’(gazelle giraffe lion tiger))
" 4 0) (89.99861145019531 232.41751098632812 365.4090576171875 257.1071472167969 "(reverse animals)
Here is how you could reverse the list using a while loop:
" 5 0) (111.59814453125 262.0575256347656 318.1817626953125 271.0238952636719 "(setq animals ’(gazelle giraffe lion tiger))
" 6 0) (111.59855651855469 287.0175476074219 323.0157165527344 370.7439270019531 "(defun reverse-list-with-while (list)
\"Using while, reverse the order of LIST.\"
(let (value)
; make sure list starts empty
(while list
(setq value (cons (car list) value))
(setq list (cdr list)))
value))
" 7 0) (89.99896240234375 386.6174621582031 328.3076477050781 411.3070983886719 "(reverse-list-with-while animals)
And here is how you could use the dolist macro:
" 8 0) (111.59846496582031 416.2574462890625 318.18206787109375 425.22381591796875 "(setq animals ’(gazelle giraffe lion tiger))
" 9 0) (111.59886169433594 441.2174377441406 323.01763916015625 499.98382568359375 "(defun reverse-list-with-dolist (list)
\"Using dolist, reverse the order of LIST.\"
(let (value)
; make sure list starts empty
(dolist (element list value)
(setq value (cons element value)))))
" 10 0) (90.000732421875 515.8574829101562 449.23663330078125 552.555908203125 "(reverse-list-with-dolist animals)
In Info, you can place your cursor after the closing parenthesis of each ex-
pression and type C-x C-e; in each case, you should see
" 11 0) (90.00082397460938 557.4974975585938 449.4011535644531 630.787109375 "(tiger lion giraffe gazelle)
in the echo area.
For this example, the existing reverse function is obviously best. The
while loop is just like our first example (see Section 11.1.1, “A while Loop
and a List”, page 122). The while first checks whether the list has elements;
if so, it constructs a new list by adding the first element of the list to the
" 12 0)) (151 (90.0 47.60907745361328 449.7485656738281 60.90726852416992 "The dotimes Macro
133
" 0 0) (89.99954223632812 77.48908233642578 449.464599609375 346.3872375488281 "existing list (which in the first iteration of the loop is nil). Since the second
element is prepended in front of the first element, and the third element is
prepended in front of the second element, the list is reversed.
In the expression using a while loop, the (setq list (cdr list)) ex-
pression shortens the list, so the while loop eventually stops. In addition,
it provides the cons expression with a new first element by creating a new
and shorter list at each repetition of the loop.
The dolist expression does very much the same as the while expression,
except that the dolist macro does some of the work you have to do when
writing a while expression.
Like a while loop, a dolist loops. What is different is that it automat-
ically shortens the list each time it loops — it ‘cdrs down the list’ on its
own — and it automatically binds the car of each shorter version of the list
to the first of its arguments.
In the example, the car of each shorter version of the list is referred
to using the symbol ‘element’, the list itself is called ‘list’, and the value
returned is called ‘value’. The remainder of the dolist expression is the
body.
The dolist expression binds the car of each shorter version of the list
to element and then evaluates the body of the expression; and repeats the
loop. The result is returned in value.
" 1 0) (89.99913024902344 363.7218017578125 213.1038818359375 376.8373718261719 "The dotimes Macro
" 2 0) (89.99871826171875 386.2490539550781 449.4753723144531 525.7871704101562 "The dotimes macro is similar to dolist, except that it loops a specific
number of times.
The first argument to dotimes is assigned the numbers 0, 1, 2 and so
forth each time around the loop, and the value of the third argument is
returned. You need to provide the value of the second argument, which is
how many times the macro loops.
For example, the following binds the numbers from 0 up to, but not
including, the number 3 to the first argument, number, and then constructs
a list of the three numbers. (The first number is 0, the second number is
1, and the third number is 2; this makes a total of three numbers in all,
starting with zero as the first number.)
" 3 0) (111.599365234375 532.0575561523438 374.6771545410156 565.98388671875 "(let (value)
; otherwise a value is a void variable
(dotimes (number 3 value)
(setq value (cons number value))))
" 4 0) (89.99945068359375 581.0130615234375 449.43194580078125 630.7872314453125 "⇒ (2 1 0)
dotimes returns value, so the way to use dotimes is to operate on some
expression number number of times and then return the result, either as a
list or an atom.
" 5 0)) (152 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "134
Chapter 11: Loops and Recursion
" 0 0) (89.9996337890625 79.76905059814453 449.4971008300781 105.0672378540039 "Here is an example of a defun that uses dotimes to add up the number
of pebbles in a triangle.
" 1 0) (111.59959411621094 110.25759887695312 402.81005859375 169.02391052246094 "(defun triangle-using-dotimes (number-of-rows)
\"Using dotimes, add up the number of pebbles in a triangle.\"
(let ((total 0))
; otherwise a total is a void variable
(dotimes (number number-of-rows total)
(setq total (+ total (1+ number))))))
" 2 0) (111.60026550292969 184.89755249023438 233.70309448242188 193.8639373779297 "(triangle-using-dotimes 4)
" 3 0) (90.00025939941406 210.62030029296875 196.5753173828125 224.9808349609375 "11.3 Recursion
" 4 0) (89.99917602539062 232.8890380859375 449.3672790527344 332.1072082519531 "A recursive function contains code that tells the Lisp interpreter to call a
program that runs exactly like itself, but with slightly different arguments.
The code runs exactly the same because it has the same name. However,
even though it has the same name, it is not the same thread of execution.
It is different. In the jargon, it is a different ‘instance’.
Eventually, if the program is written correctly, the ‘slightly different ar-
guments’ will become sufficiently different from the first arguments that the
final instance will stop.
" 5 0) (89.9995346069336 346.0817565917969 411.239501953125 359.1857604980469 "11.3.1 Building Robots: Extending the Metaphor
" 6 0) (89.9945068359375 367.40899658203125 449.41986083984375 630.7872314453125 "It is sometimes helpful to think of a running program as a robot that does
a job. In doing its job, a recursive function calls on a second robot to help
it. The second robot is identical to the first in every way, except that the
second robot helps the first and has been passed different arguments than
the first.
In a recursive function, the second robot may call a third; and the third
may call a fourth, and so on. Each of these is a different entity; but all are
clones.
Since each robot has slightly different instructions—the arguments will
differ from one robot to the next—the last robot should know when to stop.
Let’s expand on the metaphor in which a computer program is a robot.
A function definition provides the blueprints for a robot. When you install
a function definition, that is, when you evaluate a defun special form, you
install the necessary equipment to build robots. It is as if you were in a
factory, setting up an assembly line. Robots with the same name are built
according to the same blueprints. So they have, as it were, the same ‘model
number’, but a different ‘serial number’.
We often say that a recursive function ‘calls itself’. What we mean is
that the instructions in a recursive function cause the Lisp interpreter to
run a different function that has the same name and does the same job as
the first, but with different arguments.
" 7 0)) (153 (90.0 47.60907745361328 449.7159423828125 60.90726852416992 "Recursion with a List
135
" 0 0) (89.9986572265625 77.48908233642578 449.39874267578125 102.66727447509766 "It is important that the arguments differ from one instance to the next;
otherwise, the process will never stop.
" 1 0) (89.99916076660156 119.5218505859375 363.9984436035156 132.62583923339844 "11.3.2 The Parts of a Recursive Definition
" 2 0) (89.99972534179688 141.9290771484375 449.4326477050781 299.1073303222656 "A recursive function typically contains a conditional expression which has
three parts:
1. A true-or-false-test that determines whether the function is called again,
here called the do-again-test.
2. The name of the function. When this name is called, a new instance of
the function—a new robot, as it were—is created and told what to do.
3. An expression that returns a different value each time the function is
called, here called the next-step-expression.
Consequently, the argu-
ment (or arguments) passed to the new instance of the function will
be different from that passed to the previous instance. This causes the
conditional expression, the do-again-test, to test false after the correct
number of repetitions.
" 3 0) (89.99984741210938 305.129150390625 449.4219665527344 393.4273376464844 "Recursive functions can be much simpler than any other kind of function.
Indeed, when people first start to use them, they often look so mysteriously
simple as to be incomprehensible. Like riding a bicycle, reading a recursive
function definition takes a certain knack which is hard at first but then seems
simple.
There are several different common recursive patterns. A very simple
pattern looks like this:
" 4 0) (89.99853515625 399.5752868652344 449.387451171875 630.787353515625 "(defun name-of-recursive-function (argument-list)
\"documentation...\"
(if do-again-test
body...
(name-of-recursive-function
next-step-expression)))
Each time a recursive function is evaluated, a new instance of it is created
and told what to do. The arguments tell the instance what to do.
An argument is bound to the value of the next-step-expression. Each
instance runs with a different value of the next-step-expression.
The value in the next-step-expression is used in the do-again-test.
The value returned by the next-step-expression is passed to the new in-
stance of the function, which evaluates it (or some transmogrification of it)
to determine whether to continue or stop. The next-step-expression is de-
signed so that the do-again-test returns false when the function should no
longer be repeated.
The do-again-test is sometimes called the stop condition, since it stops
the repetitions when it tests false.
" 5 0)) (154 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "136
Chapter 11: Loops and Recursion
" 0 0) (89.9993896484375 78.2418212890625 273.6626281738281 91.34580993652344 "11.3.3 Recursion with a List
" 1 0) (89.99676513671875 101.36908721923828 449.4533996582031 269.9473571777344 "The example of a while loop that printed the elements of a list of numbers
can be written recursively. Here is the code, including an expression to set
the value of the variable animals to a list.
If you are using Emacs 20 or before, this example must be copied to the
‘*scratch*’ buffer and each expression must be evaluated there. Use C-u C-
x C-e to evaluate the (print-elements-recursively animals) expression
so that the results are printed in the buffer; otherwise the Lisp interpreter
will try to squeeze the results into the one line of the echo area.
Also, place your cursor immediately after the last closing parenthesis of
the print-elements-recursively function, before the comment. Other-
wise, the Lisp interpreter will try to evaluate the comment.
If you are using Emacs 21 or later, you can evaluate this expression
directly in Info.
" 2 0) (111.5966796875 276.9377136230469 318.1802978515625 285.9040832519531 "(setq animals ’(gazelle giraffe lion tiger))
" 3 0) (111.59652709960938 301.8977355957031 390.83935546875 397.9841003417969 "(defun print-elements-recursively (list)
\"Print each element of LIST on a line of its own.
Uses recursion.\"
(if list
; do-again-test
(progn
(print (car list))
; body
(print-elements-recursively
; recursive call
(cdr list)))))
; next-step-expression
" 4 0) (89.99456787109375 413.97784423828125 449.4491882324219 630.7874755859375 "(print-elements-recursively animals)
The print-elements-recursively function first tests whether there is
any content in the list; if there is, the function prints the first element of the
list, the car of the list. Then the function ‘invokes itself’, but gives itself as
its argument, not the whole list, but the second and subsequent elements of
the list, the cdr of the list.
Put another way, if the list is not empty, the function invokes another
instance of code that is similar to the initial code, but is a different thread
of execution, with different arguments than the first instance.
Put in yet another way, if the list is not empty, the first robot assemblies a
second robot and tells it what to do; the second robot is a different individual
from the first, but is the same model.
When the second evaluation occurs, the if expression is evaluated and if
true, prints the first element of the list it receives as its argument (which is
the second element of the original list). Then the function ‘calls itself’ with
the cdr of the list it is invoked with, which (the second time around) is the
cdr of the cdr of the original list.
" 5 0)) (155 (90.0 47.60907745361328 449.628662109375 60.90726852416992 "Recursion in Place of a Counter
137
" 0 0) (89.99838256835938 77.48908233642578 449.45318603515625 216.42723083496094 "Note that although we say that the function ‘calls itself’, what we mean
is that the Lisp interpreter assembles and instructs a new instance of the
program. The new instance is a clone of the first, but is a separate individual.
Each time the function ‘invokes itself’, it invokes itself on a shorter version
of the original list. It creates a new instance that works on a shorter list.
Eventually, the function invokes itself on an empty list. It creates a new
instance whose argument is nil. The conditional expression tests the value
of list. Since the value of list is nil, the if expression tests false so the
then-part is not evaluated. The function as a whole then returns nil.
When you evaluate (print-elements-recursively animals) in the
‘*scratch*’ buffer, you see this result:
" 1 0) (111.59873962402344 221.37759399414062 144.33499145507812 230.34397888183594 "giraffe
" 2 0) (111.59873962402344 246.33761596679688 144.33499145507812 255.3040008544922 "gazelle
" 3 0) (111.59873962402344 271.1776428222656 130.32054138183594 280.1440124511719 "lion
" 4 0) (111.59873962402344 296.1376647949219 134.99203491210938 317.5840148925781 "tiger
nil
" 5 0) (89.99874114990234 330.0018615722656 341.5819396972656 343.1058654785156 "11.3.4 Recursion in Place of a Counter
" 6 0) (89.99822998046875 351.2091064453125 449.2782287597656 376.5072937011719 "The triangle function described in a previous section can also be written
recursively. It looks like this:
" 7 0) (111.59823608398438 381.4576416015625 393.33697509765625 477.6641845703125 "(defun triangle-recursively (number)
\"Return the sum of the numbers 1 through NUMBER inclusive.
Uses recursion.\"
(if (= number 1)
; do-again-test
1
; then-part
(+ number
; else-part
(triangle-recursively
; recursive call
(1- number)))))
; next-step-expression
" 8 0) (89.99560546875 493.5378112792969 449.4173583984375 630.7874755859375 "(triangle-recursively 7)
You can install this function by evaluating it and then try it by evaluating
(triangle-recursively 7). (Remember to put your cursor immediately
after the last parenthesis of the function definition, before the comment.)
The function evaluates to 28.
To understand how this function works, let’s consider what happens in
the various cases when the function is passed 1, 2, 3, or 4 as the value of its
argument.
First, what happens if the value of the argument is 1?
The function has an if expression after the documentation string. It
tests whether the value of number is equal to 1; if so, Emacs evaluates the
" 9 0)) (156 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "138
Chapter 11: Loops and Recursion
" 0 0) (89.99923706054688 77.48908233642578 449.5621643066406 154.6272430419922 "then-part of the if expression, which returns the number 1 as the value of
the function. (A triangle with one row has one pebble in it.)
Suppose, however, that the value of the argument is 2.
In this case,
Emacs evaluates the else-part of the if expression.
The else-part consists of an addition, the recursive call to triangle-
recursively and a decrementing action; and it looks like this:
" 1 0) (89.99948120117188 159.57760620117188 449.24639892578125 194.94725036621094 "(+ number (triangle-recursively (1- number)))
When Emacs evaluates this expression, the innermost expression is eval-
uated first; then the other parts in sequence. Here are the steps in detail:
" 2 0) (89.99887084960938 199.529052734375 449.3108215332031 236.70726013183594 "Step 1
Evaluate the innermost expression.
The innermost expression is (1- number) so Emacs decrements
the value of number from 2 to 1.
" 3 0) (89.99850463867188 241.2890625 449.6722412109375 341.2272644042969 "Step 2
Evaluate the triangle-recursively function.
The Lisp interpreter creates an individual instance of triangle-
recursively. It does not matter that this function is contained
within itself. Emacs passes the result Step 1 as the argument
used by this instance of the triangle-recursively function
In this case, Emacs evaluates triangle-recursively with an
argument of 1. This means that this evaluation of triangle-
recursively returns 1.
" 4 0) (89.99891662597656 345.80908203125 449.39892578125 382.9872741699219 "Step 3
Evaluate the value of number.
The variable number is the second element of the list that starts
with +; its value is 2.
" 5 0) (89.99952697753906 387.569091796875 449.5302429199219 475.5072937011719 "Step 4
Evaluate the + expression.
The + expression receives two arguments, the first from the eval-
uation of number (Step 3) and the second from the evaluation
of triangle-recursively (Step 2).
The result of the addition is the sum of 2 plus 1, and the number
3 is returned, which is correct. A triangle with two rows has
three pebbles in it.
" 6 0) (89.99984741210938 488.8818664550781 234.927001953125 501.9858703613281 "An argument of 3 or 4
" 7 0) (104.99982452392578 509.9691162109375 440.5414123535156 523.267333984375 "Suppose that triangle-recursively is called with an argument of 3.
" 8 0) (89.99960327148438 527.84912109375 449.4755859375 589.02734375 "Step 1
Evaluate the do-again-test.
The if expression is evaluated first. This is the do-again test and
returns false, so the else-part of the if expression is evaluated.
(Note that in this example, the do-again-test causes the function
to call itself when it tests false, not when it tests true.)
" 9 0) (89.99935913085938 593.609130859375 449.37762451171875 630.787353515625 "Step 2
Evaluate the innermost expression of the else-part.
The innermost expression of the else-part is evaluated, which
decrements 3 to 2. This is the next-step-expression.
" 10 0)) (157 (90.0 47.60907745361328 449.6395568847656 60.90726852416992 "Recursion Example Using cond
139
" 0 0) (89.99978637695312 77.48908233642578 449.73797607421875 153.0673065185547 "Step 3
Evaluate the triangle-recursively function.
The number 2 is passed to the triangle-recursively function.
We know what happens when Emacs evaluates triangle-
recursively with an argument of 2. After going through the
sequence of actions described earlier, it returns a value of 3. So
that is what will happen here.
" 1 0) (89.99909973144531 156.9290771484375 449.6606140136719 206.10728454589844 "Step 4
Evaluate the addition.
3 will be passed as an argument to the addition and will be
added to the number with which the function was called, which
is 3.
" 2 0) (89.99915313720703 209.24908447265625 449.4094543457031 274.6273498535156 "The value returned by the function as a whole will be 6.
Now that we know what will happen when triangle-recursively is
called with an argument of 3, it is evident what will happen if it is called
with an argument of 4:
In the recursive call, the evaluation of
" 3 0) (111.59822082519531 279.6977233886719 273.3363342285156 303.3073425292969 "(triangle-recursively (1- 4))
will return the value of evaluating
" 4 0) (89.99691772460938 308.3777160644531 449.4413757324219 571.8675537109375 "(triangle-recursively 3)
which is 6 and this value will be added to 4 by the addition in the
third line.
The value returned by the function as a whole will be 10.
Each time triangle-recursively is evaluated, it evaluates a version
of itself—a different instance of itself—with a smaller argument, until the
argument is small enough so that it does not evaluate itself.
Note that this particular design for a recursive function requires that
operations be deferred.
Before (triangle-recursively 7) can calculate its answer, it must call
(triangle-recursively 6); and before (triangle-recursively 6) can
calculate its answer, it must call (triangle-recursively 5); and so on.
That is to say, the calculation that (triangle-recursively 7) makes must
be deferred until (triangle-recursively 6) makes its calculation; and
(triangle-recursively 6) must defer until (triangle-recursively 5)
completes; and so on.
If each of these instances of triangle-recursively are thought of as
different robots, the first robot must wait for the second to complete its job,
which must wait until the third completes, and so on.
There is a way around this kind of waiting, which we will discuss in
Section 11.3.7, “Recursion without Deferments”, page 143.
" 5 0) (89.99859619140625 584.4020385742188 332.9549255371094 597.517578125 "11.3.5 Recursion Example Using cond
" 6 0) (89.99822998046875 605.4893188476562 449.2889709472656 630.7875366210938 "The version of triangle-recursively described earlier is written with
the if special form. It can also be written using another special form called
" 7 0)) (158 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "140
Chapter 11: Loops and Recursion
" 0 0) (89.9993896484375 77.48908233642578 449.46435546875 145.0272674560547 "cond. The name of the special form cond is an abbreviation of the word
‘conditional’.
Although the cond special form is not used as often in the Emacs Lisp
sources as if, it is used often enough to justify explaining it.
The template for a cond expression looks like this:
" 1 0) (90.00009155273438 151.17758178710938 351.6325378417969 203.7071990966797 "(cond
body...)
where the body is a series of lists.
Written out more fully, the template looks like this:
" 2 0) (89.99929809570312 209.85751342773438 449.4210205078125 449.5870666503906 "(cond
(first-true-or-false-test first-consequent)
(second-true-or-false-test second-consequent)
(third-true-or-false-test third-consequent)
...)
When the Lisp interpreter evaluates the cond expression, it evaluates the
first element (the car or true-or-false-test) of the first expression in a series
of expressions within the body of the cond.
If the true-or-false-test returns nil the rest of that expression, the con-
sequent, is skipped and the true-or-false-test of the next expression is eval-
uated. When an expression is found whose true-or-false-test returns a value
that is not nil, the consequent of that expression is evaluated. The conse-
quent can be one or more expressions. If the consequent consists of more
than one expression, the expressions are evaluated in sequence and the value
of the last one is returned. If the expression does not have a consequent, the
value of the true-or-false-test is returned.
If none of the true-or-false-tests test true, the cond expression returns
nil.
Written using cond, the triangle function looks like this:
" 3 0) (89.9990234375 455.7374267578125 449.7041320800781 554.3471069335938 "(defun triangle-using-cond (number)
(cond ((<= number 0) 0)
((= number 1) 1)
((> number 1)
(+ number (triangle-using-cond (1- number))))))
In this example, the cond returns 0 if the number is less than or equal to
0, it returns 1 if the number is 1 and it evaluates (+ number (triangle-
using-cond (1- number))) if the number is greater than 1.
" 4 0) (89.9989013671875 571.2015991210938 257.3028564453125 584.3056030273438 "11.3.6 Recursive Patterns
" 5 0) (89.9986572265625 593.60888671875 449.2678527832031 630.787109375 "Here are three common recursive patterns. Each involves a list. Recursion
does not need to involve lists, but Lisp is designed for lists and this provides
a sense of its primal capabilities.
" 6 0)) (159 (90.0 47.60907745361328 449.6722412109375 60.90726852416992 "Recursive Pattern: every
141
" 0 0) (89.99948120117188 78.18191528320312 252.61074829101562 91.34580993652344 "Recursive Pattern: every
" 1 0) (89.99978637695312 106.88910675048828 449.159423828125 132.1873016357422 "In the every recursive pattern, an action is performed on every element
of a list.
" 2 0) (104.99982452392578 140.36907958984375 203.72694396972656 153.6672821044922 "The basic pattern is:
" 3 0) (98.99972534179688 162.80908203125 253.55955505371094 183.8527374267578 "• If a list be empty, return nil.
" 4 0) (98.99983215332031 185.24908447265625 385.3194274902344 206.29273986816406 "• Else, act on the beginning of the list (the car of the list)
" 5 0) (117.47940063476562 207.6890869140625 449.3990783691406 232.98728942871094 "− through a recursive call by the function on the rest (the cdr) of
the list,
" 6 0) (117.47989654541016 242.12908935546875 449.3452453613281 267.3072814941406 "− and, optionally, combine the acted-on element, using cons, with
the results of acting on the rest.
" 7 0) (104.99940490722656 286.049072265625 183.61032104492188 299.3472595214844 "Here is example:
" 8 0) (111.59941101074219 311.8576354980469 407.21514892578125 395.58404541015625 "(defun square-each (numbers-list)
\"Square each of a NUMBERS LIST, recursively.\"
(if (not numbers-list)
; do-again-test
nil
(cons
(* (car numbers-list) (car numbers-list))
(square-each (cdr numbers-list))))) ; next-step-expression
" 9 0) (111.5997314453125 403.6576843261719 214.91368103027344 430.849853515625 "(square-each ’(1 2 3))
⇒ (1 4 9)
" 10 0) (89.99971771240234 434.9691467285156 449.3998107910156 472.1473388671875 "If numbers-list is empty, do nothing. But if it has content, construct a list
combining the square of the first number in the list with the result of the
recursive call.
" 11 0) (89.999755859375 480.32916259765625 449.4867248535156 517.5073852539062 "(The example follows the pattern exactly: nil is returned if the numbers’
list is empty. In practice, you would write the conditional so it carries out
the action when the numbers’ list is not empty.)
" 12 0) (89.99844360351562 525.689208984375 449.2569885253906 574.867431640625 "The print-elements-recursively function (see Section 11.3.3, “Recur-
sion with a List”, page 136) is another example of an every pattern, except
in this case, rather than bring the results together using cons, we print each
element of output.
" 13 0) (104.99842834472656 583.0491943359375 390.6851806640625 596.347412109375 "The print-elements-recursively function looks like this:
" 14 0) (111.59808349609375 608.8577270507812 318.18170166015625 617.8240966796875 "(setq animals ’(gazelle giraffe lion tiger))
" 15 0)) (160 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "142
Chapter 11: Loops and Recursion
" 0 0) (111.59884643554688 81.33761596679688 390.8416748046875 177.4238739013672 "(defun print-elements-recursively (list)
\"Print each element of LIST on a line of its own.
Uses recursion.\"
(if list
; do-again-test
(progn
(print (car list))
; body
(print-elements-recursively
; recursive call
(cdr list)))))
; next-step-expression
" 1 0) (98.99717712402344 193.41751098632812 411.8258361816406 291.0127258300781 "(print-elements-recursively animals)
The pattern for print-elements-recursively is:
• If the list be empty, do nothing.
• But if the list has at least one element,
− act on the beginning of the list (the car of the list),
− and make a recursive call on the rest (the cdr) of the list.
" 2 0) (89.99673461914062 299.8219909667969 291.0596923828125 312.98590087890625 "Recursive Pattern: accumulate
" 3 0) (89.99578857421875 322.0491638183594 449.4500427246094 497.17279052734375 "Another recursive pattern is called the accumulate pattern.
In the
accumulate recursive pattern, an action is performed on every element of a
list and the result of that action is accumulated with the results of perform-
ing the action on the other elements.
This is very like the ‘every’ pattern using cons, except that cons is not
used, but some other combiner.
The pattern is:
• If a list be empty, return zero or some other constant.
• Else, act on the beginning of the list (the car of the list),
− and combine that acted-on element, using + or some other combin-
ing function, with
− a recursive call by the function on the rest (the cdr) of the list.
" 4 0) (104.99554443359375 495.3291320800781 198.7045440673828 508.6273193359375 "Here is an example:
" 5 0) (111.59553527832031 514.65771484375 402.5395812988281 573.424072265625 "(defun add-elements (numbers-list)
\"Add the elements of NUMBERS-LIST together.\"
(if (not numbers-list)
0
(+ (car numbers-list) (add-elements (cdr numbers-list)))))
" 6 0) (89.9951171875 581.6177368164062 449.32940673828125 630.7874145507812 "(add-elements ’(1 2 3 4))
⇒ 10
See Section 14.9.2, “Making a List of Files”, page 194, for an example of
the accumulate pattern.
" 7 0)) (161 (90.0 47.60907745361328 449.62884521484375 60.90726852416992 "Recursion without Deferments
143
" 0 0) (90.00009155273438 78.18191528320312 245.68148803710938 91.34580993652344 "Recursive Pattern: keep
" 1 0) (90.00018310546875 101.00910186767578 449.3999938964844 181.3872528076172 "A third recursive pattern is called the keep pattern. In the keep recursive
pattern, each element of a list is tested; the element is acted on and the
results are kept only if the element meets a criterion.
Again, this is very like the ‘every’ pattern, except the element is skipped
unless it meets a criterion.
The pattern has three parts:
" 2 0) (98.9996566772461 184.6490478515625 253.5594940185547 205.6927032470703 "• If a list be empty, return nil.
" 3 0) (98.99977111816406 201.08905029296875 425.1919250488281 222.13270568847656 "• Else, if the beginning of the list (the car of the list) passes a test
" 4 0) (117.48001098632812 217.6490478515625 384.2071533203125 238.6927032470703 "− act on that element and combine it, using cons with
" 5 0) (117.48040771484375 234.20904541015625 438.6436767578125 255.25270080566406 "− a recursive call by the function on the rest (the cdr) of the list.
" 6 0) (99.00057983398438 250.76904296875 449.2471008300781 271.8127136230469 "• Otherwise, if the beginning of the list (the car of the list) fails the test
" 7 0) (117.48019409179688 267.32916259765625 234.076416015625 288.3728332519531 "− skip on that element,
" 8 0) (117.48059844970703 283.88916015625 447.49114990234375 304.9328308105469 "− and, recursively call the function on the rest (the cdr) of the list.
" 9 0) (105.00106811523438 304.04913330078125 272.13897705078125 317.3473205566406 "Here is an example that uses cond:
" 10 0) (111.60125732421875 323.9776611328125 308.6962890625 382.7440490722656 "(defun keep-three-letter-words (word-list)
\"Keep three letter words in WORD-LIST.\"
(cond
;; First do-again-test: stop-condition
((not word-list) nil)
" 11 0) (125.76116943359375 398.7376708984375 435.6067199707031 445.0240478515625 ";; Second do-again-test: when to act
((eq 3 (length (symbol-name (car word-list))))
;; combine acted-on element with recursive call on shorter list
(cons (car word-list) (keep-three-letter-words (cdr word-list))))
" 12 0) (125.76197814941406 461.0176696777344 407.4836120605469 494.82403564453125 ";; Third do-again-test: when to skip element;
;;
recursively call shorter list with next-step expression
(t
(keep-three-letter-words (cdr word-list)))))
" 13 0) (90.00296020507812 503.0176696777344 449.32659912109375 552.6673583984375 "(keep-three-letter-words ’(one two three four five six))
⇒ (one two six)
It goes without saying that you need not use nil as the test for when to
stop; and you can, of course, combine these patterns.
" 14 0) (90.00303649902344 570.8418579101562 331.9056091308594 583.9458618164062 "11.3.7 Recursion without Deferments
" 15 0) (90.00335693359375 593.609130859375 449.50146484375 630.787353515625 "Let’s consider again what happens with the triangle-recursively func-
tion. We will find that the intermediate calculations are deferred until all
can be done.
" 16 0)) (162 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "144
Chapter 11: Loops and Recursion
" 0 0) (104.9993896484375 82.04907989501953 250.7883758544922 95.3472671508789 "Here is the function definition:
" 1 0) (111.5993881225586 102.81759643554688 393.338134765625 198.9038543701172 "(defun triangle-recursively (number)
\"Return the sum of the numbers 1 through NUMBER inclusive.
Uses recursion.\"
(if (= number 1)
; do-again-test
1
; then-part
(+ number
; else-part
(triangle-recursively
; recursive call
(1- number)))))
; next-step-expression
" 2 0) (104.99867248535156 202.7689208984375 412.13275146484375 216.06712341308594 "What happens when we call this function with a argument of 7?
" 3 0) (89.99819946289062 219.20892333984375 449.96551513671875 268.3871154785156 "The first instance of the triangle-recursively function adds the num-
ber 7 to the value returned by a second instance of triangle-recursively,
an instance that has been passed an argument of 6. That is to say, the first
calculation is:
" 4 0) (111.59820556640625 275.8574523925781 247.8523712158203 284.8238220214844 "(+ 7 (triangle-recursively 6)
" 5 0) (89.99838256835938 288.44891357421875 449.48583984375 373.5071105957031 "The first instance of triangle-recursively—you may want to think of it
as a little robot—cannot complete its job. It must hand off the calculation
for (triangle-recursively 6) to a second instance of the program, to a
second robot. This second individual is completely different from the first
one; it is, in the jargon, a ‘different instantiation’. Or, put another way, it
is a different robot. It is the same model as the first; it calculates triangle
numbers recursively; but it has a different serial number.
" 6 0) (89.99810791015625 376.64892578125 449.93231201171875 425.8271179199219 "And what does (triangle-recursively 6) return? It returns the num-
ber 6 added to the value returned by evaluating triangle-recursively
with an argument of 5. Using the robot metaphor, it asks yet another robot
to help it.
" 7 0) (104.99850463867188 429.08892822265625 184.80931091308594 442.3871154785156 "Now the total is:
" 8 0) (111.59849548339844 449.85748291015625 257.3240966796875 458.8238525390625 "(+ 7 6 (triangle-recursively 5)
" 9 0) (104.99826049804688 462.4489440917969 224.7907257080078 475.74713134765625 "And what happens next?
" 10 0) (111.59805297851562 483.2174987792969 266.6750793457031 492.1838684082031 "(+ 7 6 5 (triangle-recursively 4)
" 11 0) (89.99777221679688 495.8089599609375 449.2889709472656 533.107177734375 "Each time triangle-recursively is called, except for the last time,
it creates another instance of the program—another robot—and asks it to
make a calculation.
" 12 0) (104.9978256225586 536.2489624023438 358.9394226074219 549.5471801757812 "Eventually, the full addition is set up and performed:
" 13 0) (111.59796142578125 557.0175170898438 191.46832275390625 565.98388671875 "(+ 7 6 5 4 3 2 1)
" 14 0) (89.99649047851562 569.6090087890625 449.4405212402344 630.7872314453125 "This design for the function defers the calculation of the first step until
the second can be done, and defers that until the third can be done, and
so on. Each deferment means the computer must remember what is being
waited on. This is not a problem when there are only a few steps, as in this
example. But it can be a problem when there are more steps.
" 15 0)) (163 (90.0 47.60907745361328 449.70574951171875 60.90726852416992 "No Deferment Solution
145
" 0 0) (90.0 78.2418212890625 284.39776611328125 91.34580993652344 "11.3.8 No Deferment Solution
" 1 0) (89.9984130859375 101.12909698486328 449.61712646484375 205.74729919433594 "The solution to the problem of deferred operations is to write in a manner
that does not defer operations2. This requires writing to a different pattern,
often one that involves writing two function definitions, an ‘initialization’
function and a ‘helper’ function.
The ‘initialization’ function sets up the job; the ‘helper’ function does the
work.
Here are the two function definitions for adding up numbers. They are
so simple, I find them hard to understand.
" 2 0) (111.59779357910156 212.61764526367188 393.33648681640625 271.3839416503906 "(defun triangle-initialization (number)
\"Return the sum of the numbers 1 through NUMBER inclusive.
This is the ‘initialization’ component of a two function
duo that uses recursion.\"
(triangle-recursive-helper 0 0 number))
" 3 0) (111.59840393066406 279.5776672363281 377.4187316894531 388.2640075683594 "(defun triangle-recursive-helper (sum counter number)
\"Return SUM, using COUNTER, through NUMBER inclusive.
This is the ‘helper’ component of a two function duo
that uses recursion.\"
(if (> counter number)
sum
(triangle-recursive-helper (+ sum counter)
; sum
(1+ counter)
; counter
number)))
; number
" 4 0) (89.99703979492188 392.3691101074219 449.5279846191406 417.66729736328125 "Install both function definitions by evaluating them, then call triangle-
initialization with 2 rows:
" 5 0) (89.99713134765625 424.41766357421875 450.02947998046875 525.787353515625 "(triangle-initialization 2)
⇒ 3
The ‘initialization’ function calls the first instance of the ‘helper’ function
with three arguments: zero, zero, and a number which is the number of rows
in the triangle.
The first two arguments passed to the ‘helper’ function are initializa-
tion values. These values are changed when triangle-recursive-helper
invokes new instances.3
" 6 0) (89.98799896240234 539.1519775390625 233.98800659179688 539.6319580078125 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (95.87972259521484 540.09521484375 449.8048400878906 630.3015747070312 "2 The phrase tail recursive is used to describe such a process, one that uses ‘constant
space’.
3 The jargon is mildly confusing: triangle-recursive-helper uses a process that is
iterative in a procedure that is recursive. The process is called iterative because the
computer need only record the three values, sum, counter, and number; the procedure
is recursive because the function ‘calls itself’. On the other hand, both the process
and the procedure used by triangle-recursively are called recursive.
The word
‘recursive’ has different meanings in the two contexts.
" 8 0)) (164 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "146
Chapter 11: Loops and Recursion
" 0 0) (89.9993896484375 77.48908233642578 449.38818359375 130.1472625732422 "Let’s see what happens when we have a triangle that has one row. (This
triangle will have one pebble in it!)
triangle-initialization will call its helper with the arguments 0 0 1.
That function will run the conditional test whether (> counter number):
" 1 0) (89.99911499023438 136.65762329101562 449.4424743652344 173.46726989746094 "(> 0 1)
and find that the result is false, so it will invoke the then-part of the if
clause:
" 2 0) (130.43911743164062 179.97763061523438 346.1848449707031 226.2639617919922 "(triangle-recursive-helper
(+ sum counter)
; sum plus counter ⇒ sum
(1+ counter)
; increment counter ⇒ counter
number)
; number stays the same
" 3 0) (89.999267578125 230.1290283203125 207.6537322998047 243.42723083496094 "which will first compute:
" 4 0) (89.99832153320312 249.8150634765625 321.07952880859375 293.5813903808594 "(triangle-recursive-helper (+ 0 0)
; sum
(1+ 0)
; counter
1)
; number
which is:
" 5 0) (89.99813842773438 305.8573913574219 449.31048583984375 370.38702392578125 "(triangle-recursive-helper 0 1 1)
Again, (> counter number) will be false, so again, the Lisp interpreter
will evaluate triangle-recursive-helper, creating a new instance with
new arguments.
This new instance will be;
" 6 0) (130.43798828125 376.7773742675781 346.1836853027344 423.0637512207031 "(triangle-recursive-helper
(+ sum counter)
; sum plus counter ⇒ sum
(1+ counter)
; increment counter ⇒ counter
number)
; number stays the same
" 7 0) (89.99810791015625 436.41497802734375 125.05845642089844 445.3813781738281 "which is:
" 8 0) (89.99749755859375 457.6573791503906 449.4193420410156 553.027099609375 "(triangle-recursive-helper 1 2 1)
In this case, the (> counter number) test will be true! So the instance
will return the value of the sum, which will be 1, as expected.
Now, let’s pass triangle-initialization an argument of 2, to find out
how many pebbles there are in a triangle with two rows.
That function calls (triangle-recursive-helper 0 0 2).
In stages, the instances called will be:
" 9 0) (111.59709167480469 559.4149780273438 317.1062927246094 580.86376953125 "sum counter number
(triangle-recursive-helper 0
1
2)
" 10 0) (111.59696960449219 596.7374267578125 309.01666259765625 605.7037963867188 "(triangle-recursive-helper 1
2
2)
" 11 0) (111.59684753417969 621.6974487304688 309.01654052734375 630.663818359375 "(triangle-recursive-helper 3
3
2)
" 12 0)) (165 (90.0 47.60907745361328 449.7492370605469 60.90726852416992 "Looping Exercise
147
" 0 0) (89.99972534179688 77.48908233642578 449.55267333984375 128.58726501464844 "When the last instance is called, the (> counter number) test will be
true, so the instance will return the value of sum, which will be 3.
This kind of pattern helps when you are writing functions that can use
many resources in a computer.
" 1 0) (89.99966430664062 143.90032958984375 247.12889099121094 158.2608642578125 "11.4 Looping Exercise
" 2 0) (98.99977111816406 164.009033203125 449.4334411621094 305.8272399902344 "• Write a function similar to triangle in which each row has a value
which is the square of the row number. Use a while loop.
• Write a function similar to triangle that multiplies instead of adds the
values.
• Rewrite these two functions recursively. Rewrite these functions using
cond.
• Write a function for Texinfo mode that creates an index entry at the
beginning of a paragraph for every ‘@dfn’ within the paragraph. (In
a Texinfo file, ‘@dfn’ marks a definition.
For more information, see
“Indicating Definitions, Commands, etc.” in Texinfo, The GNU Docu-
mentation Format.)
" 3 0)) (166 (90.0 47.60907745361328 449.62860107421875 60.90726852416992 "148
Chapter 11: Loops and Recursion
" 0 0)) (167 (90.0 47.60907745361328 449.53076171875 60.90726852416992 "The Regular Expression for sentence-end
149
" 0 0) (90.0 75.14844512939453 362.1356506347656 92.38106536865234 "12 Regular Expression Searches
" 1 0) (89.9967041015625 113.12909698486328 449.43243408203125 361.5073547363281 "Regular expression searches are used extensively in GNU Emacs. The
two functions, forward-sentence and forward-paragraph, illustrate these
searches well. They use regular expressions to find where to move point.
The phrase ‘regular expression’ is often written as ‘regexp’.
Regular expression searches are described in section “Regular Expression
Search” in The GNU Emacs Manual, as well as in section “Regular Expres-
sions” in The GNU Emacs Lisp Reference Manual. In writing this chapter,
I am presuming that you have at least a mild acquaintance with them. The
major point to remember is that regular expressions permit you to search
for patterns as well as for literal strings of characters. For example, the code
in forward-sentence searches for the pattern of possible characters that
could mark the end of a sentence, and moves point to that spot.
Before looking at the code for the forward-sentence function, it is worth
considering what the pattern that marks the end of a sentence must be.
The pattern is discussed in the next section; following that is a descrip-
tion of the regular expression search function, re-search-forward. The
forward-sentence function is described in the section following. Finally,
the forward-paragraph function is described in the last section of this chap-
ter. forward-paragraph is a complex function that introduces several new
features.
" 2 0) (89.9974365234375 385.8204345703125 416.1036376953125 400.19366455078125 "12.1 The Regular Expression for sentence-end
" 3 0) (89.9971923828125 409.88916015625 449.4735412597656 486.9073486328125 "The symbol sentence-end is bound to the pattern that marks the end
of a sentence. What should this regular expression be?
Clearly, a sentence may be ended by a period, a question mark, or an
exclamation mark. Indeed, only clauses that end with one of those three
characters should be considered the end of a sentence. This means that the
pattern should include the character set:
" 4 0) (89.9964599609375 493.897705078125 449.5382995605469 630.787353515625 "[.?!]
However, we do not want forward-sentence merely to jump to a period,
a question mark, or an exclamation mark, because such a character might
be used in the middle of a sentence. A period, for example, is used after
abbreviations. So other information is needed.
According to convention, you type two spaces after every sentence, but
only one space after a period, a question mark, or an exclamation mark in the
body of a sentence. So a period, a question mark, or an exclamation mark
followed by two spaces is a good indicator of an end of sentence. However, in
a file, the two spaces may instead be a tab or the end of a line. This means
that the regular expression should include these three items as alternatives.
" 5 0)) (168 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "150
Chapter 12: Regular Expression Searches
" 0 0) (104.99993896484375 79.76905059814453 316.5269775390625 93.0672378540039 "This group of alternatives will look like this:
" 1 0) (89.999267578125 98.25759887695312 449.3774108886719 247.1472625732422 "\\\\($\\\\| \\\\|
\\\\)
^
^^
TAB
SPC
Here, ‘$’ indicates the end of the line, and I have pointed out where the tab
and two spaces are inserted in the expression. Both are inserted by putting
the actual characters into the expression.
Two backslashes, ‘\\\\’, are required before the parentheses and vertical
bars: the first backslash quotes the following backslash in Emacs; and the
second indicates that the following character, the parenthesis or the vertical
bar, is special.
Also, a sentence may be followed by one or more carriage returns, like
this:
" 2 0) (89.99929809570312 252.45761108398438 449.24658203125 306.52978515625 "[
]*
Like tabs and spaces, a carriage return is inserted into a regular expression
by inserting it literally. The asterisk indicates that the ⟨
" 3 0) (352.18798828125 290.75201416015625 370.3079833984375 291.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (352.20001220703125 291.9624328613281 370.3001403808594 299.9325256347656 "RET
" 5 0) (352.18798828125 299.27203369140625 370.3079833984375 299.7520446777344 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99893188476562 287.00909423828125 449.79254150390625 374.5873718261719 "⟩ is repeated zero
or more times.
But a sentence end does not consist only of a period, a question mark or an
exclamation mark followed by appropriate space: a closing quotation mark
or a closing brace of some kind may precede the space. Indeed more than
one such mark or brace may precede the space. These require a expression
that looks like this:
" 7 0) (89.99905395507812 379.7777404785156 449.3990173339844 465.4273986816406 "[]\\\"’)}]*
In this expression, the first ‘]’ is the first character in the expression; the
second character is ‘\"’, which is preceded by a ‘\\\\u2019 to tell Emacs the ‘\"’ is not
special. The last three characters are ‘’’, ‘)’, and ‘}’.
All this suggests what the regular expression pattern for matching the
end of a sentence should be; and, indeed, if we evaluate sentence-end we
find that it returns the following value:
" 8 0) (111.59864807128906 470.6177673339844 318.3877868652344 504.5441589355469 "sentence-end
⇒ \"[.?!][]\\\"’)}]*\\\\($\\\\|
\\\\|
\\\\)[
]*\"
" 9 0) (89.99901580810547 521.1805419921875 352.0373840332031 535.5537719726562 "12.2 The re-search-forward Function
" 10 0) (89.99972534179688 543.5692749023438 449.50885009765625 630.7874755859375 "The re-search-forward function is very like the search-forward func-
tion. (See Section 8.1.3, “The search-forward Function”, page 92.)
re-search-forward searches for a regular expression. If the search is
successful, it leaves point immediately after the last character in the target.
If the search is backwards, it leaves point just before the first character in
the target. You may tell re-search-forward to return t for true. (Moving
point is therefore a ‘side effect’.)
" 11 0)) (169 (90.0 47.60907745361328 449.7377624511719 60.90726852416992 "forward-sentence
151
" 0 0) (90.00054931640625 77.48908233642578 449.378662109375 102.66727447509766 "Like search-forward, the re-search-forward function takes four argu-
ments:
" 1 0) (95.88055419921875 108.32910919189453 449.1930236816406 133.50730895996094 "1. The first argument is the regular expression that the function searches
for. The regular expression will be a string between quotations marks.
" 2 0) (95.88018798828125 139.04913330078125 449.258056640625 164.3473358154297 "2. The optional second argument limits how far the function will search;
it is a bound, which is specified as a position in the buffer.
" 3 0) (95.88034057617188 169.88916015625 449.3128356933594 219.06736755371094 "3. The optional third argument specifies how the function responds to
failure: nil as the third argument causes the function to signal an error
(and print a message) when the search fails; any other value causes it
to return nil if the search fails and t if the search succeeds.
" 4 0) (95.88040161132812 224.60919189453125 449.4111328125 249.9073944091797 "4. The optional fourth argument is the repeat count. A negative repeat
count causes re-search-forward to search backwards.
" 5 0) (105.00051879882812 261.44921875 358.59356689453125 274.7474060058594 "The template for re-search-forward looks like this:
" 6 0) (111.60047912597656 283.65533447265625 286.3549499511719 329.9440612792969 "(re-search-forward \"regular-expression\"
limit-of-search
what-to-do-if-search-fails
repeat-count)
" 7 0) (89.9998779296875 335.2491455078125 449.3128662109375 384.4273376464844 "The second, third, and fourth arguments are optional. However, if you
want to pass a value to either or both of the last two arguments, you must also
pass a value to all the preceding arguments. Otherwise, the Lisp interpreter
will mistake which argument you are passing the value to.
" 8 0) (89.99993896484375 389.0091552734375 449.4107666015625 414.3073425292969 "In the forward-sentence function, the regular expression will be the
value of the variable sentence-end, namely:
" 9 0) (111.599609375 423.2176818847656 266.6687927246094 444.6640625 "\"[.?!][]\\\"’)}]*\\\\($\\\\|
\\\\|
\\\\)[
]*\"
" 10 0) (89.99981689453125 450.44915771484375 449.55181884765625 499.6273498535156 "The limit of the search will be the end of the paragraph (since a sentence
cannot go beyond a paragraph). If the search fails, the function will return
nil; and the repeat count will be provided by the argument to the forward-
sentence function.
" 11 0) (89.99996185302734 531.740478515625 245.4329376220703 546.1137084960938 "12.3 forward-sentence
" 12 0) (89.99908447265625 557.7291259765625 449.4430236816406 630.796142578125 "The command to move the cursor forward a sentence is a straightforward
illustration of how to use regular expression searches in Emacs Lisp. Indeed,
the function looks longer and more complicated than it is; this is because the
function is designed to go backwards as well as forwards; and, optionally, over
more than one sentence. The function is usually bound to the key command
M-e.
" 13 0)) (170 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "152
Chapter 12: Regular Expression Searches
" 0 0) (104.99993896484375 80.12909698486328 297.163330078125 93.42728424072266 "Here is the code for forward-sentence:
" 1 0) (89.99945068359375 99.09762573242188 449.4322509765625 422.2270202636719 "(defun forward-sentence (&optional arg)
\"Move forward to next sentence-end.
With argument, repeat.
With negative argument, move backward repeatedly to sentence-beginning.
Sentence ends are identified by the value of sentence-end
treated as a regular expression.
Also, every paragraph boundary
terminates sentences as well.\"
(interactive \"p\")
(or arg (setq arg 1))
(while (< arg 0)
(let ((par-beg
(save-excursion (start-of-paragraph-text) (point))))
(if (re-search-backward
(concat sentence-end \"[^ \\t\\n]\") par-beg t)
(goto-char (1- (match-end 0)))
(goto-char par-beg)))
(setq arg (1+ arg)))
(while (> arg 0)
(let ((par-end
(save-excursion (end-of-paragraph-text) (point))))
(if (re-search-forward sentence-end par-end t)
(skip-chars-backward \" \\t\\n\")
(goto-char par-end)))
(setq arg (1- arg))))
The function looks long at first sight and it is best to look at its skeleton
first, and then its muscle. The way to see the skeleton is to look at the
expressions that start in the left-most columns:
" 2 0) (89.99920654296875 427.8973693847656 449.60614013671875 630.787109375 "(defun forward-sentence (&optional arg)
\"documentation...\"
(interactive \"p\")
(or arg (setq arg 1))
(while (< arg 0)
body-of-while-loop
(while (> arg 0)
body-of-while-loop
This looks much simpler! The function definition consists of documenta-
tion, an interactive expression, an or expression, and while loops.
Let’s look at each of these parts in turn.
We note that the documentation is thorough and understandable.
The function has an interactive \"p\" declaration. This means that the
processed prefix argument, if any, is passed to the function as its argument.
(This will be a number.)
If the function is not passed an argument (it
is optional) then the argument arg will be bound to 1. When forward-
" 3 0)) (171 (90.0 47.60907745361328 449.7705078125 60.90726852416992 "The while loops
153
" 0 0) (89.999755859375 77.48908233642578 449.3232421875 142.50730895996094 "sentence is called non-interactively without an argument, arg is bound to
nil.
The or expression handles the prefix argument. What it does is either
leave the value of arg as it is, but only if arg is bound to a value; or it sets
the value of arg to 1, in the case when arg is bound to nil.
" 1 0) (89.99942016601562 161.641845703125 191.64161682128906 174.7574005126953 "The while loops
" 2 0) (89.99771118164062 184.76910400390625 449.4635314941406 285.7873229980469 "Two while loops follow the or expression. The first while has a true-
or-false-test that tests true if the prefix argument for forward-sentence is
a negative number. This is for going backwards. The body of this loop is
similar to the body of the second while clause, but it is not exactly the
same. We will skip this while loop and concentrate on the second while
loop.
The second while loop is for moving point forward. Its skeleton looks
like this:
" 3 0) (111.59773254394531 292.6552734375 350.038330078125 363.9040222167969 "(while (> arg 0)
; true-or-false-test
(let varlist
(if (true-or-false-test)
then-part
else-part
(setq arg (1- arg))))
; while loop decrementer
" 4 0) (89.99560546875 367.88909912109375 449.4292297363281 512.5872802734375 "The while loop is of the decrementing kind. (See Section 11.1.4, “A Loop
with a Decrementing Counter”, page 129.) It has a true-or-false-test that
tests true so long as the counter (in this case, the variable arg) is greater
than zero; and it has a decrementer that subtracts 1 from the value of the
counter every time the loop repeats.
If no prefix argument is given to forward-sentence, which is the most
common way the command is used, this while loop will run once, since the
value of arg will be 1.
The body of the while loop consists of a let expression, which creates
and binds a local variable, and has, as its body, an if expression.
The body of the while loop looks like this:
" 5 0) (89.99581909179688 519.4577026367188 449.3626403808594 630.787353515625 "(let ((par-end
(save-excursion (end-of-paragraph-text) (point))))
(if (re-search-forward sentence-end par-end t)
(skip-chars-backward \" \\t\\n\")
(goto-char par-end)))
The let expression creates and binds the local variable par-end. As we
shall see, this local variable is designed to provide a bound or limit to the
regular expression search. If the search fails to find a proper sentence ending
in the paragraph, it will stop on reaching the end of the paragraph.
" 6 0)) (172 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "154
Chapter 12: Regular Expression Searches
" 0 0) (89.99993896484375 77.48908233642578 449.5736999511719 114.66727447509766 "But first, let us examine how par-end is bound to the value of the end
of the paragraph. What happens is that the let sets the value of par-end
to the value returned when the Lisp interpreter evaluates the expression
" 1 0) (89.9990234375 119.61764526367188 449.7923278808594 228.9072723388672 "(save-excursion (end-of-paragraph-text) (point))
In this expression, (end-of-paragraph-text) moves point to the end of the
paragraph, (point) returns the value of point, and then save-excursion
restores point to its original position. Thus, the let binds par-end to the
value returned by the save-excursion expression, which is the position of
the end of the paragraph. (The (end-of-paragraph-text) function uses
forward-paragraph, which we will discuss shortly.)
Emacs next evaluates the body of the let, which is an if expression that
looks like this:
" 2 0) (89.99746704101562 233.855224609375 449.59356689453125 344.2272644042969 "(if (re-search-forward sentence-end par-end t) ; if-part
(skip-chars-backward \" \\t\\n\")
; then-part
(goto-char par-end)))
; else-part
The if tests whether its first argument is true and if so, evaluates its
then-part; otherwise, the Emacs Lisp interpreter evaluates the else-part.
The true-or-false-test of the if expression is the regular expression search.
It may seem odd to have what looks like the ‘real work’ of the forward-
sentence function buried here, but this is a common way this kind of oper-
ation is carried out in Lisp.
" 3 0) (89.99707794189453 356.1618347167969 281.9797058105469 369.2658386230469 "The regular expression search
" 4 0) (89.9952392578125 377.36907958984375 449.45166015625 630.787353515625 "The re-search-forward function searches for the end of the sentence,
that is, for the pattern defined by the sentence-end regular expression.
If the pattern is found—if the end of the sentence is found—then the re-
search-forward function does two things:
1. The re-search-forward function carries out a side effect, which is to
move point to the end of the occurrence found.
2. The re-search-forward function returns a value of true. This is the
value received by the if, and means that the search was successful.
The side effect, the movement of point, is completed before the if function
is handed the value returned by the successful conclusion of the search.
When the if function receives the value of true from a successful call to
re-search-forward, the if evaluates the then-part, which is the expression
(skip-chars-backward \" \\t\\n\"). This expression moves backwards over
any blank spaces, tabs or carriage returns until a printed character is found
and then leaves point after the character.
Since point has already been
moved to the end of the pattern that marks the end of the sentence, this
action leaves point right after the closing printed character of the sentence,
which is usually a period.
On the other hand, if the re-search-forward function fails to find a
pattern marking the end of the sentence, the function returns false. The
" 5 0)) (173 (90.0 47.60907745361328 449.4983215332031 60.90726852416992 "forward-paragraph: a Goldmine of Functions
155
" 0 0) (90.00009155273438 77.48908233642578 449.6403503417969 153.4272918701172 "false then causes the if to evaluate its third argument, which is (goto-char
par-end): it moves point to the end of the paragraph.
Regular expression searches are exceptionally useful and the pattern il-
lustrated by re-search-forward, in which the search is the test of an if
expression, is handy. You will see or write code incorporating this pattern
often.
" 1 0) (90.00009155273438 173.660400390625 438.1575622558594 188.0336151123047 "12.4 forward-paragraph: a Goldmine of Functions
" 2 0) (90.000244140625 196.64910888671875 449.4227294921875 478.7473449707031 "The forward-paragraph function moves point forward to the end of the
paragraph. It is usually bound to M-} and makes use of a number of functions
that are important in themselves, including let*, match-beginning, and
looking-at.
The function definition for forward-paragraph is considerably longer
than the function definition for forward-sentence because it works with a
paragraph, each line of which may begin with a fill prefix.
A fill prefix consists of a string of characters that are repeated at the
beginning of each line. For example, in Lisp code, it is a convention to start
each line of a paragraph-long comment with ‘;;; ’. In Text mode, four blank
spaces make up another common fill prefix, creating an indented paragraph.
(See section “Fill Prefix” in The GNU Emacs Manual, for more information
about fill prefixes.)
The existence of a fill prefix means that in addition to being able to
find the end of a paragraph whose lines begin on the left-most column, the
forward-paragraph function must be able to find the end of a paragraph
when all or many of the lines in the buffer begin with the fill prefix.
Moreover, it is sometimes practical to ignore a fill prefix that exists, espe-
cially when blank lines separate paragraphs. This is an added complication.
Rather than print all of the forward-paragraph function, we will only
print parts of it. Read without preparation, the function can be daunting!
In outline, the function looks like this:
" 3 0) (111.60200500488281 484.6576843261719 344.3360595703125 630.6641235351562 "(defun forward-paragraph (&optional arg)
\"documentation...\"
(interactive \"p\")
(or arg (setq arg 1))
(let*
varlist
(while (< arg 0)
; backward-moving-code
...
(setq arg (1+ arg)))
(while (> arg 0)
; forward-moving-code
...
(setq arg (1- arg)))))
" 4 0)) (174 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "156
Chapter 12: Regular Expression Searches
" 0 0) (89.99948120117188 77.48908233642578 449.2684326171875 102.66727447509766 "The first parts of the function are routine: the function’s argument list
consists of one optional argument. Documentation follows.
" 1 0) (89.99819946289062 107.00910186767578 449.42071533203125 203.9473114013672 "The lower case ‘p’ in the interactive declaration means that the pro-
cessed prefix argument, if any, is passed to the function.
This will be a
number, and is the repeat count of how many paragraphs point will move.
The or expression in the next line handles the common case when no argu-
ment is passed to the function, which occurs if the function is called from
other code rather than interactively. This case was described earlier. (See
Section 12.3, “forward-sentence”, page 151.) Now we reach the end of the
familiar part of this function.
" 2 0) (89.9985122680664 228.24188232421875 218.32643127441406 241.35743713378906 "The let* expression
" 3 0) (89.99908447265625 253.04913330078125 449.409912109375 290.2273254394531 "The next line of the forward-paragraph function begins a let* expres-
sion. This is a different kind of expression than we have seen so far. The
symbol is let* not let.
" 4 0) (89.99856567382812 294.44915771484375 449.38751220703125 343.6273498535156 "The let* special form is like let except that Emacs sets each variable
in sequence, one after another, and variables in the latter part of the varlist
can make use of the values to which Emacs set variables in the earlier part
of the varlist.
" 5 0) (89.99856567382812 347.96905517578125 449.68231201171875 385.1472473144531 "In the let* expression in this function, Emacs binds two variables: fill-
prefix-regexp and paragraph-separate. The value to which paragraph-
separate is bound depends on the value of fill-prefix-regexp.
" 6 0) (90.0001220703125 389.48907470703125 449.33477783203125 414.7872619628906 "Let’s look at each in turn. The symbol fill-prefix-regexp is set to
the value returned by evaluating the following list:
" 7 0) (111.60064697265625 423.3376159667969 294.23504638671875 469.7440185546875 "(and fill-prefix
(not (equal fill-prefix \"\"))
(not paragraph-ignore-fill-prefix)
(regexp-quote fill-prefix))
" 8 0) (90.00092315673828 474.6891174316406 399.294921875 487.9873046875 "This is an expression whose first element is the and special form.
" 9 0) (90.0006103515625 492.3291015625 449.4550476074219 577.3873291015625 "As we learned earlier (see “The kill-new function”, page 105), the and
special form evaluates each of its arguments until one of the arguments
returns a value of nil, in which case the and expression returns nil; however,
if none of the arguments returns a value of nil, the value resulting from
evaluating the last argument is returned. (Since such a value is not nil, it
is considered true in Lisp.) In other words, an and expression returns a true
value only if all its arguments are true.
" 10 0) (90.0015869140625 581.609130859375 449.4786376953125 630.787353515625 "In this case, the variable fill-prefix-regexp is bound to a non-nil
value only if the following four expressions produce a true (i.e., a non-nil)
value when they are evaluated; otherwise, fill-prefix-regexp is bound to
nil.
" 11 0)) (175 (90.0 47.60907745361328 449.7272644042969 60.90726852416992 "The let* expression
157
" 0 0) (90.00051879882812 79.33271789550781 449.5204162597656 126.66727447509766 "fill-prefix
When this variable is evaluated, the value of the fill prefix, if
any, is returned. If there is no fill prefix, this variable returns
nil.
" 1 0) (90.00067901611328 132.6127471923828 449.4652099609375 179.8273162841797 "(not (equal fill-prefix \"\")
This expression checks whether an existing fill prefix is an empty
string, that is, a string with no characters in it. An empty string
is not a useful fill prefix.
" 2 0) (90.00048828125 185.7727813720703 449.98846435546875 233.1073455810547 "(not paragraph-ignore-fill-prefix)
This expression returns nil if the variable paragraph-ignore-
fill-prefix has been turned on by being set to a true value
such as t.
" 3 0) (89.99918365478516 239.0528106689453 449.5186767578125 298.2673645019531 "(regexp-quote fill-prefix)
This is the last argument to the and special form. If all the
arguments to the and are true, the value resulting from evaluat-
ing this expression will be returned by the and expression and
bound to the variable fill-prefix-regexp,
" 4 0) (89.99911499023438 304.4091796875 449.96673583984375 415.26739501953125 "The result of evaluating this and expression successfully is that fill-
prefix-regexp will be bound to the value of fill-prefix as modified by
the regexp-quote function. What regexp-quote does is read a string and
return a regular expression that will exactly match the string and match
nothing else. This means that fill-prefix-regexp will be set to a value
that will exactly match the fill prefix if the fill prefix exists. Otherwise, the
variable will be set to nil.
The second local variable in the let* expression is paragraph-separate.
It is bound to the value returned by evaluating the expression:
" 5 0) (90.00009155273438 420.3377380371094 449.8907775878906 630.7874755859375 "(if fill-prefix-regexp
(concat paragraph-separate
\"\\\\|^\" fill-prefix-regexp \"[ \\t]*$\")
paragraph-separate)))
This expression shows why let* rather than let was used. The true-or-
false-test for the if depends on whether the variable fill-prefix-regexp
evaluates to nil or some other value.
If fill-prefix-regexp does not have a value, Emacs evaluates the else-
part of the if expression and binds paragraph-separate to its local value.
(paragraph-separate is a regular expression that matches what separates
paragraphs.)
But if fill-prefix-regexp does have a value, Emacs evaluates the then-
part of the if expression and binds paragraph-separate to a regular ex-
pression that includes the fill-prefix-regexp as part of the pattern.
Specifically, paragraph-separate is set to the original value of the para-
graph separate regular expression concatenated with an alternative expres-
sion that consists of the fill-prefix-regexp followed by a blank line. The
" 6 0)) (176 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "158
Chapter 12: Regular Expression Searches
" 0 0) (89.99960327148438 77.48908233642578 449.94512939453125 114.66727447509766 "‘^’ indicates that the fill-prefix-regexp must begin a line, and the op-
tional whitespace to the end of the line is defined by \"[ \\t]*$\".) The ‘\\\\|’
defines this portion of the regexp as an alternative to paragraph-separate.
" 1 0) (89.9998779296875 120.20911407470703 449.4647521972656 157.38731384277344 "Now we get into the body of the let*. The first part of the body of the
let* deals with the case when the function is given a negative argument and
is therefore moving backwards. We will skip this section.
" 2 0) (89.999267578125 185.5218505859375 290.05029296875 198.6374053955078 "The forward motion while loop
" 3 0) (89.99871826171875 211.52911376953125 449.44268798828125 272.7073059082031 "The second part of the body of the let* deals with forward motion. It
is a while loop that repeats itself so long as the value of arg is greater than
zero. In the most common use of the function, the value of the argument is
1, so the body of the while loop is evaluated exactly once, and the cursor
moves forward one paragraph.
" 4 0) (89.99847412109375 278.2491455078125 449.40911865234375 315.4273376464844 "This part handles three situations: when point is between paragraphs,
when point is within a paragraph and there is a fill prefix, and when point
is within a paragraph and there is no fill prefix.
" 5 0) (104.99806213378906 321.0891418457031 251.87796020507812 334.3873291015625 "The while loop looks like this:
" 6 0) (111.59785461425781 344.2576904296875 209.7518310546875 365.7040710449219 "(while (> arg 0)
(beginning-of-line)
" 7 0) (120.9578628540039 381.6952819824219 360.3697204589844 427.98406982421875 ";; between paragraphs
(while (prog1 (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1)))
" 8 0) (120.95848846435547 436.17529296875 369.69635009765625 519.7841186523438 ";; within paragraphs, with a fill prefix
(if fill-prefix-regexp
;; There is a fill prefix; it overrides paragraph-start.
(while (and (not (eobp))
(not (looking-at paragraph-separate))
(looking-at fill-prefix-regexp))
(forward-line 1))
" 9 0) (130.43902587890625 527.9752807617188 341.92572021484375 574.26416015625 ";; within paragraphs, no fill prefix
(if (re-search-forward paragraph-start nil t)
(goto-char (match-beginning 0))
(goto-char (point-max))))
" 10 0) (120.95838928222656 590.2577514648438 214.92933654785156 599.22412109375 "(setq arg (1- arg)))
" 11 0) (89.99810791015625 605.4891967773438 449.39801025390625 630.7874145507812 "We can see immediately that this is a decrementing counter while loop,
using the expression (setq arg (1- arg)) as the decrementer.
" 12 0)) (177 (90.0 47.60907745361328 449.7273864746094 60.90726852416992 "Between paragraphs
159
" 0 0) (104.9996337890625 79.76905059814453 346.49383544921875 93.0672378540039 "The body of the loop consists of three expressions:
" 1 0) (111.59902954101562 98.25519561767578 205.7562255859375 144.54393005371094 ";; between paragraphs
(beginning-of-line)
(while
body-of-while)
" 2 0) (111.59857177734375 152.735107421875 261.6708984375 186.6614532470703 ";; within paragraphs, with fill prefix
(if true-or-false-test
then-part
" 3 0) (89.99832153320312 194.73504638671875 449.4425964355469 290.8271179199219 ";; within paragraphs, no fill prefix
else-part
When the Emacs Lisp interpreter evaluates the body of the while loop, the
first thing it does is evaluate the (beginning-of-line) expression and move
point to the beginning of the line. Then there is an inner while loop. This
while loop is designed to move the cursor out of the blank space between
paragraphs, if it should happen to be there. Finally, there is an if expression
that actually moves point to the end of the paragraph.
" 4 0) (89.99859619140625 304.80169677734375 220.37962341308594 317.90570068359375 "Between paragraphs
" 5 0) (89.99856567382812 326.1289367675781 449.5511779785156 480.547119140625 "First, let us look at the inner while loop. This loop handles the case
when point is between paragraphs; it uses three functions that are new to
us: prog1, eobp and looking-at.
• prog1 is similar to the progn special form, except that prog1 evaluates
its arguments in sequence and then returns the value of its first argument
as the value of the whole expression. (progn returns the value of its last
argument as the value of the expression.) The second and subsequent
arguments to prog1 are evaluated only for their side effects.
• eobp is an abbreviation of ‘End Of Buffer P’ and is a function that
returns true if point is at the end of the buffer.
• looking-at is a function that returns true if the text following point
matches the regular expression passed looking-at as its argument.
" 6 0) (104.99765014648438 484.64892578125 330.6956481933594 497.9471130371094 "The while loop we are studying looks like this:
" 7 0) (89.99786376953125 503.1374816894531 449.37579345703125 564.9071655273438 "(while (prog1 (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1)))
This is a while loop with no body! The true-or-false-test of the loop is the
expression:
" 8 0) (89.99807739257812 570.0975341796875 449.4409484863281 630.7871704101562 "(prog1 (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1))
The first argument to the prog1 is the and expression. It has within in it a
test of whether point is at the end of the buffer and also a test of whether
" 9 0)) (178 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "160
Chapter 12: Regular Expression Searches
" 0 0) (89.999755859375 77.48908233642578 449.41094970703125 237.3072967529297 "the pattern following point matches the regular expression for separating
paragraphs.
If the cursor is not at the end of the buffer and if the characters fol-
lowing the cursor mark the separation between two paragraphs, then the
and expression is true. After evaluating the and expression, the Lisp inter-
preter evaluates the second argument to prog1, which is forward-line. This
moves point forward one line. The value returned by the prog1 however, is
the value of its first argument, so the while loop continues so long as point
is not at the end of the buffer and is between paragraphs. When, finally,
point is moved to a paragraph, the and expression tests false. Note however,
that the forward-line command is carried out anyhow. This means that
when point is moved from between paragraphs to a paragraph, it is left at
the beginning of the second line of the paragraph.
" 1 0) (89.99977111816406 253.92181396484375 211.5074005126953 267.02581787109375 "Within paragraphs
" 2 0) (89.99969482421875 276.20904541015625 449.6615295410156 337.3872375488281 "The next expression in the outer while loop is an if expression. The
Lisp interpreter evaluates the then-part of the if when the fill-prefix-
regexp variable has a value other than nil, and it evaluates the else-part
when the value of if fill-prefix-regexp is nil, that is, when there is no
fill prefix.
" 3 0) (89.99969482421875 354.0018005371094 171.7611083984375 367.1058044433594 "No fill prefix
" 4 0) (89.99993896484375 376.2890625 449.4975280761719 413.4672546386719 "It is simplest to look at the code for the case when there is no fill prefix
first. This code consists of yet another inner if expression, and reads as
follows:
" 5 0) (89.99655151367188 419.49761962890625 449.43017578125 630.787353515625 "(if (re-search-forward paragraph-start nil t)
(goto-char (match-beginning 0))
(goto-char (point-max)))
This expression actually does the work that most people think of as the
primary purpose of the forward-paragraph command: it causes a regular
expression search to occur that searches forward to the start of the next
paragraph and if it is found, moves point there; but if the start of another
paragraph if not found, it moves point to the end of the accessible region of
the buffer.
The only unfamiliar part of this is the use of match-beginning. This is
another function that is new to us. The match-beginning function returns
a number specifying the location of the start of the text that was matched
by the last regular expression search.
The match-beginning function is used here because of a characteristic
of a forward search: a successful forward search, regardless of whether it is
a plain search or a regular expression search, will move point to the end of
the text that is found. In this case, a successful search will move point to
" 6 0)) (179 (90.0 47.60907745361328 449.8367614746094 60.90726852416992 "Summary
161
" 0 0) (89.997314453125 77.48908233642578 449.54998779296875 252.18724060058594 "the end of the pattern for paragraph-start, which will be the beginning of
the next paragraph rather than the end of the current one.
However, we want to put point at the end of the current paragraph, not at
the beginning of the next one. The two positions may be different, because
there may be several blank lines between paragraphs.
When given an argument of 0, match-beginning returns the position
that is the start of the text that the most recent regular expression search
matched. In this case, the most recent regular expression search is the one
looking for paragraph-start, so match-beginning returns the beginning
position of the pattern, rather than the end of the pattern. The beginning
position is the end of the paragraph.
(Incidentally, when passed a positive number as an argument, the match-
beginning function will place point at that parenthesized expression in the
last regular expression. It is a useful function.)
" 1 0) (89.99736022949219 265.4417724609375 198.25259399414062 278.5457763671875 "With a fill prefix
" 2 0) (89.99710083007812 286.6490478515625 449.4732666015625 323.8272399902344 "The inner if expression just discussed is the else-part of an enclosing if
expression which tests whether there is a fill prefix. If there is a fill prefix,
the then-part of this if is evaluated. It looks like this:
" 3 0) (89.99717712402344 328.8975830078125 449.3642578125 446.58734130859375 "(while (and (not (eobp))
(not (looking-at paragraph-separate))
(looking-at fill-prefix-regexp))
(forward-line 1))
What this expression does is move point forward line by line so long as three
conditions are true:
1. Point is not at the end of the buffer.
2. The text following point does not separate paragraphs.
3. The pattern following point is the fill prefix regular expression.
" 4 0) (89.99679565429688 450.20916748046875 449.38580322265625 499.3873596191406 "The last condition may be puzzling, until you remember that point was
moved to the beginning of the line early in the forward-paragraph function.
This means that if the text has a fill prefix, the looking-at function will
see it.
" 5 0) (89.99679565429688 512.6419067382812 151.72039794921875 525.7459106445312 "Summary
" 6 0) (89.99636840820312 533.84912109375 449.45123291015625 630.787353515625 "In summary, when moving forward, the forward-paragraph function
does the following:
• Move point to the beginning of the line.
• Skip over lines between paragraphs.
• Check whether there is a fill prefix, and if there is:
— Go forward line by line so long as the line is not a paragraph sep-
arating line.
" 7 0)) (180 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "162
Chapter 12: Regular Expression Searches
" 0 0) (98.99993896484375 77.48908233642578 449.57373046875 147.5472869873047 "• But if there is no fill prefix,
— Search for the next paragraph start pattern.
— Go to the beginning of the paragraph start pattern, which will be
the end of the previous paragraph.
— Or else go to the end of the accessible portion of the buffer.
" 1 0) (89.99850463867188 151.28900146484375 449.3110656738281 176.5872039794922 "For review, here is the code we have just been discussing, formatted for
clarity:
" 2 0) (111.59854888916016 181.65756225585938 360.6536560058594 265.2638244628906 "(interactive \"p\")
(or arg (setq arg 1))
(let* (
(fill-prefix-regexp
(and fill-prefix (not (equal fill-prefix \"\"))
(not paragraph-ignore-fill-prefix)
(regexp-quote fill-prefix)))
" 3 0) (144.598876953125 273.4574279785156 289.92138671875 357.1837463378906 "(paragraph-separate
(if fill-prefix-regexp
(concat paragraph-separate
\"\\\\|^\"
fill-prefix-regexp
\"[ \\t]*$\")
paragraph-separate)))
" 4 0) (120.95891571044922 373.0549621582031 266.1722412109375 382.02374267578125 "omitted-backward-moving-code ...
" 5 0) (120.95893859863281 390.2149658203125 364.9723815917969 411.66375732421875 "(while (> arg 0)
; forward-moving-code
(beginning-of-line)
" 6 0) (130.4390869140625 427.5373840332031 369.7309265136719 461.4637756347656 "(while (prog1 (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1)))
" 7 0) (130.439697265625 469.53741455078125 379.0573425292969 579.183837890625 "(if fill-prefix-regexp
(while (and (not (eobp))
; then-part
(not (looking-at paragraph-separate))
(looking-at fill-prefix-regexp))
(forward-line 1))
; else-part: the inner-if
(if (re-search-forward paragraph-start nil t)
(goto-char (match-beginning 0))
(goto-char (point-max))))
" 8 0) (89.999755859375 595.175048828125 449.3126525878906 630.787109375 "(setq arg (1- arg)))))
; decrementer
The full definition for the forward-paragraph function not only includes
this code for going forwards, but also code for going backwards.
" 9 0)) (181 (90.0 47.60907745361328 449.6614074707031 60.90726852416992 "Create Your Own ‘TAGS’ File
163
" 0 0) (89.99905395507812 77.48908233642578 449.5411682128906 238.62730407714844 "If you are reading this inside of GNU Emacs and you want to see the
whole function, you can type C-h f (describe-function) and the name of
the function. This gives you the function documentation and the name of
the library containing the function’s source. Place point over the name of
the library and press the RET key; you will be taken directly to the source.
(Be sure to install your sources! Without them, you are like a person who
tries to drive a car with his eyes shut!)
Or – a good habit to get into – you can type M-. (find-tag) and
the name of the function when prompted for it.
This will take you di-
rectly to the source.
If the find-tag function first asks you for the
name of a ‘TAGS’ table, give it the name of the ‘TAGS’ file such as
‘/usr/local/share/emacs/21.0.100/lisp/TAGS’. (The exact path to your
‘TAGS’ file depends on how your copy of Emacs was installed.)
" 1 0) (105.00038146972656 241.76898193359375 433.5707702636719 255.0671844482422 "You can also create your own ‘TAGS’ file for directories that lack one.
" 2 0) (89.999755859375 281.30029296875 327.34423828125 295.67352294921875 "12.5 Create Your Own ‘TAGS’ File
" 3 0) (89.99783325195312 305.8489990234375 449.50732421875 435.5472106933594 "The M-. (find-tag) command takes you directly to the source for a
function, variable, node, or other source.
The function depends on tags
tables to tell it where to go.
You often need to build and install tags tables yourself. They are not
built automatically. A tags table is called a ‘TAGS’ file; the name is in upper
case letters.
You can create a ‘TAGS’ file by calling the etags program that comes as
a part of the Emacs distribution. Usually, etags is compiled and installed
when Emacs is built. (etags is not an Emacs Lisp function or a part of
Emacs; it is a C program.)
" 4 0) (89.99786376953125 438.80902099609375 449.45233154296875 499.8672180175781 "To create a ‘TAGS’ file, first switch to the directory in which you want
to create the file.
In Emacs you can do this with the M-x cd command,
or by visiting a file in the directory, or by listing the directory with C-x d
(dired). Then run the compile command, with etags *.el as the command
to execute
" 5 0) (89.99842834472656 507.3375549316406 252.54074096679688 533.1072998046875 "M-x compile RET etags *.el RET
to create a ‘TAGS’ file.
" 6 0) (89.998779296875 536.2490234375 449.3979797363281 573.42724609375 "For example, if you have a large number of files in your ‘~/emacs’ direc-
tory, as I do—I have 137 ‘.el’ files in it, of which I load 12—you can create
a ‘TAGS’ file for the Emacs Lisp files in that directory.
" 7 0) (89.9986572265625 576.6890869140625 449.3982849121094 613.8673095703125 "The etags program takes all the usual shell ‘wildcards’. For example,
if you have two directories for which you want a single ‘TAGS file’, type
etags *.el ../elisp/*.el, where ‘../elisp/’ is the second directory:
" 8 0) (111.59884643554688 621.337646484375 318.3108215332031 630.3040161132812 "M-x compile RET etags *.el ../elisp/*.el RET
" 9 0)) (182 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "164
Chapter 12: Regular Expression Searches
" 0 0) (104.99993896484375 79.52906036376953 129.6108856201172 92.8272476196289 "Type
" 1 0) (89.9996337890625 98.01760864257812 449.5953674316406 359.2271728515625 "M-x compile RET etags --help RET
to see a list of the options accepted by etags as well as a list of supported
languages.
The etags program handles more than 20 languages, including Emacs
Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX, Pascal,
Perl, Python, Texinfo, makefiles, and most assemblers. The program has no
switches for specifying the language; it recognizes the language in an input
file according to its file name and contents.
‘etags’ is very helpful when you are writing code yourself and want to
refer back to functions you have already written. Just run etags again at
intervals as you write new functions, so they become part of the ‘TAGS’ file.
If you think an appropriate ‘TAGS’ file already exists for what you want,
but do not know where it is, you can use the locate program to attempt to
find it.
Type M-x locate RET TAGS RET and Emacs will list for you the full path
names of all your ‘TAGS’ files. On my system, this command lists 34 ‘TAGS’
files. On the other hand, a ‘plain vanilla’ system I recently installed did not
contain any ‘TAGS’ files.
If the tags table you want has been created, you can use the M-x visit-
tags-table command to specify it. Otherwise, you will need to create the
tag table yourself and then use M-x visit-tags-table.
" 2 0) (89.99948120117188 372.96173095703125 319.059814453125 386.06573486328125 "Building Tags in the Emacs sources
" 3 0) (89.99874877929688 394.2889709472656 449.4205322265625 469.6271667480469 "The GNU Emacs sources come with a ‘Makefile’ that contains a sophis-
ticated etags command that creates, collects, and merges tags tables from
all over the Emacs sources and puts the information into one ‘TAGS’ file in
the ‘src/’ directory below the top level of your Emacs source directory.
To build this ‘TAGS’ file, go to the top level of your Emacs source directory
and run the compile command make tags:
" 4 0) (89.99783325195312 474.697509765625 449.3002624511719 536.2271728515625 "M-x compile RET make tags RET
(The make tags command works well with the GNU Emacs sources, as well
as with some other source packages.)
For more information, see section “Tag Tables” in The GNU Emacs Man-
ual.
" 5 0) (89.99783325195312 553.1002807617188 177.92282104492188 567.4608154296875 "12.6 Review
" 6 0) (104.99783325195312 575.3690185546875 405.0631103515625 588.667236328125 "Here is a brief summary of some recently introduced functions.
" 7 0) (89.99752807617188 593.6090087890625 449.5286865234375 630.7872314453125 "while
Repeatedly evaluate the body of the expression so long as the
first element of the body tests true. Then return nil. (The
expression is evaluated only for its side effects.)
" 8 0)) (183 (90.0 47.60907745361328 449.8467712402344 60.90726852416992 "Review
165
" 0 0) (147.60000610351562 80.36908721923828 209.08372497558594 93.66727447509766 "For example:
" 1 0) (169.20004272460938 99.45761108398438 357.13177490234375 145.7439422607422 "(let ((foo 2))
(while (> foo 0)
(insert (format \"foo is %d.\\n\" foo))
(setq foo (1- foo))))
" 2 0) (147.60009765625 160.89305114746094 449.629150390625 235.5071258544922 "⇒
foo is 2.
foo is 1.
nil
(The insert function inserts its arguments at point; the format
function returns a string formatted from its arguments the way
message formats its arguments; \\n produces a new line.)
" 3 0) (89.99957275390625 241.5725860595703 449.4542236328125 374.46710205078125 "re-search-forward
Search for a pattern, and if the pattern is found, move point to
rest just after it.
Takes four arguments, like search-forward:
1. A regular expression that specifies the pattern to search for.
2. Optionally, the limit of the search.
3. Optionally, what to do if the search fails, return nil or an
error message.
4. Optionally, how many times to repeat the search; if nega-
tive, the search goes backwards.
" 4 0) (90.00047302246094 378.68890380859375 449.41058349609375 442.6271057128906 "let*
Bind some variables locally to particular values, and then eval-
uate the remaining arguments, returning the value of the last
one. While binding the local variables, use the local values of
variables bound earlier, if any.
For example:
" 5 0) (169.20059204101562 448.4174499511719 314.8232727050781 500.56964111328125 "(let* ((foo 7)
(bar (* 3 foo)))
(message \"‘bar’ is %d.\" bar))
⇒ ‘bar’ is 21.
" 6 0) (90.00080871582031 500.652587890625 449.3891906738281 535.9871826171875 "match-beginning
Return the position of the start of the text found by the last
regular expression search.
" 7 0) (90.000244140625 542.0525512695312 449.3564147949219 577.3871459960938 "looking-at
Return t for true if the text after point matches the argument,
which should be a regular expression.
" 8 0) (90.0003662109375 581.6089477539062 449.54168701171875 630.7871704101562 "eobp
Return t for true if point is at the end of the accessible part of
a buffer. The end of the accessible part is the end of the buffer
if the buffer is not narrowed; it is the end of the narrowed part
if the buffer is narrowed.
" 9 0)) (184 (90.0 47.60907745361328 449.4543151855469 60.90726852416992 "166
Chapter 12: Regular Expression Searches
" 0 0) (89.99993896484375 77.48908233642578 449.3233947753906 117.78726959228516 "prog1
Evaluate each argument in sequence and then return the value
of the first.
For example:
" 1 0) (169.19949340820312 123.81759643554688 239.7015380859375 150.88978576660156 "(prog1 1 2 3 4)
⇒ 1
" 2 0) (89.99950408935547 165.02032470703125 359.7030334472656 179.39353942871094 "12.7 Exercises with re-search-forward
" 3 0) (98.9993896484375 185.1290283203125 449.46368408203125 297.0672302246094 "• Write a function to search for a regular expression that matches two or
more blank lines in sequence.
• Write a function to search for duplicated words, such as ‘the the’. See
section “Syntax of Regular Expressions” in The GNU Emacs Manual,
for information on how to write a regexp (a regular expression) to match
a string that is composed of two identical halves. You can devise several
regexps; some are better than others. The function I use is described
in an appendix, along with several regexps. See Appendix A, “the-the
Duplicated Words Function”, page 241.
" 4 0)) (185 (90.0 47.60907745361328 449.5970764160156 60.90726852416992 "The count-words-region Function
167
" 0 0) (90.00030517578125 75.14844512939453 415.8580017089844 92.38106536865234 "13 Counting: Repetition and Regexps
" 1 0) (89.999267578125 103.88910675048828 449.55194091796875 300.6672058105469 "Repetition and regular expression searches are powerful tools that you
often use when you write code in Emacs Lisp. This chapter illustrates the
use of regular expression searches through the construction of word count
commands using while loops and recursion.
The standard Emacs distribution contains a function for counting the
number of lines within a region. However, there is no corresponding function
for counting words.
Certain types of writing ask you to count words.
Thus, if you write
an essay, you may be limited to 800 words; if you write a novel, you may
discipline yourself to write 1000 words a day.
It seems odd to me that
Emacs lacks a word count command. Perhaps people use Emacs mostly for
code or types of documentation that do not require word counts; or perhaps
they restrict themselves to the operating system word count command, wc.
Alternatively, people may follow the publishers’ convention and compute a
word count by dividing the number of characters in a document by five. In
any event, here are commands to count words.
" 2 0) (89.99974060058594 317.4202880859375 359.4695129394531 331.79351806640625 "13.1 The count-words-region Function
" 3 0) (89.99868774414062 339.5690002441406 449.71588134765625 526.6272583007812 "A word count command could count words in a line, paragraph, region,
or buffer. What should the command cover? You could design the command
to count the number of words in a complete buffer. However, the Emacs tra-
dition encourages flexibility—you may want to count words in just a section,
rather than all of a buffer. So it makes more sense to design the command
to count the number of words in a region. Once you have a count-words-
region command, you can, if you wish, count words in a whole buffer by
marking it with C-x h (mark-whole-buffer).
Clearly, counting words is a repetitive act: starting from the beginning
of the region, you count the first word, then the second word, then the third
word, and so on, until you reach the end of the region. This means that
word counting is ideally suited to recursion or to a while loop.
First, we will implement the word count command with a while loop,
then with recursion. The command will, of course, be interactive.
The template for an interactive function definition is, as always:
" 4 0) (89.99801635742188 531.6951293945312 449.40899658203125 630.7872924804688 "(defun name-of-function (argument-list)
\"documentation...\"
(interactive-expression...)
body...)
What we need to do is fill in the slots.
The name of the function should be self-explanatory and similar to the
existing count-lines-region name. This makes the name easier to remem-
ber. count-words-region is a good choice.
" 5 0)) (186 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "168
Chapter 13: Counting: Repetition and Regexps
" 0 0) (89.99566650390625 77.48908233642578 449.6606140136719 574.1474609375 "The function counts words within a region. This means that the argument
list must contain symbols that are bound to the two positions, the beginning
and end of the region. These two positions can be called ‘beginning’ and
‘end’ respectively. The first line of the documentation should be a single sen-
tence, since that is all that is printed as documentation by a command such
as apropos. The interactive expression will be of the form ‘(interactive
\"r\")’, since that will cause Emacs to pass the beginning and end of the
region to the function’s argument list. All this is routine.
The body of the function needs to be written to do three tasks: first, to
set up conditions under which the while loop can count words, second, to
run the while loop, and third, to send a message to the user.
When a user calls count-words-region, point may be at the beginning
or the end of the region. However, the counting process must start at the
beginning of the region.
This means we will want to put point there if
it is not already there.
Executing (goto-char beginning) ensures this.
Of course, we will want to return point to its expected position when the
function finishes its work. For this reason, the body must be enclosed in a
save-excursion expression.
The central part of the body of the function consists of a while loop
in which one expression jumps point forward word by word, and another
expression counts those jumps.
The true-or-false-test of the while loop
should test true so long as point should jump forward, and false when point
is at the end of the region.
We could use (forward-word 1) as the expression for moving point for-
ward word by word, but it is easier to see what Emacs identifies as a ‘word’
if we use a regular expression search.
A regular expression search that finds the pattern for which it is searching
leaves point after the last character matched. This means that a succession
of successful word searches will move point forward word by word.
As a practical matter, we want the regular expression search to jump
over whitespace and punctuation between words as well as over the words
themselves. A regexp that refuses to jump over interword whitespace would
never jump more than one word! This means that the regexp should include
the whitespace and punctuation that follows a word, if any, as well as the
word itself. (A word may end a buffer and not have any following whitespace
or punctuation, so that part of the regexp must be optional.)
Thus, what we want for the regexp is a pattern defining one or more word
constituent characters followed, optionally, by one or more characters that
are not word constituents. The regular expression for this is:
" 1 0) (89.99563598632812 581.2577514648438 449.3737487792969 630.7874145507812 "\\w+\\W*
The buffer’s syntax table determines which characters are and are not word
constituents. (See Section 14.2, “What Constitutes a Word or Symbol?”,
page 182, for more about syntax. Also, see section “The Syntax Table” in
" 2 0)) (187 (90.0 47.60907745361328 449.5970764160156 60.90726852416992 "The count-words-region Function
169
" 0 0) (90.00030517578125 77.48908233642578 449.3891296386719 102.66727447509766 "The GNU Emacs Manual, and section “Syntax Tables” in The GNU Emacs
Lisp Reference Manual.)
" 1 0) (105.00043487548828 106.28907012939453 281.3239440917969 119.5872573852539 "The search expression looks like this:
" 2 0) (111.60086059570312 127.29769897460938 252.2696990966797 136.2640838623047 "(re-search-forward \"\\\\w+\\\\W*\")
" 3 0) (89.9998779296875 140.129150390625 449.2799072265625 201.30735778808594 "(Note that paired backslashes precede the ‘w’ and ‘W’. A single backslash
has special meaning to the Emacs Lisp interpreter. It indicates that the fol-
lowing character is interpreted differently than usual. For example, the two
characters, ‘\\n’, stand for ‘newline’, rather than for a backslash followed by
‘n’. Two backslashes in a row stand for an ordinary, ‘unspecial’ backslash.)
" 4 0) (89.99981689453125 204.68914794921875 449.4540100097656 241.9873504638672 "We need a counter to count how many words there are; this variable
must first be set to 0 and then incremented each time Emacs goes around
the while loop. The incrementing expression is simply:
" 5 0) (111.60031127929688 249.69766235351562 219.5857391357422 258.6640319824219 "(setq count (1+ count))
" 6 0) (89.99932861328125 262.52911376953125 449.3881530761719 383.4673156738281 "Finally, we want to tell the user how many words there are in the region.
The message function is intended for presenting this kind of information to
the user. The message has to be phrased so that it reads properly regardless
of how many words there are in the region: we don’t want to say that “there
are 1 words in the region”.
The conflict between singular and plural is
ungrammatical. We can solve this problem by using a conditional expression
that evaluates different messages depending on the number of words in the
region. There are three possibilities: no words in the region, one word in the
region, and more than one word. This means that the cond special form is
appropriate.
" 7 0) (104.99945068359375 386.9691162109375 339.7630615234375 400.2673034667969 "All this leads to the following function definition:
" 8 0) (111.59943389892578 408.0952453613281 346.2295227050781 516.6640625 ";;; First version; has bugs!
(defun count-words-region (beginning end)
\"Print number of words in the region.
Words are defined as at least one word-constituent
character followed by at least one character that
is not a word-constituent.
The buffer’s syntax
table determines which characters these are.\"
(interactive \"r\")
(message \"Counting words in region ... \")
" 9 0) (111.59962463378906 524.8552856445312 262.9503173828125 571.1441040039062 ";;; 1. Set up appropriate conditions.
(save-excursion
(goto-char beginning)
(let ((count 0))
" 10 0) (111.5996322631836 579.3352661132812 289.9486083984375 625.6240844726562 ";;; 2. Run the while loop.
(while (< (point) end)
(re-search-forward \"\\\\w+\\\\W*\")
(setq count (1+ count)))
" 11 0)) (188 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "170
Chapter 13: Counting: Repetition and Regexps
" 0 0) (90.00093078613281 81.33521270751953 378.7971496582031 218.4670867919922 ";;; 3. Send a message to the user.
(cond ((zerop count)
(message
\"The region does NOT have any words.\"))
((= 1 count)
(message
\"The region has 1 word.\"))
(t
(message
\"The region has %d words.\" count))))))
As written, the function works, but not in all circumstances.
" 1 0) (90.001220703125 236.16162109375 413.2157897949219 249.2771759033203 "13.1.1 The Whitespace Bug in count-words-region
" 2 0) (90.00115966796875 258.80889892578125 449.40118408203125 343.7471008300781 "The count-words-region command described in the preceding section
has two bugs, or rather, one bug with two manifestations.
First, if you
mark a region containing only whitespace in the middle of some text, the
count-words-region command tells you that the region contains one word!
Second, if you mark a region containing only whitespace at the end of the
buffer or the accessible portion of a narrowed buffer, the command displays
an error message that looks like this:
" 3 0) (90.00106811523438 350.2574462890625 449.4775695800781 417.9071960449219 "Search failed: \"\\\\w+\\\\W*\"
If you are reading this in Info in GNU Emacs, you can test for these bugs
yourself.
First, evaluate the function in the usual manner to install it.
If you wish, you can also install this keybinding by evaluating it:
" 4 0) (89.99972534179688 424.29754638671875 449.35601806640625 473.11602783203125 "(global-set-key \"\\C-c=\" ’count-words-region)
To conduct the first test, set mark and point to the beginning and end of
the following line and then type C-c = (or M-x count-words-region if you
have not bound C-c =):
" 5 0) (89.9996337890625 479.49755859375 449.6614685058594 630.7872314453125 "one
two
three
Emacs will tell you, correctly, that the region has three words.
Repeat the test, but place mark at the beginning of the line and place
point just before the word ‘one’. Again type the command C-c = (or M-x
count-words-region). Emacs should tell you that the region has no words,
since it is composed only of the whitespace at the beginning of the line. But
instead Emacs tells you that the region has one word!
For the third test, copy the sample line to the end of the ‘*scratch*’
buffer and then type several spaces at the end of the line. Place mark right
after the word ‘three’ and point at the end of line. (The end of the line
will be the end of the buffer.) Type C-c = (or M-x count-words-region) as
you did before. Again, Emacs should tell you that the region has no words,
" 6 0)) (189 (90.0 47.60907745361328 449.5201721191406 60.90726852416992 "The Whitespace Bug in count-words-region
171
" 0 0) (89.99606323242188 77.48908233642578 449.4191589355469 465.76971435546875 "since it is composed only of the whitespace at the end of the line. Instead,
Emacs displays an error message saying ‘Search failed’.
The two bugs stem from the same problem.
Consider the first manifestation of the bug, in which the command tells
you that the whitespace at the beginning of the line contains one word.
What happens is this: The M-x count-words-region command moves point
to the beginning of the region. The while tests whether the value of point
is smaller than the value of end, which it is.
Consequently, the regular
expression search looks for and finds the first word. It leaves point after the
word. count is set to one. The while loop repeats; but this time the value
of point is larger than the value of end, the loop is exited; and the function
displays a message saying the number of words in the region is one. In brief,
the regular expression search looks for and finds the word even though it is
outside the marked region.
In the second manifestation of the bug, the region is whitespace at the
end of the buffer. Emacs says ‘Search failed’. What happens is that the
true-or-false-test in the while loop tests true, so the search expression is
executed. But since there are no more words in the buffer, the search fails.
In both manifestations of the bug, the search extends or attempts to
extend outside of the region.
The solution is to limit the search to the region—this is a fairly simple
action, but as you may have come to expect, it is not quite as simple as you
might think.
As we have seen, the re-search-forward function takes a search pattern
as its first argument. But in addition to this first, mandatory argument, it
accepts three optional arguments. The optional second argument bounds the
search. The optional third argument, if t, causes the function to return nil
rather than signal an error if the search fails. The optional fourth argument
is a repeat count. (In Emacs, you can see a function’s documentation by
typing C-h f, the name of the function, and then ⟨
" 1 0) (330.947998046875 449.9919738769531 349.0679931640625 450.47198486328125 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (330.9599914550781 451.2024230957031 349.06011962890625 459.1725158691406 "RET
" 3 0) (330.947998046875 458.5119934082031 349.0679931640625 458.99200439453125 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00009155273438 446.60906982421875 449.54193115234375 511.50726318359375 "⟩.)
In the count-words-region definition, the value of the end of the region
is held by the variable end which is passed as an argument to the func-
tion. Thus, we can add end as an argument to the regular expression search
expression:
" 5 0) (90.00003051757812 518.2576293945312 449.51092529296875 630.787353515625 "(re-search-forward \"\\\\w+\\\\W*\" end)
However, if you make only this change to the count-words-region defini-
tion and then test the new version of the definition on a stretch of whitespace,
you will receive an error message saying ‘Search failed’.
What happens is this: the search is limited to the region, and fails as
you expect because there are no word-constituent characters in the region.
Since it fails, we receive an error message. But we do not want to receive an
error message in this case; we want to receive the message that \"The region
does NOT have any words.\"
" 6 0)) (190 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "172
Chapter 13: Counting: Repetition and Regexps
" 0 0) (89.99862670898438 77.48908233642578 449.9118957519531 403.0272521972656 "The solution to this problem is to provide re-search-forward with a
third argument of t, which causes the function to return nil rather than
signal an error if the search fails.
However, if you make this change and try it, you will see the message
“Counting words in region ... ” and . . . you will keep on seeing that message
. . ., until you type C-g (keyboard-quit).
Here is what happens: the search is limited to the region, as before, and
it fails because there are no word-constituent characters in the region, as
expected. Consequently, the re-search-forward expression returns nil.
It does nothing else. In particular, it does not move point, which it does
as a side effect if it finds the search target. After the re-search-forward
expression returns nil, the next expression in the while loop is evaluated.
This expression increments the count. Then the loop repeats. The true-or-
false-test tests true because the value of point is still less than the value of
end, since the re-search-forward expression did not move point. . . . and
the cycle repeats . . .
The count-words-region definition requires yet another modification,
to cause the true-or-false-test of the while loop to test false if the search
fails. Put another way, there are two conditions that must be satisfied in the
true-or-false-test before the word count variable is incremented: point must
still be within the region and the search expression must have found a word
to count.
Since both the first condition and the second condition must be true
together, the two expressions, the region test and the search expression, can
be joined with an and special form and embedded in the while loop as the
true-or-false-test, like this:
" 1 0) (89.99948120117188 409.4175109863281 449.421630859375 560.46728515625 "(and (< (point) end) (re-search-forward \"\\\\w+\\\\W*\" end t))
(For information about and, see Section 12.4, “forward-paragraph: a Gold-
mine of Functions”, page 155.)
The re-search-forward expression returns t if the search succeeds and
as a side effect moves point.
Consequently, as words are found, point is
moved through the region. When the search expression fails to find another
word, or when point reaches the end of the region, the true-or-false-test tests
false, the while loop exists, and the count-words-region function displays
one or other of its messages.
After incorporating these final changes, the count-words-region works
without bugs (or at least, without bugs that I have found!). Here is what it
looks like:
" 2 0) (111.6004409790039 566.8551635742188 313.65875244140625 625.6240234375 ";;; Final version: while
(defun count-words-region (beginning end)
\"Print number of words in the region.\"
(interactive \"r\")
(message \"Counting words in region ... \")
" 3 0)) (191 (90.0 47.60907745361328 449.68341064453125 60.90726852416992 "Count Words Recursively
173
" 0 0) (111.59963989257812 81.33521270751953 262.9503173828125 127.62394714355469 ";;; 1. Set up appropriate conditions.
(save-excursion
(let ((count 0))
(goto-char beginning)
" 1 0) (111.599609375 135.81512451171875 370.1859130859375 182.10386657714844 ";;; 2. Run the while loop.
(while (and (< (point) end)
(re-search-forward \"\\\\w+\\\\W*\" end t))
(setq count (1+ count)))
" 2 0) (111.59981536865234 190.2950439453125 360.594482421875 311.3436584472656 ";;; 3. Send a message to the user.
(cond ((zerop count)
(message
\"The region does NOT have any words.\"))
((= 1 count)
(message
\"The region has 1 word.\"))
(t
(message
\"The region has %d words.\" count))))))
" 3 0) (90.00080871582031 352.46002197265625 307.4132995605469 366.820556640625 "13.2 Count Words Recursively
" 4 0) (90.00100708007812 380.96875 449.291748046875 406.1469421386719 "You can write the function for counting words recursively as well as with
a while loop. Let’s see how this is done.
" 5 0) (90.00167846679688 413.1287536621094 449.3470764160156 462.30694580078125 "First, we need to recognize that the count-words-region function has
three jobs: it sets up the appropriate conditions for counting to occur; it
counts the words in the region; and it sends a message to the user telling
how many words there are.
" 6 0) (90.001708984375 469.28875732421875 449.3692932128906 542.3469848632812 "If we write a single recursive function to do everything, we will receive
a message for every recursive call. If the region contains 13 words, we will
receive thirteen messages, one right after the other. We don’t want this!
Instead, we must write two functions to do the job, one of which (the recur-
sive function) will be used inside of the other. One function will set up the
conditions and display the message; the other will return the word count.
" 7 0) (90.00103759765625 549.3287353515625 449.28094482421875 574.626953125 "Let us start with the function that causes the message to be displayed.
We can continue to call this count-words-region.
" 8 0) (90.00042724609375 581.6087646484375 449.4657287597656 630.7869873046875 "This is the function that the user will call. It will be interactive. Indeed,
it will be similar to our previous versions of this function, except that it
will call recursive-count-words to determine how many words are in the
region.
" 9 0)) (192 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "174
Chapter 13: Counting: Repetition and Regexps
" 0 0) (89.99954223632812 92.96906280517578 449.3885498046875 118.26725006103516 "We can readily construct a template for this function, based on our pre-
vious versions:
" 1 0) (111.59953308105469 136.65521240234375 321.160400390625 182.94395446777344 ";; Recursive version; uses regular expression search
(defun count-words-region (beginning end)
\"documentation...\"
(interactive-expression...)
" 2 0) (111.60049438476562 200.01513671875 262.951171875 233.8238983154297 ";;; 1. Set up appropriate conditions.
(explanatory message)
(set-up functions...
" 3 0) (111.60102844238281 250.77508544921875 210.19813537597656 272.2214660644531 ";;; 2. Count the words.
recursive call
" 4 0) (111.60116577148438 289.175048828125 261.52764892578125 310.6238098144531 ";;; 3. Send a message to the user.
message providing word count))
" 5 0) (90.001708984375 325.4089050292969 449.4017333984375 398.58709716796875 "The definition looks straightforward, except that somehow the count re-
turned by the recursive call must be passed to the message displaying the
word count. A little thought suggests that this can be done by making use
of a let expression: we can bind a variable in the varlist of a let expression
to the number of words in the region, as returned by the recursive call; and
then the cond expression, using binding, can display the value to the user.
" 6 0) (90.00112915039062 412.64892578125 449.3790588378906 461.8271179199219 "Often, one thinks of the binding within a let expression as somehow
secondary to the ‘primary’ work of a function. But in this case, what you
might consider the ‘primary’ job of the function, counting words, is done
within the let expression.
" 7 0) (105.00102233886719 476.0089416503906 337.61541748046875 489.30712890625 "Using let, the function definition looks like this:
" 8 0) (111.60133361816406 507.6974792480469 304.15350341796875 541.50390625 "(defun count-words-region (beginning end)
\"Print number of words in the region.\"
(interactive \"r\")
" 9 0) (111.60213470458984 549.695068359375 313.6596374511719 595.98388671875 ";;; 1. Set up appropriate conditions.
(message \"Counting words in region ... \")
(save-excursion
(goto-char beginning)
" 10 0) (111.60181427001953 604.1751098632812 327.6658935546875 625.6239013671875 ";;; 2. Count the words.
(let ((count (recursive-count-words end)))
" 11 0)) (193 (90.0 47.60907745361328 449.68341064453125 60.90726852416992 "Count Words Recursively
175
" 0 0) (89.99911499023438 81.33521270751953 449.5313720703125 488.2272033691406 ";;; 3. Send a message to the user.
(cond ((zerop count)
(message
\"The region does NOT have any words.\"))
((= 1 count)
(message
\"The region has 1 word.\"))
(t
(message
\"The region has %d words.\" count))))))
Next, we need to write the recursive counting function.
A recursive function has at least three parts: the ‘do-again-test’, the
‘next-step-expression’, and the recursive call.
The do-again-test determines whether the function will or will not be
called again. Since we are counting words in a region and can use a function
that moves point forward for every word, the do-again-test can check whether
point is still within the region. The do-again-test should find the value of
point and determine whether point is before, at, or after the value of the
end of the region. We can use the point function to locate point. Clearly,
we must pass the value of the end of the region to the recursive counting
function as an argument.
In addition, the do-again-test should also test whether the search finds a
word. If it does not, the function should not call itself again.
The next-step-expression changes a value so that when the recursive func-
tion is supposed to stop calling itself, it stops. More precisely, the next-step-
expression changes a value so that at the right time, the do-again-test stops
the recursive function from calling itself again. In this case, the next-step-
expression can be the expression that moves point forward, word by word.
The third part of a recursive function is the recursive call.
Somewhere, also, we also need a part that does the ‘work’ of the function,
a part that does the counting. A vital part!
But already, we have an outline of the recursive counting function:
" 1 0) (89.998291015625 494.0175476074219 449.3875732421875 630.7872314453125 "(defun recursive-count-words (region-end)
\"documentation...\"
do-again-test
next-step-expression
recursive call)
Now we need to fill in the slots. Let’s start with the simplest cases first:
if point is at or beyond the end of the region, there cannot be any words in
the region, so the function should return zero. Likewise, if the search fails,
there are no words to count, so the function should return zero.
On the other hand, if point is within the region and the search succeeds,
the function should call itself again.
" 2 0)) (194 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "176
Chapter 13: Counting: Repetition and Regexps
" 0 0) (104.99993896484375 80.72907257080078 318.44720458984375 94.02725982666016 "Thus, the do-again-test should look like this:
" 1 0) (90.00039672851562 100.05758666992188 449.7181396484375 365.1073303222656 "(and (< (point) region-end)
(re-search-forward \"\\\\w+\\\\W*\" region-end t))
Note that the search expression is part of the do-again-test—the function
returns t if its search succeeds and nil if it fails. (See Section 13.1.1, “The
Whitespace Bug in count-words-region”, page 170, for an explanation of
how re-search-forward works.)
The do-again-test is the true-or-false test of an if clause.
Clearly, if
the do-again-test succeeds, the then-part of the if clause should call the
function again; but if it fails, the else-part should return zero since either
point is outside the region or the search failed because there were no words
to find.
But before considering the recursive call, we need to consider the next-
step-expression. What is it? Interestingly, it is the search part of the do-
again-test.
In addition to returning t or nil for the do-again-test, re-search-
forward moves point forward as a side effect of a successful search. This is
the action that changes the value of point so that the recursive function stops
calling itself when point completes its movement through the region. Con-
sequently, the re-search-forward expression is the next-step-expression.
In outline, then, the body of the recursive-count-words function looks
like this:
" 2 0) (90.0035400390625 371.2552795410156 449.5339660644531 630.787353515625 "(if do-again-test-and-next-step-combined
;; then
recursive-call-returning-count
;; else
return-zero)
How to incorporate the mechanism that counts?
If you are not used to writing recursive functions, a question like this can
be troublesome. But it can and should be approached systematically.
We know that the counting mechanism should be associated in some
way with the recursive call. Indeed, since the next-step-expression moves
point forward by one word, and since a recursive call is made for each word,
the counting mechanism must be an expression that adds one to the value
returned by a call to recursive-count-words.
Consider several cases:
• If there are two words in the region, the function should return a value
resulting from adding one to the value returned when it counts the first
word, plus the number returned when it counts the remaining words in
the region, which in this case is one.
• If there is one word in the region, the function should return a value
resulting from adding one to the value returned when it counts that
" 3 0)) (195 (90.0 47.60907745361328 449.68341064453125 60.90726852416992 "Count Words Recursively
177
" 0 0) (98.99937438964844 77.48908233642578 449.3337707519531 125.29273986816406 "word, plus the number returned when it counts the remaining words in
the region, which in this case is zero.
• If there are no words in the region, the function should return zero.
" 1 0) (89.99850463867188 121.16907501220703 449.4313049316406 196.3872528076172 "From the sketch we can see that the else-part of the if returns zero for
the case of no words. This means that the then-part of the if must return
a value resulting from adding one to the value returned from a count of the
remaining words.
The expression will look like this, where 1+ is a function that adds one
to its argument.
" 2 0) (104.99900817871094 201.33761596679688 434.04974365234375 224.82725524902344 "(1+ (recursive-count-words region-end))
The whole recursive-count-words function will then look like this:
" 3 0) (111.59866333007812 229.89761352539062 304.02215576171875 251.22398376464844 "(defun recursive-count-words (region-end)
\"documentation...\"
" 4 0) (111.59858703613281 267.2152099609375 370.12518310546875 301.0239562988281 ";;; 1. do-again-test
(if (and (< (point) region-end)
(re-search-forward \"\\\\w+\\\\W*\" region-end t))
" 5 0) (111.59889221191406 309.21514892578125 322.8799743652344 330.6639099121094 ";;; 2. then-part: the recursive call
(1+ (recursive-count-words region-end))
" 6 0) (89.99563598632812 346.6551208496094 449.6683044433594 630.7872314453125 ";;; 3. else-part
0))
Let’s examine how this works:
If there are no words in the region, the else part of the if expression is
evaluated and consequently the function returns zero.
If there is one word in the region, the value of point is less than the value
of region-end and the search succeeds. In this case, the true-or-false-test
of the if expression tests true, and the then-part of the if expression is
evaluated. The counting expression is evaluated. This expression returns a
value (which will be the value returned by the whole function) that is the
sum of one added to the value returned by a recursive call.
Meanwhile, the next-step-expression has caused point to jump over the
first (and in this case only) word in the region.
This means that when
(recursive-count-words region-end) is evaluated a second time, as a
result of the recursive call, the value of point will be equal to or greater
than the value of region end. So this time, recursive-count-words will
return zero. The zero will be added to one, and the original evaluation of
recursive-count-words will return one plus zero, which is one, which is
the correct amount.
Clearly, if there are two words in the region, the first call to recursive-
count-words returns one added to the value returned by calling recursive-
count-words on a region containing the remaining word—that is, it adds
one to one, producing two, which is the correct amount.
" 7 0)) (196 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "178
Chapter 13: Counting: Repetition and Regexps
" 0 0) (90.00015258789062 77.48908233642578 449.454833984375 126.66727447509766 "Similarly, if there are three words in the region, the first call to
recursive-count-words returns one added to the value returned by calling
recursive-count-words on a region containing the remaining two words—
and so on and so on.
" 1 0) (90.00039672851562 140.72906494140625 362.0294189453125 154.0272674560547 "With full documentation the two functions look like this:
" 2 0) (90.00033569335938 168.08905029296875 199.9748077392578 181.3872528076172 "The recursive function:
" 3 0) (111.6003189086914 199.65756225585938 341.56671142578125 220.9839324951172 "(defun recursive-count-words (region-end)
\"Number of words between point and REGION-END.\"
" 4 0) (111.60011291503906 229.17510986328125 370.126708984375 263.1038513183594 ";;; 1. do-again-test
(if (and (< (point) region-end)
(re-search-forward \"\\\\w+\\\\W*\" region-end t))
" 5 0) (111.60041809082031 271.175048828125 322.8815002441406 292.6238098144531 ";;; 2. then-part: the recursive call
(1+ (recursive-count-words region-end))
" 6 0) (111.60090637207031 308.61505126953125 174.8882598876953 330.0638122558594 ";;; 3. else-part
0))
" 7 0) (90.00100708007812 345.68890380859375 154.72451782226562 358.9870910644531 "The wrapper:
" 8 0) (111.6008529663086 377.2550354003906 304.15301513671875 411.183837890625 ";;; Recursive version
(defun count-words-region (beginning end)
\"Print number of words in the region.
" 9 0) (111.60128784179688 419.2574768066406 355.9421081542969 528.9039306640625 "Words are defined as at least one word-constituent
character followed by at least one character that is
not a word-constituent.
The buffer’s syntax table
determines which characters these are.\"
(interactive \"r\")
(message \"Counting words in region ... \")
(save-excursion
(goto-char beginning)
(let ((count (recursive-count-words end)))
" 10 0) (139.8018035888672 533.49755859375 360.59637451171875 567.303955078125 "(cond ((zerop count)
(message
\"The region does NOT have any words.\"))
" 11 0) (168.12220764160156 571.8975219726562 355.7972106933594 630.6639404296875 "((= 1 count)
(message \"The region has 1 word.\"))
(t
(message
\"The region has %d words.\" count))))))
" 12 0)) (197 (90.0 47.60907745361328 449.6072692871094 60.90726852416992 "Exercise: Counting Punctuation
179
" 0 0) (89.99951171875 77.30034637451172 354.9492492675781 91.66089630126953 "13.3 Exercise: Counting Punctuation
" 1 0) (89.9998779296875 99.32910919189453 449.3885498046875 136.62730407714844 "Using a while loop, write a function to count the number of punctuation
marks in a region—period, comma, semicolon, colon, exclamation mark, and
question mark. Do the same using recursion.
" 2 0)) (198 (90.0 47.60907745361328 449.4106750488281 60.90726852416992 "180
Chapter 13: Counting: Repetition and Regexps
" 0 0)) (199 (90.0 47.60907745361328 449.7816467285156 60.90726852416992 "What to Count?
181
" 0 0) (89.9998779296875 75.14844512939453 346.95648193359375 92.39627838134766 "14 Counting Words in a defun
" 1 0) (89.9971923828125 101.00910186767578 449.55023193359375 445.50732421875 "Our next project is to count the number of words in a function definition.
Clearly, this can be done using some variant of count-word-region. See
Chapter 13, “Counting Words: Repetition and Regexps”, page 167. If we
are just going to count the words in one definition, it is easy enough to
mark the definition with the C-M-h (mark-defun) command, and then call
count-word-region.
However, I am more ambitious: I want to count the words and symbols
in every definition in the Emacs sources and then print a graph that shows
how many functions there are of each length: how many contain 40 to 49
words or symbols, how many contain 50 to 59 words or symbols, and so on.
I have often been curious how long a typical function is, and this will tell.
Described in one phrase, the histogram project is daunting; but divided
into numerous small steps, each of which we can take one at a time, the
project becomes less fearsome. Let us consider what the steps must be:
• First, write a function to count the words in one definition. This includes
the problem of handling symbols as well as words.
• Second, write a function to list the numbers of words in each function
in a file. This function can use the count-words-in-defun function.
• Third, write a function to list the numbers of words in each function
in each of several files. This entails automatically finding the various
files, switching to them, and counting the words in the definitions within
them.
• Fourth, write a function to convert the list of numbers that we created
in step three to a form that will be suitable for printing as a graph.
• Fifth, write a function to print the results as a graph.
This is quite a project! But if we take each step slowly, it will not be
difficult.
" 2 0) (89.99758911132812 460.7004089355469 242.57705688476562 475.0609436035156 "14.1 What to Count?
" 3 0) (89.99746704101562 482.84912109375 449.5504150390625 591.787353515625 "When we first start thinking about how to count the words in a function
definition, the first question is (or ought to be) what are we going to count?
When we speak of ‘words’ with respect to a Lisp function definition, we are
actually speaking, in large part, of ‘symbols’. For example, the following
multiply-by-seven function contains the five symbols defun, multiply-
by-seven, number, *, and 7. In addition, in the documentation string, it
contains the four words ‘Multiply’, ‘NUMBER’, ‘by’, and ‘seven’. The symbol
‘number’ is repeated, so the definition contains a total of ten words and
symbols.
" 4 0) (111.59752655029297 596.7377319335938 266.529296875 630.6640625 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
" 5 0)) (200 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "182
Chapter 14: Counting Words in a defun
" 0 0) (90.000244140625 77.48908233642578 449.5642395019531 126.66727447509766 "However, if we mark the multiply-by-seven definition with C-M-h (mark-
defun), and then call count-words-region on it, we will find that count-
words-region claims the definition has eleven words, not ten! Something is
wrong!
" 1 0) (90.0001220703125 129.9290771484375 449.357177734375 190.98728942871094 "The problem is twofold: count-words-region does not count the ‘*’ as
a word, and it counts the single symbol, multiply-by-seven, as containing
three words. The hyphens are treated as if they were interword spaces rather
than intraword connectors: ‘multiply-by-seven’ is counted as if it were
written ‘multiply by seven’.
" 2 0) (90.00003051757812 194.24908447265625 449.41119384765625 231.5472869873047 "The cause of this confusion is the regular expression search within the
count-words-region definition that moves point forward word by word. In
the canonical version of count-words-region, the regexp is:
" 3 0) (111.60128784179688 239.13760375976562 158.3519744873047 248.10398864746094 "\"\\\\w+\\\\W*\"
" 4 0) (90.00115966796875 251.84906005859375 449.29180908203125 301.0272521972656 "This regular expression is a pattern defining one or more word constituent
characters possibly followed by one or more characters that are not word
constituents. What is meant by ‘word constituent characters’ brings us to
the issue of syntax, which is worth a section of its own.
" 5 0) (90.00103759765625 327.8603515625 395.8272705078125 342.22088623046875 "14.2 What Constitutes a Word or Symbol?
" 6 0) (90.00045776367188 352.5290832519531 449.36773681640625 461.46728515625 "Emacs treats different characters as belonging to different syntax cate-
gories. For example, the regular expression, ‘\\\\w+’, is a pattern specifying
one or more word constituent characters. Word constituent characters are
members of one syntax category. Other syntax categories include the class
of punctuation characters, such as the period and the comma, and the class
of whitespace characters, such as the blank space and the tab character.
(For more information, see section “The Syntax Table” in The GNU Emacs
Manual, and section “Syntax Tables” in The GNU Emacs Lisp Reference
Manual.)
" 7 0) (89.9990234375 464.7290954589844 449.37738037109375 537.9073486328125 "Syntax tables specify which characters belong to which categories. Usu-
ally, a hyphen is not specified as a ‘word constituent character’. Instead,
it is specified as being in the ‘class of characters that are part of symbol
names but not words.’ This means that the count-words-region function
treats it in the same way it treats an interword white space, which is why
count-words-region counts ‘multiply-by-seven’ as three words.
" 8 0) (89.99856567382812 541.1690673828125 449.3878479003906 566.3472900390625 "There are two ways to cause Emacs to count ‘multiply-by-seven’ as
one symbol: modify the syntax table or modify the regular expression.
" 9 0) (89.99810791015625 569.609130859375 449.540283203125 630.787353515625 "We could redefine a hyphen as a word constituent character by modifying
the syntax table that Emacs keeps for each mode. This action would serve
our purpose, except that a hyphen is merely the most common character
within symbols that is not typically a word constituent character; there are
others, too.
" 10 0)) (201 (90.0 47.60907745361328 449.5750427246094 60.90726852416992 "The count-words-in-defun Function
183
" 0 0) (90.00003051757812 77.48908233642578 449.5527038574219 141.3072967529297 "Alternatively, we can redefine the regular expression used in the count-
words definition so as to include symbols. This procedure has the merit of
clarity, but the task is a little tricky.
The first part is simple enough: the pattern must match “at least one
character that is a word or symbol constituent”. Thus:
" 1 0) (89.99988555908203 146.97763061523438 449.4879455566406 281.2273254394531 "\"\\\\(\\\\w\\\\|\\\\s_\\\\)+\"
The ‘\\\\(’ is the first part of the grouping construct that includes the ‘\\\\w’
and the ‘\\\\s_’ as alternatives, separated by the ‘\\\\|’. The ‘\\\\w’ matches any
word-constituent character and the ‘\\\\s_’ matches any character that is part
of a symbol name but not a word-constituent character. The ‘+’ following
the group indicates that the word or symbol constituent characters must be
matched at least once.
However, the second part of the regexp is more difficult to design. What
we want is to follow the first part with “optionally one or more characters
that are not constituents of a word or symbol”. At first, I thought I could
define this with the following:
" 2 0) (89.99884033203125 286.8976745605469 449.411376953125 459.7873840332031 "\"\\\\(\\\\W\\\\|\\\\S_\\\\)*\"
The upper case ‘W’ and ‘S’ match characters that are not word or symbol
constituents. Unfortunately, this expression matches any character that is
either not a word constituent or not a symbol constituent. This matches any
character!
I then noticed that every word or symbol in my test region was followed
by white space (blank space, tab, or newline). So I tried placing a pattern
to match one or more blank spaces after the pattern for one or more word
or symbol constituents.
This failed, too.
Words and symbols are often
separated by whitespace, but in actual code parentheses may follow symbols
and punctuation may follow words. So finally, I designed a pattern in which
the word or symbol constituents are followed optionally by characters that
are not white space and then followed optionally by white space.
Here is the full regular expression:
" 3 0) (111.59983825683594 465.3377380371094 280.6660461425781 474.3041076660156 "\"\\\\(\\\\w\\\\|\\\\s_\\\\)+[^ \\t\\n]*[ \\t\\n]*\"
" 4 0) (89.99984741210938 493.8204650878906 374.2123107910156 508.1936950683594 "14.3 The count-words-in-defun Function
" 5 0) (89.999755859375 516.5692138671875 449.9452209472656 630.7874145507812 "We have seen that there are several ways to write a count-word-region
function. To write a count-words-in-defun, we need merely adapt one of
these versions.
The version that uses a while loop is easy to understand, so I am going to
adapt that. Because count-words-in-defun will be part of a more complex
program, it need not be interactive and it need not display a message but
just return the count. These considerations simplify the definition a little.
On the other hand, count-words-in-defun will be used within a buffer
that contains function definitions. Consequently, it is reasonable to ask that
" 6 0)) (202 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "184
Chapter 14: Counting Words in a defun
" 0 0) (89.99954223632812 77.48908233642578 449.4430236816406 141.1873016357422 "the function determine whether it is called when point is within a function
definition, and if it is, to return the count for that definition. This adds
complexity to the definition, but saves us from needing to pass arguments
to the function.
These considerations lead us to prepare the following template:
" 1 0) (89.99893188476562 146.85763549804688 449.4325866699219 513.7872924804688 "(defun count-words-in-defun ()
\"documentation...\"
(set up...
(while loop...)
return count)
As usual, our job is to fill in the slots.
First, the set up.
We are presuming that this function will be called within a buffer con-
taining function definitions. Point will either be within a function definition
or not. For count-words-in-defun to work, point must move to the begin-
ning of the definition, a counter must start at zero, and the counting loop
must stop when point reaches the end of the definition.
The beginning-of-defun function searches backwards for an opening
delimiter such as a ‘(’ at the beginning of a line, and moves point to that
position, or else to the limit of the search.
In practice, this means that
beginning-of-defun moves point to the beginning of an enclosing or pre-
ceding function definition, or else to the beginning of the buffer. We can use
beginning-of-defun to place point where we wish to start.
The while loop requires a counter to keep track of the words or symbols
being counted. A let expression can be used to create a local variable for
this purpose, and bind it to an initial value of zero.
The end-of-defun function works like beginning-of-defun except that
it moves point to the end of the definition. end-of-defun can be used as part
of an expression that determines the position of the end of the definition.
The set up for count-words-in-defun takes shape rapidly: first we move
point to the beginning of the definition, then we create a local variable to
hold the count, and finally, we record the position of the end of the definition
so the while loop will know when to stop looping.
The code looks like this:
" 2 0) (89.99728393554688 519.3377075195312 449.8126220703125 630.787353515625 "(beginning-of-defun)
(let ((count 0)
(end (save-excursion (end-of-defun) (point))))
The code is simple. The only slight complication is likely to concern end: it
is bound to the position of the end of the definition by a save-excursion
expression that returns the value of point after end-of-defun temporarily
moves it to the end of the definition.
The second part of the count-words-in-defun, after the set up, is the
while loop.
" 3 0)) (203 (90.0 47.60907745361328 449.5750427246094 60.90726852416992 "The count-words-in-defun Function
185
" 0 0) (89.99972534179688 77.48908233642578 449.4979248046875 150.5472869873047 "The loop must contain an expression that jumps point forward word by
word and symbol by symbol, and another expression that counts the jumps.
The true-or-false-test for the while loop should test true so long as point
should jump forward, and false when point is at the end of the definition.
We have already redefined the regular expression for this (see Section 14.2,
“Syntax”, page 182), so the loop is straightforward:
" 1 0) (111.59980773925781 161.25759887695312 374.82330322265625 207.54393005371094 "(while (and (< (point) end)
(re-search-forward
\"\\\\(\\\\w\\\\|\\\\s_\\\\)+[^ \\t\\n]*[ \\t\\n]*\" end t)
(setq count (1+ count)))
" 2 0) (89.9989013671875 214.64898681640625 449.4320068359375 263.7071838378906 "The third part of the function definition returns the count of words and
symbols. This part is the last expression within the body of the let expres-
sion, and can be, very simply, the local variable count, which when evaluated
returns the count.
" 3 0) (104.99899291992188 270.208984375 425.88995361328125 283.5071716308594 "Put together, the count-words-in-defun definition looks like this:
" 4 0) (111.598876953125 294.2174987792969 365.3086853027344 441.18414306640625 "(defun count-words-in-defun ()
\"Return the number of words and symbols in a defun.\"
(beginning-of-defun)
(let ((count 0)
(end (save-excursion (end-of-defun) (point))))
(while
(and (< (point) end)
(re-search-forward
\"\\\\(\\\\w\\\\|\\\\s_\\\\)+[^ \\t\\n]*[ \\t\\n]*\"
end t))
(setq count (1+ count)))
count))
" 5 0) (89.99868774414062 448.1692199707031 449.4203186035156 485.4674072265625 "How to test this? The function is not interactive, but it is easy to put a
wrapper around the function to make it interactive; we can use almost the
same code as for the recursive version of count-words-region:
" 6 0) (111.59860229492188 496.05535888671875 393.57659912109375 567.30419921875 ";;; Interactive version.
(defun count-words-defun ()
\"Number of words and symbols in a function definition.\"
(interactive)
(message
\"Counting words and symbols in function definition ... \")
" 7 0) (120.95877075195312 571.8978271484375 398.04248046875 630.6641845703125 "(let ((count (count-words-in-defun)))
(cond
((zerop count)
(message
\"The definition does NOT have any words or symbols.\"))
" 8 0)) (204 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "186
Chapter 14: Counting Words in a defun
" 0 0) (90.00007629394531 81.33761596679688 388.6927185058594 168.67596435546875 "((= 1 count)
(message
\"The definition has 1 word or symbol.\"))
(t
(message
\"The definition has %d words or symbols.\" count)))))
Let’s re-use C-c = as a convenient keybinding:
" 1 0) (89.99951171875 174.21749877929688 449.8251953125 222.0671844482422 "(global-set-key \"\\C-c=\" ’count-words-defun)
Now we can try out count-words-defun: install both count-words-in-
defun and count-words-defun, and set the keybinding, and then place the
cursor within the following definition:
" 2 0) (89.99911499023438 227.49752807617188 449.27911376953125 315.4271545410156 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
⇒ 10
Success! The definition has 10 words and symbols.
The next problem is to count the numbers of words and symbols in several
definitions within a single file.
" 3 0) (89.99908447265625 333.8602600097656 375.99884033203125 348.2334899902344 "14.4 Count Several defuns Within a File
" 4 0) (89.99578857421875 356.4889831542969 449.51934814453125 630.7872314453125 "A file such as ‘simple.el’ may have 80 or more function definitions within
it. Our long term goal is to collect statistics on many files, but as a first
step, our immediate goal is to collect statistics on one file.
The information will be a series of numbers, each number being the length
of a function definition. We can store the numbers in a list.
We know that we will want to incorporate the information regarding one
file with information about many other files; this means that the function
for counting definition lengths within one file need only return the list of
lengths. It need not and should not display any messages.
The word count commands contain one expression to jump point forward
word by word and another expression to count the jumps. The function to
return the lengths of definitions can be designed to work the same way, with
one expression to jump point forward definition by definition and another
expression to construct the lengths’ list.
This statement of the problem makes it elementary to write the function
definition. Clearly, we will start the count at the beginning of the file, so
the first command will be (goto-char (point-min)). Next, we start the
while loop; and the true-or-false test of the loop can be a regular expression
search for the next function definition—so long as the search succeeds, point
is moved forward and then the body of the loop is evaluated. The body needs
an expression that constructs the lengths’ list. cons, the list construction
command, can be used to create the list. That is almost all there is to it.
" 5 0)) (205 (90.0 47.60907745361328 449.6398620605469 60.90726852416992 "lengths-list-file in Detail
187
" 0 0) (105.00009155273438 80.60907745361328 320.62896728515625 93.90726470947266 "Here is what this fragment of code looks like:
" 1 0) (90.00112915039062 100.05758666992188 449.3138732910156 216.1871795654297 "(goto-char (point-min))
(while (re-search-forward \"^(defun\" nil t)
(setq lengths-list
(cons (count-words-in-defun) lengths-list)))
What we have left out is the mechanism for finding the file that contains
the function definitions.
In previous examples, we either used this, the Info file, or we switched
back and forth to some other buffer, such as the ‘*scratch*’ buffer.
Finding a file is a new process that we have not yet discussed.
" 2 0) (90.00173950195312 237.020263671875 204.30682373046875 251.38079833984375 "14.5 Find a File
" 3 0) (90.00192260742188 260.24896240234375 449.5104064941406 313.1558837890625 "To find a file in Emacs, you use the C-x C-f (find-file) command. This
command is almost, but not quite right for the lengths problem.
Let’s look at the source for find-file (you can use the find-tag com-
mand or C-h f (describe-function) to find the source of a function):
" 4 0) (90.001220703125 319.2973937988281 449.6739196777344 630.7869873046875 "(defun find-file (filename)
\"Edit file FILENAME.
Switch to a buffer visiting file FILENAME,
creating one if none already exists.\"
(interactive \"FFind file: \")
(switch-to-buffer (find-file-noselect filename)))
The definition possesses short but complete documentation and an in-
teractive specification that prompts you for a file name when you use the
command interactively. The body of the definition contains two functions,
find-file-noselect and switch-to-buffer.
According to its documentation as shown by C-h f (the describe-
function command), the find-file-noselect function reads the named
file into a buffer and returns the buffer. However, the buffer is not selected.
Emacs does not switch its attention (or yours if you are using find-file-
noselect) to the named buffer. That is what switch-to-buffer does: it
switches the buffer to which Emacs attention is directed; and it switches the
buffer displayed in the window to the new buffer. We have discussed buffer
switching elsewhere. (See Section 2.3, “Switching Buffers”, page 26.)
In this histogram project, we do not need to display each file on the
screen as the program determines the length of each definition within it.
Instead of employing switch-to-buffer, we can work with set-buffer,
which redirects the attention of the computer program to a different buffer
but does not redisplay it on the screen. So instead of calling on find-file
to do the job, we must write our own expression.
The task is easy: use find-file-noselect and set-buffer.
" 5 0)) (206 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "188
Chapter 14: Counting Words in a defun
" 0 0) (90.000244140625 77.30034637451172 318.9039611816406 91.67356872558594 "14.6 lengths-list-file in Detail
" 1 0) (90.00003051757812 100.16907501220703 449.5526123046875 173.22727966308594 "The core of the lengths-list-file function is a while loop containing
a function to move point forward ‘defun by defun’ and a function to count
the number of words and symbols in each defun. This core must be sur-
rounded by functions that do various other tasks, including finding the file,
and ensuring that point starts out at the beginning of the file. The function
definition looks like this:
" 2 0) (89.9979248046875 179.13760375976562 449.4315490722656 630.7874145507812 "(defun lengths-list-file (filename)
\"Return list of definitions’ lengths within FILE.
The returned list is a list of numbers.
Each number is the number of words or
symbols in one function definition.\"
(message \"Working on ‘%s’ ... \" filename)
(save-excursion
(let ((buffer (find-file-noselect filename))
(lengths-list))
(set-buffer buffer)
(setq buffer-read-only t)
(widen)
(goto-char (point-min))
(while (re-search-forward \"^(defun\" nil t)
(setq lengths-list
(cons (count-words-in-defun) lengths-list)))
(kill-buffer buffer)
lengths-list)))
The function is passed one argument, the name of the file on which it will
work. It has four lines of documentation, but no interactive specification.
Since people worry that a computer is broken if they don’t see anything
going on, the first line of the body is a message.
The next line contains a save-excursion that returns Emacs’ attention
to the current buffer when the function completes. This is useful in case you
embed this function in another function that presumes point is restored to
the original buffer.
In the varlist of the let expression, Emacs finds the file and binds the
local variable buffer to the buffer containing the file. At the same time,
Emacs creates lengths-list as a local variable.
Next, Emacs switches its attention to the buffer.
In the following line, Emacs makes the buffer read-only. Ideally, this line
is not necessary. None of the functions for counting words and symbols in a
function definition should change the buffer. Besides, the buffer is not going
to be saved, even if it were changed. This line is entirely the consequence
of great, perhaps excessive, caution. The reason for the caution is that this
function and those it calls work on the sources for Emacs and it is very
" 3 0)) (207 (90.0 47.60907745361328 449.6398620605469 60.90726852416992 "lengths-list-file in Detail
189
" 0 0) (90.00009155273438 77.48908233642578 449.44384765625 114.66727447509766 "inconvenient if they are inadvertently modified. It goes without saying that
I did not realize a need for this line until an experiment went awry and
started to modify my Emacs source files . . .
" 1 0) (89.9984130859375 119.60907745361328 449.4205322265625 192.6672821044922 "Next comes a call to widen the buffer if it is narrowed. This function
is usually not needed—Emacs creates a fresh buffer if none already exists;
but if a buffer visiting the file already exists Emacs returns that one. In
this case, the buffer may be narrowed and must be widened. If we wanted
to be fully ‘user-friendly’, we would arrange to save the restriction and the
location of point, but we won’t.
" 2 0) (89.99905395507812 197.60906982421875 449.5403137207031 222.7872772216797 "The (goto-char (point-min)) expression moves point to the beginning
of the buffer.
" 3 0) (89.99887084960938 227.72906494140625 449.3111267089844 264.9072570800781 "Then comes a while loop in which the ‘work’ of the function is carried out.
In the loop, Emacs determines the length of each definition and constructs
a lengths’ list containing the information.
" 4 0) (89.9989013671875 269.84906005859375 449.3553771972656 319.0272521972656 "Emacs kills the buffer after working through it. This is to save space
inside of Emacs. My version of Emacs 19 contained over 300 source files
of interest; Emacs 21 contains over 800 source files. Another function will
apply lengths-list-file to each of the files.
" 5 0) (89.99887084960938 323.84906005859375 449.6390686035156 349.1472473144531 "Finally, the last expression within the let expression is the lengths-list
variable; its value is returned as the value of the whole function.
" 6 0) (89.99868774414062 354.08905029296875 449.5509338378906 391.2672424316406 "You can try this function by installing it in the usual fashion. Then place
your cursor after the following expression and type C-x C-e (eval-last-
sexp).
" 7 0) (111.59893798828125 400.53759765625 392.7716064453125 421.9839782714844 "(lengths-list-file
\"/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el\")
" 8 0) (89.99807739257812 427.2890625 449.38690185546875 464.5872497558594 "(You may need to change the pathname of the file; the one here worked
with GNU Emacs version 21.0.100. To change the expression, copy it to the
‘*scratch*’ buffer and edit it.
" 9 0) (89.99794006347656 470.1290588378906 449.24462890625 495.42724609375 "(Also, to see the full length of the list, rather than a truncated version, you
may have to evaluate the following:
" 10 0) (111.5982894897461 504.6976013183594 384.03692626953125 513.6640014648438 "(custom-set-variables ’(eval-expression-print-length nil))
" 11 0) (89.9974365234375 518.9690551757812 449.419189453125 544.2672729492188 "(See Section 16.2, “Setting Variables with defcustom”, page 214.
Then
evaluate the lengths-list-file expression.)
" 12 0)) (208 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "190
Chapter 14: Counting Words in a defun
" 0 0) (90.000244140625 77.48908233642578 449.4219055175781 102.66727447509766 "The lengths’ list for ‘debug.el’ takes less than a second to produce and
looks like this:
" 1 0) (111.60027313232422 113.13760375976562 384.1658630371094 122.10398864746094 "(77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
" 2 0) (89.99981689453125 129.44915771484375 449.2359313964844 154.6273651123047 "(Using my old machine, the version 19 lengths’ list for ‘debug.el’ took
seven seconds to produce and looked like this:
" 3 0) (111.59977722167969 165.09768676757812 290.2049865722656 174.06407165527344 "(75 41 80 62 20 45 44 68 45 12 34 235)
" 4 0) (89.99856567382812 180.56915283203125 449.1914978027344 205.8673553466797 "(The newer version of ‘debug.el’ contains more defuns than the earlier
one; and my new machine is much faster than the old one.)
" 5 0) (104.99896240234375 212.0091552734375 438.4784851074219 225.30735778808594 "Note that the length of the last definition in the file is first in the list.
" 6 0) (89.9993896484375 263.42041015625 413.8879699707031 277.79364013671875 "14.7 Count Words in defuns in Different Files
" 7 0) (89.99832153320312 290.9691162109375 449.3984375 328.1473083496094 "In the previous section, we created a function that returns a list of the
lengths of each definition in a file. Now, we want to define a function to
return a master list of the lengths of the definitions in a list of files.
" 8 0) (89.9989013671875 334.28912353515625 449.19073486328125 359.4673156738281 "Working on each of a list of files is a repetitious act, so we can use either
a while loop or recursion.
" 9 0) (89.99713134765625 365.609130859375 449.5184326171875 462.5473327636719 "The design using a while loop is routine. The argument passed the func-
tion is a list of files. As we saw earlier (see Section 11.1.1, “Loop Example”,
page 122), you can write a while loop so that the body of the loop is evalu-
ated if such a list contains elements, but to exit the loop if the list is empty.
For this design to work, the body of the loop must contain an expression
that shortens the list each time the body is evaluated, so that eventually the
list is empty. The usual technique is to set the value of the list to the value
of the cdr of the list each time the body is evaluated.
" 10 0) (104.99717712402344 468.80914306640625 241.2080078125 482.1073303222656 "The template looks like this:
" 11 0) (111.5969009399414 492.45526123046875 247.5894775390625 526.3840942382812 "(while test-whether-list-is-empty
body...
set-list-to-cdr-of-list)
" 12 0) (89.9952392578125 533.7291259765625 449.5048522949219 630.787353515625 "Also, we remember that a while loop returns nil (the result of evaluat-
ing the true-or-false-test), not the result of any evaluation within its body.
(The evaluations within the body of the loop are done for their side effects.)
However, the expression that sets the lengths’ list is part of the body—and
that is the value that we want returned by the function as a whole. To do
this, we enclose the while loop within a let expression, and arrange that
the last element of the let expression contains the value of the lengths’ list.
(See “Loop Example with an Incrementing Counter”, page 125.)
" 13 0)) (209 (90.0 47.60907745361328 449.7275695800781 60.90726852416992 "The append Function
191
" 0 0) (105.00082397460938 81.32910919189453 384.3059997558594 94.6272964477539 "These considerations lead us directly to the function itself:
" 1 0) (111.6006851196289 101.37525177001953 365.0529479980469 135.1840057373047 ";;; Use while loop.
(defun lengths-list-many-files (list-of-files)
\"Return list of lengths of defuns in LIST-OF-FILES.\"
" 2 0) (120.96092224121094 139.77761840820312 210.00338745117188 148.74400329589844 "(let (lengths-list)
" 3 0) (111.60092163085938 164.615234375 228.89453125 223.3839569091797 ";;; true-or-false-test
(while list-of-files
(setq lengths-list
(append
lengths-list
" 4 0) (111.60092163085938 239.37518310546875 369.6644592285156 273.1839294433594 ";;; Generate a lengths’ list.
(lengths-list-file
(expand-file-name (car list-of-files)))))
" 5 0) (111.60099792480469 281.375244140625 332.1130065917969 302.8240051269531 ";;; Make files’ list shorter.
(setq list-of-files (cdr list-of-files)))
" 6 0) (90.0 318.69525146484375 449.3998107910156 408.18731689453125 ";;; Return final value of lengths’ list.
lengths-list))
expand-file-name is a built-in function that converts a file name to the
absolute, long, path name form of the directory in which the function is
called.
Thus, if expand-file-name is called on debug.el when Emacs is visiting
the ‘/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/’ directory,
" 7 0) (89.99988555908203 414.93768310546875 149.0076141357422 440.2273254394531 "debug.el
becomes
" 8 0) (89.99957275390625 446.857666015625 449.5304870605469 484.0273132324219 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
The only other new element of this function definition is the as yet un-
studied function append, which merits a short section for itself.
" 9 0) (89.99966430664062 502.56182861328125 266.5523376464844 515.6773681640625 "14.7.1 The append Function
" 10 0) (104.99947357177734 525.569091796875 373.3299560546875 538.8673095703125 "The append function attaches one list to another. Thus,
" 11 0) (89.9989013671875 545.4976806640625 252.5672149658203 570.787353515625 "(append ’(1 2 3 4) ’(5 6 7 8))
produces the list
" 12 0) (89.99856567382812 577.5376586914062 449.3985900878906 614.5873413085938 "(1 2 3 4 5 6 7 8)
This is exactly how we want to attach two lengths’ lists produced by
lengths-list-file to each other. The results contrast with cons,
" 13 0) (111.59884643554688 621.3377075195312 243.22401428222656 630.3040771484375 "(cons ’(1 2 3 4) ’(5 6 7 8))
" 14 0)) (210 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "192
Chapter 14: Counting Words in a defun
" 0 0) (90.000244140625 79.88904571533203 449.3891906738281 105.0672378540039 "which constructs a new list in which the first argument to cons becomes the
first element of the new list:
" 1 0) (111.6004409790039 110.37759399414062 200.9337615966797 119.34397888183594 "((1 2 3 4) 5 6 7 8)
" 2 0) (89.99993133544922 137.30035400390625 432.23687744140625 151.660888671875 "14.8 Recursively Count Words in Different Files
" 3 0) (89.99957275390625 159.6890869140625 449.41070556640625 270.9072570800781 "Besides a while loop, you can work on each of a list of files with recursion.
A recursive version of lengths-list-many-files is short and simple.
The recursive function has the usual parts: the ‘do-again-test’, the ‘next-
step-expression’, and the recursive call.
The ‘do-again-test’ determines
whether the function should call itself again, which it will do if the list-
of-files contains any remaining elements; the ‘next-step-expression’ resets
the list-of-files to the cdr of itself, so eventually the list will be empty;
and the recursive call calls itself on the shorter list. The complete function
is shorter than this description!
" 4 0) (89.99749755859375 276.2176208496094 449.85638427734375 549.427490234375 "(defun recursive-lengths-list-many-files (list-of-files)
\"Return list of lengths of each defun in LIST-OF-FILES.\"
(if list-of-files
; do-again-test
(append
(lengths-list-file
(expand-file-name (car list-of-files)))
(recursive-lengths-list-many-files
(cdr list-of-files)))))
In a sentence, the function returns the lengths’ list for the first of the list-
of-files appended to the result of calling itself on the rest of the list-
of-files.
Here is a test of recursive-lengths-list-many-files, along with the
results of running lengths-list-file on each of the files individually.
Install recursive-lengths-list-many-files and lengths-list-file,
if necessary, and then evaluate the following expressions. You may need to
change the files’ pathnames; those here work when this Info file and the
Emacs sources are located in their customary places. To change the expres-
sions, copy them to the ‘*scratch*’ buffer, edit them, and then evaluate
them.
The results are shown after the ‘⇒’. (These results are for files from
Emacs Version 21.0.100; files from other versions of Emacs may produce
different results.)
" 5 0) (111.59747314453125 554.7378540039062 294.1896057128906 563.7042236328125 "(cd \"/usr/local/share/emacs/21.0.100/\")
" 6 0) (111.59727478027344 579.6978759765625 289.6379089355469 606.77001953125 "(lengths-list-file \"./lisp/macros.el\")
⇒ (273 263 456 90)
" 7 0) (111.59735870361328 609.2178955078125 327.00982666015625 636.4100341796875 "(lengths-list-file \"./lisp/mail/mailalias.el\")
⇒ (38 32 26 77 174 180 321 198 324)
" 8 0)) (211 (90.0 47.60907745361328 449.7813415527344 60.90726852416992 "Sorting Lists
193
" 0 0) (111.59957885742188 93.81759643554688 294.31170654296875 120.88977813720703 "(lengths-list-file \"./lisp/makesum.el\")
⇒ (85 181)
" 1 0) (89.99923706054688 123.33755493164062 449.27923583984375 222.9071502685547 "(recursive-lengths-list-many-files
’(\"./lisp/macros.el\"
\"./lisp/mail/mailalias.el\"
\"./lisp/makesum.el\"))
⇒ (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
The recursive-lengths-list-many-files function produces the out-
put we want.
The next step is to prepare the data in the list for display in a graph.
" 2 0) (89.99911499023438 239.78021240234375 415.40411376953125 254.1407470703125 "14.9 Prepare the Data for Display in a Graph
" 3 0) (89.998046875 261.92901611328125 449.4859924316406 520.6273193359375 "The recursive-lengths-list-many-files function returns a list of
numbers. Each number records the length of a function definition. What
we need to do now is transform this data into a list of numbers suitable for
generating a graph. The new list will tell how many functions definitions
contain less than 10 words and symbols, how many contain between 10 and
19 words and symbols, how many contain between 20 and 29 words and
symbols, and so on.
In brief, we need to go through the lengths’ list produced by the
recursive-lengths-list-many-files function and count the number of
defuns within each range of lengths, and produce a list of those numbers.
Based on what we have done before, we can readily foresee that it should
not be too hard to write a function that ‘cdrs’ down the lengths’ list, looks
at each element, determines which length range it is in, and increments a
counter for that range.
However, before beginning to write such a function, we should consider
the advantages of sorting the lengths’ list first, so the numbers are ordered
from smallest to largest.
First, sorting will make it easier to count the
numbers in each range, since two adjacent numbers will either be in the
same length range or in adjacent ranges. Second, by inspecting a sorted list,
we can discover the highest and lowest number, and thereby determine the
largest and smallest length range that we will need.
" 4 0) (89.99827575683594 534.36181640625 217.02584838867188 547.4658203125 "14.9.1 Sorting Lists
" 5 0) (89.9971923828125 555.569091796875 449.485107421875 630.7872924804688 "Emacs contains a function to sort lists, called (as you might guess) sort.
The sort function takes two arguments, the list to be sorted, and a predicate
that determines whether the first of two list elements is “less” than the
second.
As we saw earlier (see Section 1.8.4, “Using the Wrong Type Object as
an Argument”, page 14), a predicate is a function that determines whether
" 6 0)) (212 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "194
Chapter 14: Counting Words in a defun
" 0 0) (89.99972534179688 77.48908233642578 449.51959228515625 141.0673065185547 "some property is true or false. The sort function will reorder a list accord-
ing to whatever property the predicate uses; this means that sort can be
used to sort non-numeric lists by non-numeric criteria—it can, for example,
alphabetize a list.
The < function is used when sorting a numeric list. For example,
" 1 0) (89.9996337890625 146.37765502929688 262.0389404296875 170.2273406982422 "(sort ’(4 8 21 17 33 7 21 7) ’<)
produces this:
" 2 0) (89.99850463867188 175.65768432617188 450.0417785644531 237.5474090576172 "(4 7 7 8 17 21 21 33)
(Note that in this example, both the arguments are quoted so that the
symbols are not evaluated before being passed to sort as arguments.)
Sorting the list returned by the recursive-lengths-list-many-files
function is straightforward; it uses the < function:
" 3 0) (89.99833679199219 242.97775268554688 275.3841552734375 330.1872863769531 "(sort
(recursive-lengths-list-many-files
’(\"../lisp/macros.el\"
\"../lisp/mailalias.el\"
\"../lisp/makesum.el\"))
’<
which produces:
" 4 0) (89.99844360351562 335.4976501464844 449.387451171875 383.227294921875 "(85 86 116 122 154 176 179 265)
(Note that in this example, the first argument to sort is not quoted, since
the expression must be evaluated so as to produce the list that is passed to
sort.)
" 5 0) (89.99847412109375 397.5618591308594 276.4914855957031 410.6658630371094 "14.9.2 Making a List of Files
" 6 0) (89.99462890625 419.1291198730469 449.5805969238281 630.787353515625 "The recursive-lengths-list-many-files function requires a list of
files as its argument. For our test examples, we constructed such a list by
hand; but the Emacs Lisp source directory is too large for us to do for that.
Instead, we will write a function to do the job for us. In this function, we
will use both a while loop and a recursive call.
We did not have to write a function like this for older versions of GNU
Emacs, since they placed all the ‘.el’ files in one directory. Instead, we were
able to use the directory-files function, which lists the names of files that
match a specified pattern within a single directory.
However, recent versions of Emacs place Emacs Lisp files in sub-
directories of the top level ‘lisp’ directory.
This re-arrangement eases
navigation.
For example, all the mail related files are in a ‘lisp’
sub-directory called ‘mail’. But at the same time, this arrangement forces
us to create a file listing function that descends into the sub-directories.
We can create this function, called files-in-below-directory, using
familiar functions such as car, nthcdr, and substring in conjunction with
an existing function called directory-files-and-attributes. This latter
" 7 0)) (213 (90.0 47.60907745361328 449.7158203125 60.90726852416992 "Making a List of Files
195
" 0 0) (89.99874877929688 77.48908233642578 449.3434753417969 142.50730895996094 "function not only lists all the filenames in a directory, including the names
of sub-directories, but also their attributes.
To restate our goal: to create a function that will enable us to feed
filenames to recursive-lengths-list-many-files as a list that looks like
this (but with more elements):
" 1 0) (89.99624633789062 149.49765014648438 449.6146240234375 327.4273376464844 "(\"../lisp/macros.el\"
\"../lisp/mail/rmail.el\"
\"../lisp/makesum.el\")
The directory-files-and-attributes function returns a list of lists.
Each of the lists within the main list consists of 13 elements.
The first
element is a string that contains the name of the file – which, in GNU/Linux,
may be a ‘directory file’, that is to say, a file with the special attributes of
a directory. The second element of the list is t for a directory, a string for
symbolic link (the string is the name linked to), or nil.
For example, the first ‘.el’ file in the ‘lisp/’ directory is ‘abbrev.el’.
Its name is ‘/usr/local/share/emacs/21.0.100/lisp/abbrev.el’ and it
is not a directory or a symbolic link.
This is how directory-files-and-attributes lists that file and its
attributes:
" 2 0) (111.5958251953125 334.4176025390625 341.1346435546875 456.42413330078125 "(\"/usr/local/share/emacs/21.0.100/lisp/abbrev.el\"
nil
1
1000
100
(15019 32380)
(14883 48041)
(15214 49336)
11583
\"-rw-rw-r--\"
" 3 0) (111.5958251953125 461.01776123046875 139.6605987548828 494.8241271972656 "t
341385
776)
" 4 0) (89.99566650390625 499.1692199707031 449.2643737792969 524.4674072265625 "On the other hand, ‘mail/’ is a directory within the ‘lisp/’ directory.
The beginning of its listing looks like this:
" 5 0) (111.59548950195312 531.3378295898438 317.656494140625 577.6241455078125 "(\"/usr/local/share/emacs/21.0.100/lisp/mail\"
t
...
)
" 6 0) (89.99423217773438 581.6092529296875 449.9945373535156 630.7874755859375 "(Look at the documentation of file-attributes to learn about the dif-
ferent attributes. Bear in mind that the file-attributes function does not
list the filename, so its first element is directory-files-and-attributes’s
second element.)
" 7 0)) (214 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "196
Chapter 14: Counting Words in a defun
" 0 0) (89.99984741210938 77.48908233642578 449.4106750488281 114.66727447509766 "We will want our new function, files-in-below-directory, to list the
‘.el’ files in the directory it is told to check, and in any directories below
that directory.
" 1 0) (89.99990844726562 120.08905792236328 450.1416320800781 169.2672576904297 "This gives us a hint on how to construct files-in-below-directory:
within a directory, the function should add ‘.el’ filenames to a list; and if,
within a directory, the function comes upon a sub-directory, it should go
into that sub-directory and repeat its actions.
" 2 0) (89.99896240234375 174.56903076171875 449.82440185546875 247.6272430419922 "However, we should note that every directory contains a name that refers
to itself, called ‘.’, (“dot”) and a name that refers to its parent directory,
called ‘..’ (“double dot”). (In ‘/’, the root directory, ‘..’ refers to itself,
since ‘/’ has no parent.)
Clearly, we do not want our files-in-below-
directory function to enter those directories, since they always lead us,
directly or indirectly, to the current directory.
" 3 0) (89.99893188476562 253.04901123046875 449.2569274902344 278.3471984863281 "Consequently, our files-in-below-directory function must do several
tasks:
" 4 0) (98.99893188476562 284.72900390625 449.4416809082031 309.9071960449219 "• Check to see whether it is looking at a filename that ends in ‘.el’; and
if so, add its name to a list.
" 5 0) (98.99954223632812 316.28900146484375 449.46417236328125 341.5871887207031 "• Check to see whether it is looking at a filename that is the name of a
directory; and if so,
" 6 0) (117.47953796386719 347.968994140625 442.122802734375 369.0126647949219 "− Check to see whether it is looking at ‘.’ or ‘..’; and if so skip it.
" 7 0) (117.47988891601562 367.64898681640625 390.6103515625 388.6926574707031 "− Or else, go into that directory and repeat the process.
" 8 0) (89.99984741210938 394.0489807128906 449.46533203125 455.107177734375 "Let’s write a function definition to do these tasks. We will use a while
loop to move from one filename to another within a directory, checking what
needs to be done; and we will use a recursive call to repeat the actions on
each sub-directory. The recursive pattern is ‘accumulate’ (see “Recursive
Pattern: accumulate”, page 142), using append as the combiner.
" 9 0) (104.99993896484375 460.64898681640625 202.40711975097656 473.9471740722656 "Here is the function:
" 10 0) (111.59992980957031 483.6975402832031 407.2333068847656 567.303955078125 "(defun files-in-below-directory (directory)
\"List the .el files in DIRECTORY and in its sub-directories.\"
;; Although the function will be used non-interactively,
;; it will be easier to test if we make it interactive.
;; The directory will have a name such as
;;
\"/usr/local/share/emacs/21.0.100/lisp/\"
(interactive \"DDirectory name: \")
" 11 0) (120.96011352539062 571.8975830078125 370.10107421875 630.6639404296875 "(let (el-files-list
(current-directory-list
(directory-files-and-attributes directory t)))
;; while we are in the current directory
(while current-directory-list
" 12 0)) (215 (90.0 47.60907745361328 449.6291809082031 60.90726852416992 "Counting function definitions
197
" 0 0) (139.8004150390625 81.33761596679688 445.2222900390625 265.6237487792969 "(cond
;; check to see whether filename ends in ‘.el’
;; and if so, append its name to a list.
((equal \".el\" (substring (car (car current-directory-list)) -3))
(setq el-files-list
(cons (car (car current-directory-list)) el-files-list)))
;; check whether filename is that of a directory
((eq t (car (cdr (car current-directory-list))))
;; decide whether to skip or recurse
(if
(equal (or \".\" \"..\")
(substring (car (car current-directory-list)) -1))
;; then do nothing if filename is that of
;;
current directory or parent
()
" 1 0) (90.00042724609375 270.2173767089844 449.4222412109375 446.22698974609375 ";; else descend into the directory and repeat the process
(setq el-files-list
(append
(files-in-below-directory
(car (car current-directory-list)))
el-files-list)))))
;; move to the next filename in the list; this also
;; shortens the list so the while loop eventually comes to an end
(setq current-directory-list (cdr current-directory-list)))
;; return the filenames
el-files-list))
The files-in-below-directory directory-files function takes one
argument, the name of a directory.
Thus, on my system,
" 2 0) (90.00027465820312 452.1373291015625 449.3565673828125 527.947021484375 "(length
(files-in-below-directory \"/usr/local/share/emacs/21.0.100/lisp/\"))
tells me that my version 21.0.100 Lisp sources directory contains 754 ‘.el’
files.
files-in-below-directory returns a list in reverse alphabetical order.
An expression to sort the list in alphabetical order looks like this:
" 3 0) (111.59994506835938 533.8573608398438 425.7215270996094 567.7837524414062 "(sort
(files-in-below-directory \"/usr/local/share/emacs/21.0.100/lisp/\")
’string-lessp)
" 4 0) (89.99923706054688 583.4415893554688 323.1592102050781 596.5455932617188 "14.9.3 Counting function definitions
" 5 0) (89.99951171875 605.4888305664062 449.3116455078125 630.7870483398438 "Our immediate goal is to generate a list that tells us how many function
definitions contain fewer than 10 words and symbols, how many contain
" 6 0)) (216 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "198
Chapter 14: Counting Words in a defun
" 0 0) (90.000244140625 77.48908233642578 449.4653625488281 102.66727447509766 "between 10 and 19 words and symbols, how many contain between 20 and
29 words and symbols, and so on.
" 1 0) (89.9981689453125 111.56909942626953 449.5192565917969 184.62730407714844 "With a sorted list of numbers, this is easy: count how many elements
of the list are smaller than 10, then, after moving past the numbers just
counted, count how many are smaller than 20, then, after moving past the
numbers just counted, count how many are smaller than 30, and so on. Each
of the numbers, 10, 20, 30, 40, and the like, is one larger than the top of
that range. We can call the list of such numbers the top-of-ranges list.
" 2 0) (89.99765014648438 193.52911376953125 449.2886047363281 218.8273162841797 "If we wished, we could generate this list automatically, but it is simpler
to write a list manually. Here it is:
" 3 0) (111.59799194335938 231.93765258789062 346.0900573730469 328.1438903808594 "(defvar top-of-ranges
’(10
20
30
40
50
60
70
80
90 100
110 120 130 140 150
160 170 180 190 200
210 220 230 240 250
260 270 280 290 300)
\"List specifying ranges for ‘defuns-per-range’.\")
" 4 0) (104.99815368652344 337.64898681640625 289.2414855957031 350.9471740722656 "To change the ranges, we edit this list.
" 5 0) (89.99813842773438 359.8489990234375 449.5179748535156 397.0271911621094 "Next, we need to write the function that creates the list of the number of
definitions within each range. Clearly, this function must take the sorted-
lengths and the top-of-ranges lists as arguments.
" 6 0) (89.99688720703125 405.8089904785156 449.4296569824219 502.8671875 "The defuns-per-range function must do two things again and again: it
must count the number of definitions within a range specified by the current
top-of-range value; and it must shift to the next higher value in the top-
of-ranges list after counting the number of definitions in the current range.
Since each of these actions is repetitive, we can use while loops for the job.
One loop counts the number of definitions in the range defined by the current
top-of-range value, and the other loop selects each of the top-of-range values
in turn.
" 7 0) (89.99685668945312 511.64898681640625 449.26605224609375 548.8272094726562 "Several entries of the sorted-lengths list are counted for each range;
this means that the loop for the sorted-lengths list will be inside the loop
for the top-of-ranges list, like a small gear inside a big gear.
" 8 0) (89.99667358398438 557.72900390625 449.41827392578125 630.7872314453125 "The inner loop counts the number of definitions within the range. It is a
simple counting loop of the type we have seen before. (See Section 11.1.3, “A
loop with an incrementing counter”, page 124.) The true-or-false test of the
loop tests whether the value from the sorted-lengths list is smaller than
the current value of the top of the range. If it is, the function increments
the counter and tests the next value from the sorted-lengths list.
" 9 0)) (217 (90.0 47.60907745361328 449.6291809082031 60.90726852416992 "Counting function definitions
199
" 0 0) (105.00042724609375 80.60907745361328 247.56021118164062 93.90726470947266 "The inner loop looks like this:
" 1 0) (89.9993896484375 99.93518829345703 449.8359375 173.4672088623047 "(while length-element-smaller-than-top-of-range
(setq number-within-range (1+ number-within-range))
(setq sorted-lengths (cdr sorted-lengths)))
The outer loop must start with the lowest value of the top-of-ranges
list, and then be set to each of the succeeding higher values in turn. This
can be done with a loop like this:
" 2 0) (104.99873352050781 179.49752807617188 313.271240234375 229.98716735839844 "(while top-of-ranges
body-of-loop...
(setq top-of-ranges (cdr top-of-ranges)))
Put together, the two loops look like this:
" 3 0) (111.59832763671875 236.01748657226562 205.31231689453125 244.98387145996094 "(while top-of-ranges
" 4 0) (120.95803833007812 260.97515869140625 369.5848388671875 307.2638854980469 ";; Count the number of elements within the current range.
(while length-element-smaller-than-top-of-range
(setq number-within-range (1+ number-within-range))
(setq sorted-lengths (cdr sorted-lengths)))
" 5 0) (89.99578857421875 323.255126953125 449.9532165527344 521.947265625 ";; Move to next range.
(setq top-of-ranges (cdr top-of-ranges)))
In addition, in each circuit of the outer loop, Emacs should record the
number of definitions within that range (the value of number-within-range)
in a list.
We can use cons for this purpose.
(See Section 7.2, “cons”,
page 83.)
The cons function works fine, except that the list it constructs will con-
tain the number of definitions for the highest range at its beginning and the
number of definitions for the lowest range at its end. This is because cons
attaches new elements of the list to the beginning of the list, and since the
two loops are working their way through the lengths’ list from the lower end
first, the defuns-per-range-list will end up largest number first. But we
will want to print our graph with smallest values first and the larger later.
The solution is to reverse the order of the defuns-per-range-list. We can
do this using the nreverse function, which reverses the order of a list.
For example,
" 6 0) (89.99520111083984 527.9776000976562 210.2465057373047 552.5472412109375 "(nreverse ’(1 2 3 4))
produces:
" 7 0) (89.99392700195312 558.5775756835938 449.54669189453125 630.7872314453125 "(4 3 2 1)
Note that the nreverse function is “destructive”—that is, it changes
the list to which it is applied; this contrasts with the car and cdr functions,
which are non-destructive. In this case, we do not want the original defuns-
per-range-list, so it does not matter that it is destroyed. (The reverse
function provides a reversed copy of a list, leaving the original list as is.)
" 8 0)) (218 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "200
Chapter 14: Counting Words in a defun
" 0 0) (105.000244140625 81.92908477783203 369.7200927734375 95.2272720336914 "Put all together, the defuns-per-range looks like this:
" 1 0) (111.60000610351562 102.45761108398438 365.2751159667969 161.2239227294922 "(defun defuns-per-range (sorted-lengths top-of-ranges)
\"SORTED-LENGTHS defuns in each TOP-OF-RANGES range.\"
(let ((top-of-range (car top-of-ranges))
(number-within-range 0)
defuns-per-range-list)
" 2 0) (130.4398651123047 169.41510009765625 224.1538543701172 190.86387634277344 ";; Outer loop.
(while top-of-ranges
" 3 0) (139.79981994628906 198.93505859375 355.7777099609375 257.8237609863281 ";; Inner loop.
(while (and
;; Need number for numeric test.
(car sorted-lengths)
(< (car sorted-lengths) top-of-range))
" 4 0) (149.27980041503906 265.89495849609375 388.42669677734375 299.8236999511719 ";; Count number of definitions within current range.
(setq number-within-range (1+ number-within-range))
(setq sorted-lengths (cdr sorted-lengths)))
" 5 0) (139.79978942871094 315.6949462890625 337.92840576171875 324.6637268066406 ";; Exit inner loop but remain within outer loop.
" 6 0) (139.7988739013672 332.85736083984375 397.79473876953125 366.78375244140625 "(setq defuns-per-range-list
(cons number-within-range defuns-per-range-list))
(setq number-within-range 0)
; Reset count to zero.
" 7 0) (139.7975616455078 374.85498046875 327.43878173828125 421.2637939453125 ";; Move to next range.
(setq top-of-ranges (cdr top-of-ranges))
;; Specify next top of range value.
(setq top-of-range (car top-of-ranges)))
" 8 0) (130.43765258789062 429.33502197265625 385.79168701171875 500.5838317871094 ";; Exit outer loop and count the number of defuns larger than
;;
the largest top-of-range value.
(setq defuns-per-range-list
(cons
(length sorted-lengths)
defuns-per-range-list))
" 9 0) (130.4378662109375 508.77508544921875 387.80242919921875 542.703857421875 ";; Return a list of the number of definitions within each range,
;;
smallest to largest.
(nreverse defuns-per-range-list)))
" 10 0)) (219 (90.0 47.60907745361328 449.6291809082031 60.90726852416992 "Counting function definitions
201
" 0 0) (90.00018310546875 77.48908233642578 449.21453857421875 102.66727447509766 "The function is straightforward except for one subtle feature. The true-or-
false test of the inner loop looks like this:
" 1 0) (111.59979248046875 113.61764526367188 313.4173583984375 135.0640106201172 "(and (car sorted-lengths)
(< (car sorted-lengths) top-of-range))
" 2 0) (89.99980163574219 143.24908447265625 180.5669708251953 156.5472869873047 "instead of like this:
" 3 0) (111.59976196289062 167.49765014648438 285.1058349609375 176.4640350341797 "(< (car sorted-lengths) top-of-range)
" 4 0) (89.99993896484375 183.4490966796875 449.4537658691406 208.74729919433594 "The purpose of the test is to determine whether the first item in the
sorted-lengths list is less than the value of the top of the range.
" 5 0) (90.00033569335938 215.24908447265625 449.8467102050781 276.4272766113281 "The simple version of the test works fine unless the sorted-lengths
list has a nil value. In that case, the (car sorted-lengths) expression
function returns nil.
The < function cannot compare a number to nil,
which is an empty list, so Emacs signals an error and stops the function
from attempting to continue to execute.
" 6 0) (90.00027465820312 282.9290771484375 449.70538330078125 320.1072692871094 "The sorted-lengths list always becomes nil when the counter reaches
the end of the list. This means that any attempt to use the defuns-per-
range function with the simple version of the test will fail.
" 7 0) (89.99822998046875 326.7290954589844 449.377685546875 423.66729736328125 "We solve the problem by using the (car sorted-lengths) expression in
conjunction with the and expression. The (car sorted-lengths) expres-
sion returns a non-nil value so long as the list has at least one number within
it, but returns nil if the list is empty. The and expression first evaluates
the (car sorted-lengths) expression, and if it is nil, returns false without
evaluating the < expression. But if the (car sorted-lengths) expression
returns a non-nil value, the and expression evaluates the < expression, and
returns that value as the value of the and expression.
" 8 0) (89.99774169921875 430.1690979003906 449.4302978515625 455.46728515625 "This way, we avoid an error. See Section 12.4, “forward-paragraph: a
Goldmine of Functions”, page 155, for more information about and.
" 9 0) (89.99697875976562 461.9690856933594 449.30938720703125 511.14727783203125 "Here is a short test of the defuns-per-range function. First, evaluate
the expression that binds (a shortened) top-of-ranges list to the list of
values, then evaluate the expression for binding the sorted-lengths list,
and then evaluate the defuns-per-range function.
" 10 0) (111.59675598144531 522.09521484375 270.2386169433594 568.384033203125 ";; (Shorter list than we will use later.)
(setq top-of-ranges
’(110 120 130 140 150
160 170 180 190 200))
" 11 0) (111.5972671508789 584.2576293945312 388.8432922363281 605.7040405273438 "(setq sorted-lengths
’(85 86 110 116 122 129 154 176 179 200 265 300 300))
" 12 0) (111.5970458984375 621.6976928710938 332.16949462890625 630.6640625 "(defuns-per-range sorted-lengths top-of-ranges)
" 13 0)) (220 (90.0 47.60907745361328 449.7268371582031 60.90726852416992 "202
Chapter 14: Counting Words in a defun
" 0 0) (90.000244140625 79.52906036376953 243.32737731933594 92.8272476196289 "The list returned looks like this:
" 1 0) (90.00010681152344 97.89761352539062 449.43316650390625 145.1472625732422 "(2 2 2 0 0 1 0 2 0 0 4)
Indeed, there are two elements of the sorted-lengths list smaller than 110,
two elements between 110 and 119, two elements between 120 and 129, and
so on. There are four elements with a value of 200 or larger.
" 2 0)) (221 (90.0 47.60907745361328 449.7595520019531 60.90726852416992 "Readying a Graph
203
" 0 0) (89.99978637695312 75.14844512939453 274.8667297363281 92.38106536865234 "15 Readying a Graph
" 1 0) (89.99948120117188 114.08905792236328 449.67266845703125 630.787353515625 "Our goal is to construct a graph showing the numbers of function defini-
tions of various lengths in the Emacs lisp sources.
As a practical matter, if you were creating a graph, you would probably
use a program such as gnuplot to do the job. (gnuplot is nicely integrated
into GNU Emacs.) In this case, however, we create one from scratch, and
in the process we will re-acquaint ourselves with some of what we learned
before and learn more.
In this chapter, we will first write a simple graph printing function. This
first definition will be a prototype, a rapidly written function that enables
us to reconnoiter this unknown graph-making territory. We will discover
dragons, or find that they are myth. After scouting the terrain, we will feel
more confident and enhance the function to label the axes automatically.
Since Emacs is designed to be flexible and work with all kinds of terminals,
including character-only terminals, the graph will need to be made from one
of the ‘typewriter’ symbols. An asterisk will do; as we enhance the graph-
printing function, we can make the choice of symbol a user option.
We can call this function graph-body-print; it will take a numbers-list
as its only argument. At this stage, we will not label the graph, but only
print its body.
The graph-body-print function inserts a vertical column of asterisks for
each element in the numbers-list. The height of each line is determined by
the value of that element of the numbers-list.
Inserting columns is a repetitive act; that means that this function can
be written either with a while loop or recursively.
Our first challenge is to discover how to print a column of asterisks.
Usually, in Emacs, we print characters onto a screen horizontally, line by
line, by typing. We have two routes we can follow: write our own column-
insertion function or discover whether one exists in Emacs.
To see whether there is one in Emacs, we can use the M-x apropos com-
mand. This command is like the C-h a (command-apropos) command, ex-
cept that the latter finds only those functions that are commands.
The
M-x apropos command lists all symbols that match a regular expression,
including functions that are not interactive.
What we want to look for is some command that prints or inserts columns.
Very likely, the name of the function will contain either the word ‘print’ or
the word ‘insert’ or the word ‘column’. Therefore, we can simply type M-x
apropos RET print\\|insert\\|column RET and look at the result. On my
system, this command takes quite some time, and then produces a list of
79 functions and variables. Scanning down the list, the only function that
looks as if it might do the job is insert-rectangle.
" 2 0)) (222 (90.0 47.60907745361328 449.7815246582031 60.90726852416992 "204
Chapter 15: Readying a Graph
" 0 0) (104.99969482421875 79.64905548095703 394.63592529296875 92.9472427368164 "Indeed, this is the function we want; its documentation says:
" 1 0) (90.0 98.01760864257812 449.32379150390625 221.4672088623047 "insert-rectangle:
Insert text of RECTANGLE with upper left corner at point.
RECTANGLE’s first line is inserted at point,
its second line is inserted at a point vertically under point, etc.
RECTANGLE should be a list of strings.
We can run a quick test, to make sure it does what we expect of it.
Here is the result of placing the cursor after the insert-rectangle ex-
pression and typing C-u C-x C-e (eval-last-sexp). The function inserts
the strings ‘\"first\"’, ‘\"second\"’, and ‘\"third\"’ at and below point. Also
the function returns nil.
" 2 0) (89.99850463867188 226.53756713867188 449.37689208984375 391.2497253417969 "(insert-rectangle ’(\"first\" \"second\" \"third\"))first
second
third
nil
Of course, we won’t be inserting the text of the insert-rectangle expres-
sion itself into the buffer in which we are making the graph, but will call
the function from our program. We shall, however, have to make sure that
point is in the buffer at the place where the insert-rectangle function will
insert its column of strings.
If you are reading this in Info, you can see how this works by switching
to another buffer, such as the ‘*scratch*’ buffer, placing point somewhere
in the buffer, typing M-:, typing the insert-rectangle expression into the
minibuffer at the prompt, and then typing ⟨
" 3 0) (309.5879821777344 375.4720153808594 327.7079772949219 375.9520263671875 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (309.6000061035156 376.68243408203125 327.70013427734375 384.65252685546875 "RET
" 5 0) (309.5879821777344 384.11199951171875 327.7079772949219 384.5920104980469 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99758911132812 372.0890197753906 449.7491149902344 630.7872924804688 "⟩.
This causes Emacs to
evaluate the expression in the minibuffer, but to use as the value of point
the position of point in the ‘*scratch*’ buffer. (M-: is the keybinding for
eval-expression.)
We find when we do this that point ends up at the end of the last inserted
line—that is to say, this function moves point as a side-effect. If we were to
repeat the command, with point at this position, the next insertion would
be below and to the right of the previous insertion. We don’t want this! If
we are going to make a bar graph, the columns need to be beside each other.
So we discover that each cycle of the column-inserting while loop must
reposition point to the place we want it, and that place will be at the top,
not the bottom, of the column. Moreover, we remember that when we print
a graph, we do not expect all the columns to be the same height. This means
that the top of each column may be at a different height from the previous
one. We cannot simply reposition point to the same line each time, but
moved over to the right—or perhaps we can. . .
We are planning to make the columns of the bar graph out of asterisks.
The number of asterisks in the column is the number specified by the current
element of the numbers-list. We need to construct a list of asterisks of the
right length for each call to insert-rectangle. If this list consists solely of
the requisite number of asterisks, then we will have position point the right
" 7 0)) (223 (90.0 47.60907745361328 449.7595520019531 60.90726852416992 "Readying a Graph
205
" 0 0) (89.998779296875 77.48908233642578 449.8246765136719 188.9473114013672 "number of lines above the base for the graph to print correctly. This could
be difficult.
Alternatively, if we can figure out some way to pass insert-rectangle
a list of the same length each time, then we can place point on the same line
each time, but move it over one column to the right for each new column.
If we do this, however, some of the entries in the list passed to insert-
rectangle must be blanks rather than asterisks. For example, if the max-
imum height of the graph is 5, but the height of the column is 3, then
insert-rectangle requires an argument that looks like this:
" 1 0) (89.99838256835938 194.49765014648438 449.454345703125 325.9873352050781 "(\" \" \" \" \"*\" \"*\" \"*\")
This last proposal is not so difficult, so long as we can determine the
column height.
There are two ways for us to specify the column height:
we can arbitrarily state what it will be, which would work fine for graphs
of that height; or we can search through the list of numbers and use the
maximum height of the list as the maximum height of the graph. If the
latter operation were difficult, then the former procedure would be easiest,
but there is a function built into Emacs that determines the maximum of
its arguments. We can use that function. The function is called max and it
returns the largest of all its arguments, which must be numbers. Thus, for
example,
" 2 0) (89.99771118164062 331.4176940917969 449.5292663574219 405.6673278808594 "(max
3 4 6 5 7 3)
returns 7. (A corresponding function called min returns the smallest of all
its arguments.)
However, we cannot simply call max on the numbers-list; the max func-
tion expects numbers as its argument, not a list of numbers.
Thus, the
following expression,
" 3 0) (89.99787902832031 411.2176818847656 268.241455078125 435.3073425292969 "(max
’(3 4 6 5 7 3))
produces the following error message;
" 4 0) (89.99734497070312 440.7377014160156 449.48529052734375 503.22735595703125 "Wrong type of argument:
number-or-marker-p, (3 4 6 5 7 3)
We need a function that passes a list of arguments to a function. This
function is apply. This function ‘applies’ its first argument (a function) to
its remaining arguments, the last of which may be a list.
For example,
" 5 0) (89.99603271484375 508.6577453613281 449.53765869140625 630.787353515625 "(apply ’max 3 4 7 3 ’(4 8 5))
returns 8.
(Incidentally, I don’t know how you would learn of this function without
a book such as this. It is possible to discover other functions, like search-
forward or insert-rectangle, by guessing at a part of their names and
then using apropos. Even though its base in metaphor is clear—‘apply’
its first argument to the rest—I doubt a novice would come up with that
particular word when using apropos or other aid. Of course, I could be
wrong; after all, the function was first named by someone who had to invent
it.)
" 6 0)) (224 (90.0 47.60907745361328 449.7815246582031 60.90726852416992 "206
Chapter 15: Readying a Graph
" 0 0) (89.99880981445312 77.48908233642578 449.36590576171875 114.66727447509766 "The second and subsequent arguments to apply are optional, so we can
use apply to call a function and pass the elements of a list to it, like this,
which also returns 8:
" 1 0) (111.59877014160156 124.53762817382812 210.2497100830078 133.50401306152344 "(apply ’max ’(4 8 5))
" 2 0) (89.99844360351562 139.4090576171875 449.987548828125 188.58726501464844 "This latter way is how we will use apply.
The recursive-lengths-
list-many-files function returns a numbers’ list to which we can apply
max (we could also apply max to the sorted numbers’ list; it does not matter
whether the list is sorted or not.)
" 3 0) (104.99845123291016 194.12908935546875 449.3868103027344 207.4272918701172 "Hence, the operation for finding the maximum height of the graph is this:
" 4 0) (111.59771728515625 217.29763793945312 341.5301818847656 226.26402282714844 "(setq max-graph-height (apply ’max numbers-list))
" 5 0) (89.99639892578125 232.1690673828125 449.4398498535156 281.3472595214844 "Now we can return to the question of how to create a list of strings for a
column of the graph. Told the maximum height of the graph and the number
of asterisks that should appear in the column, the function should return a
list of strings for the insert-rectangle command to insert.
" 6 0) (89.994873046875 286.88909912109375 449.4386901855469 347.9472961425781 "Each column is made up of asterisks or blanks. Since the function is
passed the value of the height of the column and the number of asterisks in
the column, the number of blanks can be found by subtracting the number
of asterisks from the height of the column. Given the number of blanks and
the number of asterisks, two while loops can be used to construct the list:
" 7 0) (111.59452819824219 357.81524658203125 379.32708740234375 429.0640563964844 ";;; First version.
(defun column-of-graph (max-graph-height actual-height)
\"Return list of strings that is one column of a graph.\"
(let ((insert-list nil)
(number-of-top-blanks
(- max-graph-height actual-height)))
" 8 0) (130.43426513671875 437.1352844238281 332.23486328125 483.5440979003906 ";; Fill in asterisks.
(while (> actual-height 0)
(setq insert-list (cons \"*\" insert-list))
(setq actual-height (1- actual-height)))
" 9 0) (130.43467712402344 491.6153259277344 332.244140625 550.504150390625 ";; Fill in blanks.
(while (> number-of-top-blanks 0)
(setq insert-list (cons \" \" insert-list))
(setq number-of-top-blanks
(1- number-of-top-blanks)))
" 10 0) (130.43505859375 558.5753784179688 216.80702209472656 580.024169921875 ";; Return whole list.
insert-list))
" 11 0) (89.99520874023438 586.2892456054688 449.2527770996094 611.4674682617188 "If you install this function and then evaluate the following expression you
will see that it returns the list as desired:
" 12 0) (111.59559631347656 621.3378295898438 210.2295684814453 630.30419921875 "(column-of-graph 5 3)
" 13 0)) (225 (90.0 47.60907745361328 449.7595520019531 60.90726852416992 "Readying a Graph
207
" 0 0) (89.99978637695312 86.24909210205078 124.11254119873047 99.54727935791016 "returns
" 1 0) (111.59978485107422 112.17764282226562 210.26756286621094 121.14402770996094 "(\" \" \" \" \"*\" \"*\" \"*\")
" 2 0) (89.998779296875 129.80908203125 449.4539794921875 262.6272888183594 "As written, column-of-graph contains a major flaw: the symbols used
for the blank and for the marked entries in the column are ‘hard-coded’ as
a space and asterisk. This is fine for a prototype, but you, or another user,
may wish to use other symbols. For example, in testing the graph function,
you many want to use a period in place of the space, to make sure the point
is being repositioned properly each time the insert-rectangle function is
called; or you might want to substitute a ‘+’ sign or other symbol for the
asterisk. You might even want to make a graph-column that is more than
one display column wide. The program should be more flexible. The way to
do that is to replace the blank and the asterisk with two variables that we can
call graph-blank and graph-symbol and define those variables separately.
" 3 0) (89.9993896484375 270.80908203125 449.1701354980469 296.1072692871094 "Also, the documentation is not well written. These considerations lead
us to the second version of the function:
" 4 0) (111.599365234375 308.6176452636719 379.19476318359375 330.0639953613281 "(defvar graph-symbol \"*\"
\"String used as symbol in graph, usually an asterisk.\")
" 5 0) (111.59890747070312 338.25762939453125 374.65203857421875 384.54400634765625 "(defvar graph-blank \" \"
\"String used as blank in graph, usually a blank space.
graph-blank must be the same number of columns wide
as graph-symbol.\")
" 6 0) (89.9989013671875 394.16900634765625 449.2347717285156 419.3471984863281 "(For an explanation of defvar, see Section 8.4, “Initializing a Variable with
defvar”, page 100.)
" 7 0) (111.59901428222656 431.9751281738281 430.79534912109375 465.7839050292969 ";;; Second version.
(defun column-of-graph (max-graph-height actual-height)
\"Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
" 8 0) (111.59820556640625 482.737548828125 355.6824951171875 529.1439819335938 "The graph-symbols are contiguous entries at the end
of the list.
The list will be inserted as one column of a graph.
The strings are either graph-blank or graph-symbol.\"
" 9 0) (120.95893859863281 537.2175903320312 322.7849426269531 571.14404296875 "(let ((insert-list nil)
(number-of-top-blanks
(- max-graph-height actual-height)))
" 10 0) (130.4378204345703 579.335205078125 374.5218200683594 625.6240234375 ";; Fill in graph-symbols.
(while (> actual-height 0)
(setq insert-list (cons graph-symbol insert-list))
(setq actual-height (1- actual-height)))
" 11 0)) (226 (90.0 47.60907745361328 449.7815246582031 60.90726852416992 "208
Chapter 15: Readying a Graph
" 0 0) (130.439697265625 81.33521270751953 369.85260009765625 140.1039276123047 ";; Fill in graph-blanks.
(while (> number-of-top-blanks 0)
(setq insert-list (cons graph-blank insert-list))
(setq number-of-top-blanks
(1- number-of-top-blanks)))
" 1 0) (89.99774169921875 155.97515869140625 449.54156494140625 375.42724609375 ";; Return whole list.
insert-list))
If we wished, we could rewrite column-of-graph a third time to provide
optionally for a line graph as well as for a bar graph. This would not be
hard to do. One way to think of a line graph is that it is no more than a
bar graph in which the part of each bar that is below the top is blank. To
construct a column for a line graph, the function first constructs a list of
blanks that is one shorter than the value, then it uses cons to attach a graph
symbol to the list; then it uses cons again to attach the ‘top blanks’ to the
list.
It is easy to see how to write such a function, but since we don’t need it,
we will not do it. But the job could be done, and if it were done, it would
be done with column-of-graph. Even more important, it is worth noting
that few changes would have to be made anywhere else. The enhancement,
if we ever wish to make it, is simple.
Now, finally, we come to our first actual graph printing function. This
prints the body of a graph, not the labels for the vertical and horizontal
axes, so we can call this graph-body-print.
" 2 0) (89.99774169921875 390.2603454589844 344.72479248046875 404.6335754394531 "15.1 The graph-body-print Function
" 3 0) (89.99557495117188 412.4090576171875 449.8009948730469 537.3073120117188 "After our preparation in the preceding section, the graph-body-print
function is straightforward. The function will print column after column of
asterisks and blanks, using the elements of a numbers’ list to specify the
number of asterisks in each column. This is a repetitive act, which means
we can use a decrementing while loop or recursive function for the job. In
this section, we will write the definition using a while loop.
The column-of-graph function requires the height of the graph as an
argument, so we should determine and record that as a local variable.
This leads us to the following template for the while loop version of this
function:
" 4 0) (111.59566497802734 542.2576293945312 289.7648010253906 588.6640625 "(defun graph-body-print (numbers-list)
\"documentation...\"
(let ((height
...
...))
" 5 0) (130.43527221679688 596.7376708984375 332.10687255859375 630.6640625 "(while numbers-list
insert-columns-and-reposition-point
(setq numbers-list (cdr numbers-list)))))
" 6 0)) (227 (90.0 47.60907745361328 449.6184997558594 60.90726852416992 "The graph-body-print Function
209
" 0 0) (90.000732421875 77.48908233642578 295.34228515625 90.78726959228516 "We need to fill in the slots of the template.
" 1 0) (90.00027465820312 95.00910186767578 449.2694396972656 120.18729400634766 "Clearly, we can use the (apply ’max numbers-list) expression to deter-
mine the height of the graph.
" 2 0) (89.99972534179688 124.40912628173828 449.8033142089844 173.5873260498047 "The while loop will cycle through the numbers-list one element at a
time. As it is shortened by the (setq numbers-list (cdr numbers-list))
expression, the car of each instance of the list is the value of the argument
for column-of-graph.
" 3 0) (89.99993896484375 177.80914306640625 449.4870300292969 250.8673553466797 "At each cycle of the while loop, the insert-rectangle function inserts
the list returned by column-of-graph. Since the insert-rectangle func-
tion moves point to the lower right of the inserted rectangle, we need to save
the location of point at the time the rectangle is inserted, move back to that
position after the rectangle is inserted, and then move horizontally to the
next place from which insert-rectangle is called.
" 4 0) (89.99887084960938 255.08917236328125 449.5741882324219 352.1473693847656 "If the inserted columns are one character wide, as they will be if sin-
gle blanks and asterisks are used, the repositioning command is simply
(forward-char 1); however, the width of a column may be greater than one.
This means that the repositioning command should be written (forward-
char symbol-width). The symbol-width itself is the length of a graph-
blank and can be found using the expression (length graph-blank). The
best place to bind the symbol-width variable to the value of the width of
graph column is in the varlist of the let expression.
" 5 0) (104.99847412109375 356.48919677734375 398.8020935058594 369.7873840332031 "These considerations lead to the following function definition:
" 6 0) (111.59848022460938 378.3377380371094 336.9964294433594 412.14422607421875 "(defun graph-body-print (numbers-list)
\"Print a bar graph of the NUMBERS-LIST.
The numbers-list consists of the Y-axis values.\"
" 7 0) (120.958740234375 428.1378479003906 313.43341064453125 461.9442138671875 "(let ((height (apply ’max numbers-list))
(symbol-width (length graph-blank))
from-position)
" 8 0) (111.59880065917969 470.1378479003906 350.92486572265625 630.664306640625 "(while numbers-list
(setq from-position (point))
(insert-rectangle
(column-of-graph height (car numbers-list)))
(goto-char from-position)
(forward-char symbol-width)
;; Draw graph column by column.
(sit-for 0)
(setq numbers-list (cdr numbers-list)))
;; Place point for X axis labels.
(forward-line height)
(insert \"\\n\")
))
" 9 0)) (228 (90.0 47.60907745361328 449.7815246582031 60.90726852416992 "210
Chapter 15: Readying a Graph
" 0 0) (89.998291015625 77.48908233642578 449.4093933105469 166.74729919433594 "The one unexpected expression in this function is the (sit-for 0) expres-
sion in the while loop. This expression makes the graph printing operation
more interesting to watch than it would be otherwise. The expression causes
Emacs to ‘sit’ or do nothing for a zero length of time and then redraw the
screen. Placed here, it causes Emacs to redraw the screen column by column.
Without it, Emacs would not redraw the screen until the function exits.
We can test graph-body-print with a short list of numbers.
" 1 0) (95.87759399414062 170.60906982421875 449.299560546875 207.9072723388672 "1. Install graph-symbol, graph-blank, column-of-graph, which are in
Chapter 15, “Readying a Graph”, page 203, and graph-body-print.
2. Copy the following expression:
" 2 0) (133.19784545898438 216.09762573242188 354.1035461425781 225.0640106201172 "(graph-body-print ’(1 2 3 4 6 4 3 5 7 6 5 2 3))
" 3 0) (95.87825012207031 229.4090576171875 449.2996520996094 254.70726013183594 "3. Switch to the ‘*scratch*’ buffer and place the cursor where you want
the graph to start.
" 4 0) (95.87808990478516 258.56903076171875 258.1071472167969 271.87603759765625 "4. Type M-: (eval-expression).
" 5 0) (95.87834167480469 275.7291259765625 449.4634704589844 300.9073181152344 "5. Yank the graph-body-print expression into the minibuffer with C-y
(yank).
" 6 0) (95.87800598144531 304.76910400390625 143.98455810546875 323.9298095703125 "6. Press ⟨
" 7 0) (143.26800537109375 308.1519775390625 161.38800048828125 308.6319885253906 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (143.27999877929688 309.3624572753906 161.38011169433594 317.3325500488281 "RET
" 9 0) (143.26800537109375 316.7919921875 161.38800048828125 317.2720031738281 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (160.9199981689453 304.4090576171875 389.84722900390625 323.56976318359375 "⟩ to evaluate the graph-body-print expression.
" 11 0) (104.99958801269531 326.2490539550781 267.6866760253906 339.5472412109375 "Emacs will print a graph like this:
" 12 0) (168.11952209472656 346.777587890625 229.15016174316406 430.5039978027344 "*
*
**
*
****
*** ****
********* *
************
*************
" 13 0) (89.99951934814453 455.18035888671875 418.4400939941406 469.5535888671875 "15.2 The recursive-graph-body-print Function
" 14 0) (89.99981689453125 479.48907470703125 449.4435729980469 540.6672973632812 "The graph-body-print function may also be written recursively. The
recursive solution is divided into two parts: an outside ‘wrapper’ that uses
a let expression to determine the values of several variables that need only
be found once, such as the maximum height of the graph, and an inside
function that is called recursively to print the graph.
" 15 0)) (229 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "Need for Printed Axes
211
" 0 0) (104.99908447265625 77.48908233642578 258.9371643066406 90.78726959228516 "The ‘wrapper’ is uncomplicated:
" 1 0) (89.9986572265625 95.85763549804688 449.4972229003906 315.4271545410156 "(defun recursive-graph-body-print (numbers-list)
\"Print a bar graph of the NUMBERS-LIST.
The numbers-list consists of the Y-axis values.\"
(let ((height (apply ’max numbers-list))
(symbol-width (length graph-blank))
from-position)
(recursive-graph-body-print-internal
numbers-list
height
symbol-width)))
The recursive function is a little more difficult. It has four parts: the
‘do-again-test’, the printing code, the recursive call, and the ‘next-step-
expression’. The ‘do-again-test’ is an if expression that determines whether
the numbers-list contains any remaining elements; if it does, the func-
tion prints one column of the graph using the printing code and calls itself
again. The function calls itself again according to the value produced by the
‘next-step-expression’ which causes the call to act on a shorter version of the
numbers-list.
" 2 0) (111.59860229492188 320.6174011230469 341.6420593261719 366.9037780761719 "(defun recursive-graph-body-print-internal
(numbers-list height symbol-width)
\"Print a bar graph.
Used within recursive-graph-body-print function.\"
" 3 0) (120.95841979980469 375.097412109375 360.4049377441406 433.8638000488281 "(if numbers-list
(progn
(setq from-position (point))
(insert-rectangle
(column-of-graph height (car numbers-list)))
" 4 0) (104.998779296875 438.4574279785156 416.28948974609375 513.0670776367188 "(goto-char from-position)
(forward-char symbol-width)
(sit-for 0)
; Draw graph column by column.
(recursive-graph-body-print-internal
(cdr numbers-list) height symbol-width))))
After installation, this expression can be tested; here is a sample:
" 5 0) (104.9993896484375 518.137451171875 379.4596862792969 541.7470703125 "(recursive-graph-body-print ’(3 2 5 6 7 5 3 4 6 4 3 2 1))
Here is what recursive-graph-body-print produces:
" 6 0) (168.1194305419922 546.9374389648438 228.884521484375 630.663818359375 "*
**
*
****
*
**** ***
* *********
************
*************
" 7 0)) (230 (90.0 47.60907745361328 449.7815246582031 60.90726852416992 "212
Chapter 15: Readying a Graph
" 0 0) (89.99948120117188 77.48908233642578 449.8030090332031 102.66727447509766 "Either of these two functions, graph-body-print or recursive-graph-
body-print, create the body of a graph.
" 1 0) (89.999755859375 119.18035125732422 286.32666015625 133.5408935546875 "15.3 Need for Printed Axes
" 2 0) (89.99813842773438 141.2091064453125 449.68231201171875 240.1873016357422 "A graph needs printed axes, so you can orient yourself. For a do-once
project, it may be reasonable to draw the axes by hand using Emacs’ Picture
mode; but a graph drawing function may be used more than once.
For this reason, I have written enhancements to the basic print-graph-
body function that automatically print labels for the horizontal and vertical
axes. Since the label printing functions do not contain much new material,
I have placed their description in an appendix. See Appendix C, “A Graph
with Labelled Axes”, page 255.
" 3 0) (89.99794006347656 256.58038330078125 185.0099639892578 270.94091796875 "15.4 Exercise
" 4 0) (104.99794006347656 278.72918701171875 382.6558837890625 292.0273742675781 "Write a line graph version of the graph printing functions.
" 5 0)) (231 (90.0 47.60907745361328 449.6068420410156 60.90726852416992 "Site-wide Initialization Files
213
" 0 0) (90.00009155273438 75.14844512939453 268.8154296875 92.39627838134766 "16 Your ‘.emacs’ File
" 1 0) (89.9979248046875 105.80908966064453 449.6379699707031 356.2273864746094 "“You don’t have to like Emacs to like it” – this seemingly paradoxical
statement is the secret of GNU Emacs. The plain, ‘out of the box’ Emacs is
a generic tool. Most people who use it, customize it to suit themselves.
GNU Emacs is mostly written in Emacs Lisp; this means that by writing
expressions in Emacs Lisp you can change or extend Emacs.
There are those who appreciate Emacs’ default configuration. After all,
Emacs starts you in C mode when you edit a C file, starts you in Fortran
mode when you edit a Fortran file, and starts you in Fundamental mode
when you edit an unadorned file. This all makes sense, if you do not know
who is going to use Emacs. Who knows what a person hopes to do with an
unadorned file? Fundamental mode is the right default for such a file, just
as C mode is the right default for editing C code. But when you do know
who is going to use Emacs—you, yourself—then it makes sense to customize
Emacs.
For example, I seldom want Fundamental mode when I edit an otherwise
undistinguished file; I want Text mode. This is why I customize Emacs: so
it suits me.
You can customize and extend Emacs by writing or adapting a ‘~/.emacs’
file. This is your personal initialization file; its contents, written in Emacs
Lisp, tell Emacs what to do.1
" 2 0) (89.99703979492188 357.3292541503906 449.4523010253906 495.18743896484375 "A ‘~/.emacs’ file contains Emacs Lisp code. You can write this code
yourself; or you can use Emacs’ customize feature to write the code for
you. You can combine your own expressions and auto-written Customize
expressions in your ‘.emacs’ file.
(I myself prefer to write my own expressions, except for those, particularly
fonts, that I find easier to manipulate using the customize command. I
combine the two methods.)
Most of this chapter is about writing expressions yourself. It describes
a simple ‘.emacs’ file; for more information, see section “The Init File” in
The GNU Emacs Manual, and section “The Init File” in The GNU Emacs
Lisp Reference Manual.
" 3 0) (89.99729919433594 513.6205444335938 324.8603515625 527.9810791015625 "16.1 Site-wide Initialization Files
" 4 0) (89.99746704101562 536.1292724609375 449.2443542480469 573.427490234375 "In addition to your personal initialization file, Emacs automatically loads
various site-wide initialization files, if they exist. These have the same form
as your ‘.emacs’ file, but are loaded by everyone.
" 5 0) (89.98799896240234 583.6719970703125 233.98800659179688 584.1519775390625 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (95.87999725341797 584.6151733398438 449.8329772949219 630.3015747070312 "1 You may also add ‘.el’ to ‘~/.emacs’ and call it a ‘~/.emacs.el’ file. In the past,
you were forbidden to type the extra keystrokes that the name ‘~/.emacs.el’ requires,
but now you may.
The new format is consistent with the Emacs Lisp file naming
conventions; the old format saves typing.
" 7 0)) (232 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "214
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.99765014648438 77.48908233642578 449.716064453125 377.1072998046875 "Two site-wide initialization files, ‘site-load.el’ and ‘site-init.el’,
are loaded into Emacs and then ‘dumped’ if a ‘dumped’ version of Emacs is
created, as is most common. (Dumped copies of Emacs load more quickly.
However, once a file is loaded and dumped, a change to it does not lead
to a change in Emacs unless you load it yourself or re-dump Emacs. See
section “Building Emacs” in The GNU Emacs Lisp Reference Manual, and
the ‘INSTALL’ file.)
Three other site-wide initialization files are loaded automatically each
time you start Emacs, if they exist. These are ‘site-start.el’, which is
loaded before your ‘.emacs’ file, and ‘default.el’, and the terminal type
file, which are both loaded after your ‘.emacs’ file.
Settings and definitions in your ‘.emacs’ file will overwrite conflicting
settings and definitions in a ‘site-start.el’ file, if it exists; but the settings
and definitions in a ‘default.el’ or terminal type file will overwrite those in
your ‘.emacs’ file. (You can prevent interference from a terminal type file by
setting term-file-prefix to nil. See Section 16.11, “A Simple Extension”,
page 224.)
The ‘INSTALL’ file that comes in the distribution contains descriptions of
the ‘site-init.el’ and ‘site-load.el’ files.
The ‘loadup.el’, ‘startup.el’, and ‘loaddefs.el’ files control loading.
These files are in the ‘lisp’ directory of the Emacs distribution and are
worth perusing.
The ‘loaddefs.el’ file contains a good many suggestions as to what to
put into your own ‘.emacs’ file, or into a site-wide initialization file.
" 1 0) (89.99777221679688 394.70037841796875 383.5762634277344 409.0736083984375 "16.2 Specifying Variables using defcustom
" 2 0) (89.99658203125 417.089111328125 449.49432373046875 630.787353515625 "You can specify variables using defcustom so that you and others can
then can use Emacs’ customize feature to set their values. (You cannot use
customize to write function definitions; but you can write defuns in your
‘.emacs’ file. Indeed, you can write any Lisp expression in your ‘.emacs’
file.)
The customize feature depends on the defcustom special form.
Al-
though you can use defvar or setq for variables that users set, the
defcustom special form is designed for the job.
You can use your knowledge of defvar for writing the first three argu-
ments for defcustom. The first argument to defcustom is the name of the
variable. The second argument is the variable’s initial value, if any; and this
value is set only if the value has not already been set. The third argument
is the documentation.
The fourth and subsequent arguments to defcustom specify types and
options; these are not featured in defvar. (These arguments are optional.)
Each of these arguments consists of a keyword followed by a value. Each
keyword starts with the character :.
" 3 0)) (233 (90.0 47.60907745361328 449.5527648925781 60.90726852416992 "Specifying Variables using defcustom
215
" 0 0) (89.99993896484375 80.72907257080078 449.8252868652344 106.02725982666016 "For example, the customizable user option variable text-mode-hook
looks like this:
" 1 0) (89.9986572265625 112.29757690429688 449.87860107421875 400.7470397949219 "(defcustom text-mode-hook nil
\"Normal hook run when entering Text mode and many related modes.\"
:type ’hook
:options ’(turn-on-auto-fill flyspell-mode)
:group ’data)
The name of the variable is text-mode-hook; it has no default value; and
its documentation string tells you what it does.
The :type keyword tells Emacs what kind of data text-mode-hook
should be set to and how to display the value in a Customization buffer.
The :options keyword specifies a suggested list of values for the vari-
able. Currently, you can use :options only for a hook. The list is only a
suggestion; it is not exclusive; a person who sets the variable may set it to
other values; the list shown following the :options keyword is intended to
offer convenient choices to a user.
Finally, the :group keyword tells the Emacs Customization command in
which group the variable is located. This tells where to find it.
For more information, see section “Writing Customization Definitions”
in The GNU Emacs Lisp Reference Manual.
Consider text-mode-hook as an example.
There are two ways to customize this variable.
You can use the cus-
tomization command or write the appropriate expressions yourself.
Using the customization command, you can type:
" 2 0) (90.000244140625 406.89739990234375 449.3674621582031 455.467041015625 "M-x customize
and find that the group for editing files of data is called ‘data’. Enter that
group. Text Mode Hook is the first member. You can click on its various
options to set the values. After you click on the button to
" 3 0) (90.00070190429688 461.7373962402344 449.33465576171875 486.3070373535156 "Save for Future Sessions
Emacs will write an expression into your ‘.emacs’ file. It will look like this:
" 4 0) (90.0 492.4573974609375 450.02301025390625 630.787109375 "(custom-set-variables
;; custom-set-variables was added by Custom --
;;
don’t edit or cut/paste it!
;; Your init file should contain only one such instance.
’(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
(The text-mode-hook-identify function tells toggle-text-mode-auto-
fill which buffers are in Text mode.)
In spite of the warning, you certainly may edit, cut, and paste the ex-
pression! I do all time. The purpose of the warning is to scare those who
do not know what they are doing, so they do not inadvertently generate an
error.
" 5 0)) (234 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "216
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.99960327148438 77.48908233642578 449.69384765625 267.3072814941406 "The custom-set-variables works somewhat differently than a setq.
While I have never learned the differences, I do modify the custom-set-
variables expressions in my ‘.emacs’ file by hand: I make the changes
in what appears to me to be a reasonable manner and have not had any
problems. Others prefer to use the Customization command and let Emacs
do the work for them.
Another custom-set-... function is custom-set-faces. This function
sets the various font faces. Over time, I have set a considerable number
of faces. Some of the time, I re-set them using customize; other times, I
simply edit the custom-set-faces expression in my ‘.emacs’ file itself.
The second way to customize your text-mode-hook is to set it yourself
in your ‘.emacs’ file using code that has nothing to do with the custom-
set-... functions.
When you do this, and later use customize, you will see a message that
says
" 1 0) (105.00048828125 273.3376159667969 396.73077392578125 297.9072570800781 "this option has been changed outside the customize buffer.
This message is only a warning. If you click on the button to
" 2 0) (90.0 303.9375915527344 449.48724365234375 442.0272521972656 "Save for Future Sessions
Emacs will write a custom-set-... expression near the end of your ‘.emacs’
file that will be evaluated after your hand-written expression. It will, there-
fore, overrule your hand-written expression. No harm will be done. When
you do this, however, be careful to remember which expression is active; if
you forget, you may confuse yourself.
So long as you remember where the values are set, you will have no
trouble. In any event, the values are always set in your initialization file,
which is usually called ‘.emacs’.
I myself use customize for hardly anything. Mostly, I write expressions
myself.
" 3 0) (90.00155639648438 462.620361328125 301.0529479980469 476.99359130859375 "16.3 Beginning a ‘.emacs’ File
" 4 0) (89.99954223632812 485.7290954589844 449.42279052734375 630.787353515625 "When you start Emacs, it loads your ‘.emacs’ file unless you tell it not
to by specifying ‘-q’ on the command line. (The emacs -q command gives
you a plain, out-of-the-box Emacs.)
A ‘.emacs’ file contains Lisp expressions. Often, these are no more than
expressions to set values; sometimes they are function definitions.
See section “The Init File ‘~/.emacs’” in The GNU Emacs Manual, for
a short description of initialization files.
This chapter goes over some of the same ground, but is a walk among
extracts from a complete, long-used ‘.emacs’ file—my own.
The first part of the file consists of comments: reminders to myself. By
now, of course, I remember these things, but when I started, I did not.
" 5 0)) (235 (90.0 47.60907745361328 449.7051696777344 60.90726852416992 "Text and Auto Fill Mode
217
" 0 0) (89.99880981445312 81.33761596679688 449.2894592285156 142.0272674560547 ";;;; Bob’s .emacs file
; Robert J. Chassell
; 26 September 1985
Look at that date! I started this file a long time ago. I have been adding to
it ever since.
" 1 0) (89.99789428710938 147.33761596679688 449.4530334472656 256.3872375488281 "; Each section in this file is introduced by a
; line beginning with four semicolons; and each
; entry is introduced by a line beginning with
; three semicolons.
This describes the usual conventions for comments in Emacs Lisp. Every-
thing on a line that follows a semicolon is a comment.
Two, three, and
four semicolons are used as section and subsection markers. (See section
“Comments” in The GNU Emacs Lisp Reference Manual, for more about
comments.)
" 2 0) (89.998291015625 261.5776062011719 341.8045349121094 347.71612548828125 ";;;; The Help Key
; Control-h is the help key;
; after typing control-h, type a letter to
; indicate the subject about which you want help.
; For an explanation of the help facility,
; type control-h two times in a row.
Just remember: type C-h two times for help.
" 3 0) (89.99748992919922 353.0176696777344 449.4955139160156 476.2273254394531 "; To find out about any mode, type control-h m
; while in that mode.
For example, to find out
; about mail mode, enter mail mode and then type
; control-h m.
‘Mode help’, as I call this, is very helpful. Usually, it tells you all you need
to know.
Of course, you don’t need to include comments like these in your ‘.emacs’
file. I included them in mine because I kept forgetting about Mode help or
the conventions for comments—but I was able to remember to look here to
remind myself.
" 4 0) (89.99798583984375 493.5804138183594 305.27545166015625 507.9409484863281 "16.4 Text and Auto Fill Mode
" 5 0) (104.997802734375 515.9691162109375 449.4410400390625 529.267333984375 "Now we come to the part that ‘turns on’ Text mode and Auto Fill mode.
" 6 0) (111.59814453125 534.4577026367188 332.4704284667969 580.8641357421875 ";;; Text mode and Auto Fill mode
; The next three lines put Emacs into Text mode
; and Auto Fill mode, and are for writers who
; want to start writing prose rather than code.
" 7 0) (111.59800720214844 596.7377319335938 350.6168212890625 630.6641235351562 "(setq default-major-mode ’text-mode)
(add-hook ’text-mode-hook ’text-mode-hook-identify)
(add-hook ’text-mode-hook ’turn-on-auto-fill)
" 8 0)) (236 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "218
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.997802734375 77.48908233642578 449.47540283203125 282.3074035644531 "Here is the first part of this ‘.emacs’ file that does something besides
remind a forgetful human!
The first of the two lines in parentheses tells Emacs to turn on Text mode
when you find a file, unless that file should go into some other mode, such
as C mode.
When Emacs reads a file, it looks at the extension to the file name, if
any. (The extension is the part that comes after a ‘.’.) If the file ends with
a ‘.c’ or ‘.h’ extension then Emacs turns on C mode. Also, Emacs looks at
first nonblank line of the file; if the line says ‘-*- C -*-’, Emacs turns on
C mode. Emacs possesses a list of extensions and specifications that it uses
automatically. In addition, Emacs looks near the last page for a per-buffer,
“local variables list”, if any.
See sections “How Major Modes are Chosen” and “Local Variables in
Files” in The GNU Emacs Manual.
Now, back to the ‘.emacs’ file.
Here is the line again; how does it work?
" 1 0) (89.9974365234375 287.6177673339844 449.3984375 424.0274658203125 "(setq default-major-mode ’text-mode)
This line is a short, but complete Emacs Lisp expression.
We are already familiar with setq.
It sets the following variable,
default-major-mode, to the subsequent value, which is text-mode. The
single quote mark before text-mode tells Emacs to deal directly with the
text-mode variable, not with whatever it might stand for. See Section 1.9,
“Setting the Value of a Variable”, page 17, for a reminder of how setq works.
The main point is that there is no difference between the procedure you use
to set a value in your ‘.emacs’ file and the procedure you use anywhere else
in Emacs.
Here are the next two lines:
" 2 0) (89.99603271484375 429.45782470703125 449.8330078125 630.7874755859375 "(add-hook ’text-mode-hook ’text-mode-hook-identify)
(add-hook ’text-mode-hook ’turn-on-auto-fill)
In these two lines, the add-hook command first adds text-mode-hook-
identify to the variable called text-mode-hook and then adds turn-on-
auto-fill to the variable.
turn-on-auto-fill is the name of a program, that, you guessed it!,
turns on Auto Fill mode.
text-mode-hook-identify is a function that
tells toggle-text-mode-auto-fill which buffers are in Text mode.
Every time Emacs turns on Text mode, Emacs runs the commands
‘hooked’ onto Text mode. So every time Emacs turns on Text mode, Emacs
also turns on Auto Fill mode.
In brief, the first line causes Emacs to enter Text mode when you edit
a file, unless the file name extension, first non-blank line, or local variables
tell Emacs otherwise.
Text mode among other actions, sets the syntax table to work conve-
niently for writers. In Text mode, Emacs considers an apostrophe as part
" 3 0)) (237 (90.0 47.60907745361328 449.7597961425781 60.90726852416992 "Indent Tabs Mode
219
" 0 0) (89.99868774414062 77.48908233642578 449.4530334472656 257.2272033691406 "of a word like a letter; but Emacs does not consider a period or a space as
part of a word. Thus, M-f moves you over ‘it’s’. On the other hand, in C
mode, M-f stops just after the ‘t’ of ‘it’s’.
The second and third lines causes Emacs to turn on Auto Fill mode when
it turns on Text mode. In Auto Fill mode, Emacs automatically breaks a
line that is too wide and brings the excessively wide part of the line down
to the next line. Emacs breaks lines between words, not within them.
When Auto Fill mode is turned off, lines continue to the right as you
type them. Depending on how you set the value of truncate-lines, the
words you type either disappear off the right side of the screen, or else are
shown, in a rather ugly and unreadable manner, as a continuation line on
the screen.
In addition, in this part of my ‘.emacs’ file, I tell the Emacs fill commands
to insert two spaces after a colon:
" 1 0) (111.59912109375 263.8575744628906 238.50204467773438 272.8239440917969 "(setq colon-double-space t)
" 2 0) (89.99922180175781 296.4202880859375 213.15521240234375 310.78082275390625 "16.5 Mail Aliases
" 3 0) (104.99922180175781 320.1289978027344 442.67889404296875 333.42718505859375 "Here is a setq that ‘turns on’ mail aliases, along with more reminders.
" 4 0) (111.59918212890625 340.17755126953125 280.6993408203125 386.46392822265625 ";;; Mail mode
; To enter mail mode, type ‘C-x m’
; To enter RMAIL (for reading mail),
; type ‘M-x rmail’
" 5 0) (89.99850463867188 402.3375549316406 449.55133056640625 479.2272033691406 "(setq mail-aliases t)
This setq command sets the value of the variable mail-aliases to t. Since
t means true, the line says, in effect, “Yes, use mail aliases.”
Mail aliases are convenient short names for long email addresses or for
lists of email addresses. The file where you keep your ‘aliases’ is ‘~/.mailrc’.
You write an alias like this:
" 6 0) (89.99819946289062 485.8575439453125 449.3982238769531 522.7872314453125 "alias geo george@foobar.wiz.edu
When you write a message to George, address it to ‘geo’; the mailer will
automatically expand ‘geo’ to the full address.
" 7 0) (89.99813842773438 545.9002685546875 256.8532409667969 560.2608032226562 "16.6 Indent Tabs Mode
" 8 0) (89.99765014648438 569.6090087890625 449.3974609375 633.0672607421875 "By default, Emacs inserts tabs in place of multiple spaces when it formats
a region.
(For example, you might indent many lines of text all at once
with the indent-region command.) Tabs look fine on a terminal or with
ordinary printing, but they produce badly indented output when you use
TEX or Texinfo since TEX ignores tabs.
" 9 0)) (238 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "220
Chapter 16: Your ‘.emacs’ File
" 0 0) (104.99984741210938 80.84906768798828 306.87255859375 94.14725494384766 "The following turns off Indent Tabs mode:
" 1 0) (89.99832153320312 100.53750610351562 449.43115234375 189.06712341308594 ";;; Prevent Extraneous Tabs
(setq-default indent-tabs-mode nil)
Note that this line uses setq-default rather than the setq command
that we have seen before. The setq-default command sets values only in
buffers that do not have their own local values for the variable.
See sections “Tabs vs. Spaces” and “Local Variables in Files” in The
GNU Emacs Manual.
" 2 0) (89.99842834472656 210.8602294921875 257.6563720703125 225.22076416015625 "16.7 Some Keybindings
" 3 0) (104.99842834472656 234.3289794921875 276.07476806640625 247.62718200683594 "Now for some personal keybindings:
" 4 0) (89.996826171875 253.89749145507812 449.42938232421875 423.40960693359375 ";;; Compare windows
(global-set-key \"\\C-cw\" ’compare-windows)
compare-windows is a nifty command that compares the text in your
current window with text in the next window. It makes the comparison by
starting at point in each window, moving over text in each window as far as
they match. I use this command all the time.
This also shows how to set a key globally, for all modes.
The command is global-set-key. It is followed by the keybinding. In a
‘.emacs’ file, the keybinding is written as shown: \\C-c stands for ‘control-
c’, which means ‘press the control key and the c key at the same time’.
The w means ‘press the w key’. The keybinding is surrounded by double
quotation marks. In documentation, you would write this as C-c w. (If you
were binding a ⟨
" 5 0) (167.1479949951172 407.6319885253906 192.46798706054688 408.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (167.16000366210938 408.8424377441406 192.44651794433594 416.8125305175781 "META
" 7 0) (167.1479949951172 416.1520080566406 192.46798706054688 416.63201904296875 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (191.8800048828125 403.8890686035156 355.1866455078125 423.4097900390625 "⟩ key, such as M-c, rather than a ⟨
" 9 0) (354.5879821777344 407.6319885253906 372.22796630859375 408.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (354.6000061035156 408.8424377441406 372.1182861328125 416.8125305175781 "CTL
" 11 0) (354.5879821777344 416.1520080566406 372.22796630859375 416.63201904296875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (89.99749755859375 403.8890686035156 449.82550048828125 630.7872924804688 "⟩ key, you would
write \\M-c. See section “Rebinding Keys in Your Init File” in The GNU
Emacs Manual, for details.)
The command invoked by the keys is compare-windows.
Note that
compare-windows is preceded by a single quote; otherwise, Emacs would
first try to evaluate the symbol to determine its value.
These three things, the double quotation marks, the backslash before the
‘C’, and the single quote mark are necessary parts of keybinding that I tend
to forget. Fortunately, I have come to remember that I should look at my
existing ‘.emacs’ file, and adapt what is there.
As for the keybinding itself: C-c w. This combines the prefix key, C-c,
with a single character, in this case, w. This set of keys, C-c followed by a
single character, is strictly reserved for individuals’ own use. (I call these
‘own’ keys, since these are for my own use.) You should always be able to
create such a keybinding for your own use without stomping on someone
else’s keybinding.
If you ever write an extension to Emacs, please avoid
taking any of these keys for public use. Create a key like C-c C-w instead.
Otherwise, we will run out of ‘own’ keys.
" 13 0)) (239 (90.0 47.60907745361328 449.8367614746094 60.90726852416992 "Keymaps
221
" 0 0) (105.0 80.12909698486328 320.0397644042969 93.42728424072266 "Here is another keybinding, with a comment:
" 1 0) (89.99920654296875 98.85763549804688 449.19195556640625 186.4272918701172 ";;; Keybinding for ‘occur’
; I use occur a lot, so let’s bind it to a key:
(global-set-key \"\\C-co\" ’occur)
The occur command shows all the lines in the current buffer that contain
a match for a regular expression. Matching lines are shown in a buffer called
‘*Occur*’. That buffer serves as a menu to jump to occurrences.
Here is how to unbind a key, so it does not work:
" 2 0) (89.9998779296875 191.97763061523438 449.399658203125 279.0671691894531 ";;; Unbind ‘C-x f’
(global-unset-key \"\\C-xf\")
There is a reason for this unbinding: I found I inadvertently typed C-x f
when I meant to type C-x C-f. Rather than find a file, as I intended, I
accidentally set the width for filled text, almost always to a width I did not
want. Since I hardly ever reset my default width, I simply unbound the key.
The following rebinds an existing key:
" 3 0) (89.99984741210938 284.4975280761719 449.4437255859375 357.0671691894531 ";;; Rebind ‘C-x C-b’ for ‘buffer-menu’
(global-set-key \"\\C-x\\C-b\" ’buffer-menu)
By default, C-x C-b runs the list-buffers command. This command
lists your buffers in another window.
Since I almost always want to do
something in that window, I prefer the buffer-menu command, which not
only lists the buffers, but moves point into that window.
" 4 0) (89.999755859375 375.5002746582031 191.69708251953125 389.8608093261719 "16.8 Keymaps
" 5 0) (90.00009155273438 398.1289978027344 449.9562072753906 500.1159973144531 "Emacs uses keymaps to record which keys call which commands. When
you use global-set-key to set the keybinding for a single command in all
parts of Emacs, you are specifying the keybinding in current-global-map.
Specific modes, such as C mode or Text mode, have their own keymaps;
the mode-specific keymaps override the global map that is shared by all
buffers.
The global-set-key function binds, or rebinds, the global keymap. For
example, the following binds the key C-x C-b to the function buffer-menu:
" 6 0) (90.00030517578125 505.6575012207031 449.3887939453125 565.5159912109375 "(global-set-key \"\\C-x\\C-b\" ’buffer-menu)
Mode-specific keymaps are bound using the define-key function, which
takes a specific keymap as an argument, as well as the key and the command.
For example, my ‘.emacs’ file contains the following expression to bind the
texinfo-insert-@group command to C-c C-c g:
" 7 0) (90.00091552734375 570.9375610351562 449.4007263183594 630.7960205078125 "(define-key texinfo-mode-map \"\\C-c\\C-cg\" ’texinfo-insert-@group)
The texinfo-insert-@group function itself is a little extension to Texinfo
mode that inserts ‘@group’ into a Texinfo file. I use this command all the
time and prefer to type the three strokes C-c C-c g rather than the six
strokes @ g r o u p. (‘@group’ and its matching ‘@end group’ are commands
" 8 0)) (240 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "222
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.99960327148438 77.48908233642578 449.18145751953125 102.66727447509766 "that keep all enclosed text together on one page; many multi-line examples
in this book are surrounded by ‘@group ... @end group’.)
" 1 0) (104.99903869628906 107.36908721923828 374.51904296875 120.66727447509766 "Here is the texinfo-insert-@group function definition:
" 2 0) (111.59944152832031 129.45761108398438 341.69427490234375 188.2239227294922 "(defun texinfo-insert-@group ()
\"Insert the string @group in a Texinfo buffer.\"
(interactive)
(beginning-of-line)
(insert \"@group\\n\"))
" 3 0) (89.99978637695312 194.12896728515625 449.3337097167969 231.3071746826172 "(Of course, I could have used Abbrev mode to save typing, rather than
write a function to insert a word; but I prefer key strokes consistent with
other Texinfo mode key bindings.)
" 4 0) (89.99920654296875 235.76898193359375 449.7041015625 261.0671691894531 "You will see numerous define-key expressions in ‘loaddefs.el’ as well
as in the various mode libraries, such as ‘cc-mode.el’ and ‘lisp-mode.el’.
" 5 0) (89.99978637695312 265.529052734375 449.36669921875 302.8272399902344 "See section “Customizing Key Bindings” in The GNU Emacs Manual,
and section “Keymaps” in The GNU Emacs Lisp Reference Manual, for
more information about keymaps.
" 6 0) (90.0000228881836 334.5802307128906 220.9461669921875 348.9407653808594 "16.9 Loading Files
" 7 0) (89.99893188476562 360.5689392089844 449.4100341796875 409.74713134765625 "Many people in the GNU Emacs community have written extensions to
Emacs. As time goes by, these extensions are often included in new releases.
For example, the Calendar and Diary packages are now part of the standard
GNU Emacs.
" 8 0) (89.99917602539062 414.2089538574219 449.39825439453125 451.50714111328125 "(Calc, which I consider a vital part of Emacs, would be part of the stan-
dard distribution except that it was so large it was packaged separately and
no one has changed that.)
" 9 0) (89.9993896484375 455.9689636230469 449.431396484375 481.26715087890625 "You can use a load command to evaluate a complete file and thereby
install all the functions and variables in the file into Emacs. For example:
" 10 0) (111.59915161132812 490.0574951171875 233.22198486328125 499.02386474609375 "(load \"~/emacs/slowsplit\")
" 11 0) (89.99850463867188 503.968994140625 449.94366455078125 553.147216796875 "This evaluates, i.e. loads, the ‘slowsplit.el’ file or if it exists, the
faster, byte compiled ‘slowsplit.elc’ file from the ‘emacs’ sub-directory of
your home directory. The file contains the function split-window-quietly,
which John Robinson wrote in 1989.
" 12 0) (89.99896240234375 557.72900390625 449.4862365722656 630.7872314453125 "The split-window-quietly function splits a window with the minimum
of redisplay. I installed it in 1989 because it worked well with the slow 1200
baud terminals I was then using. Nowadays, I only occasionally come across
such a slow connection, but I continue to use the function because I like the
way it leaves the bottom half of a buffer in the lower of the new windows
and the top half in the upper window.
" 13 0)) (241 (90.0 47.60907745361328 449.7927551269531 60.90726852416992 "Autoloading
223
" 0 0) (89.9996337890625 80.48908233642578 450.11956787109375 117.78726959228516 "To replace the key binding for the default split-window-vertically,
you must also unset that key and bind the keys to split-window-quietly,
like this:
" 1 0) (89.99832153320312 123.69772338867188 449.310546875 235.6273651123047 "(global-unset-key \"\\C-x2\")
(global-set-key \"\\C-x2\" ’split-window-quietly)
If you load many extensions, as I do, then instead of specifying the exact
location of the extension file, as shown above, you can specify that directory
as part of Emacs’ load-path. Then, when Emacs loads a file, it will search
that directory as well as its default list of directories. (The default list is
specified in ‘paths.h’ when Emacs is built.)
The following command adds your ‘~/emacs’ directory to the existing
load path:
" 2 0) (89.99850463867188 241.53768920898438 449.474609375 290.5873107910156 ";;; Emacs Load Path
(setq load-path (cons \"~/emacs\" load-path))
Incidentally, load-library is an interactive interface to the load func-
tion. The complete function looks like this:
" 3 0) (89.99874877929688 296.4976501464844 449.44268798828125 445.62725830078125 "(defun load-library (library)
\"Load the library named LIBRARY.
This is an interface to the function ‘load’.\"
(interactive \"sLoad library: \")
(load library))
The name of the function, load-library, comes from the use of ‘library’
as a conventional synonym for ‘file’. The source for the load-library com-
mand is in the ‘files.el’ library.
Another interactive command that does a slightly different job is load-
file. See section “Libraries of Lisp Code for Emacs” in The GNU Emacs
Manual, for information on the distinction between load-library and this
command.
" 4 0) (89.99945068359375 465.9803466796875 221.0973358154297 480.34088134765625 "16.10 Autoloading
" 5 0) (89.99960327148438 488.96905517578125 449.4757080078125 630.7872924804688 "Instead of installing a function by loading the file that contains it, or by
evaluating the function definition, you can make the function available but
not actually install it until it is first called. This is called autoloading.
When you execute an autoloaded function, Emacs automatically evalu-
ates the file that contains the definition, and then calls the function.
Emacs starts quicker with autoloaded functions, since their libraries are
not loaded right away; but you need to wait a moment when you first use
such a function, while its containing file is evaluated.
Rarely used functions are frequently autoloaded. The ‘loaddefs.el’ li-
brary contains hundreds of autoloaded functions, from bookmark-set to
wordstar-mode. Of course, you may come to use a ‘rare’ function frequently.
" 6 0)) (242 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "224
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.99957275390625 77.48908233642578 449.2901306152344 102.66727447509766 "When you do, you should load that function’s file with a load expression in
your ‘.emacs’ file.
" 1 0) (89.99896240234375 109.16907501220703 449.3658752441406 170.34727478027344 "In my ‘.emacs’ file for Emacs version 21, I load 12 libraries that contain
functions that would otherwise be autoloaded. (Actually, it would have been
better to include these files in my ‘dumped’ Emacs when I built it, but I
forgot. See section “Building Emacs” in The GNU Emacs Lisp Reference
Manual, and the ‘INSTALL’ file for more about dumping.)
" 2 0) (89.99822998046875 176.84906005859375 449.52984619140625 273.7872619628906 "You may also want to include autoloaded expressions in your ‘.emacs’
file. autoload is a built-in function that takes up to five arguments, the final
three of which are optional. The first argument is the name of the function
to be autoloaded; the second is the name of the file to be loaded. The third
argument is documentation for the function, and the fourth tells whether
the function can be called interactively. The fifth argument tells what type
of object—autoload can handle a keymap or macro as well as a function
(the default is a function).
" 3 0) (104.99821472167969 280.4090576171875 228.4018096923828 293.7072448730469 "Here is a typical example:
" 4 0) (111.59820556640625 304.5376281738281 323.101806640625 325.8639831542969 "(autoload ’html-helper-mode
\"html-helper-mode\" \"Edit HTML documents\" t)
" 5 0) (89.99798583984375 333.6890869140625 449.35430908203125 358.9872741699219 "(html-helper-mode is an alternative to html-mode, which is a standard part
of the distribution).
" 6 0) (89.998291015625 365.48907470703125 449.4641418457031 474.4272766113281 "This expression autoloads the html-helper-mode function.
It takes
it from the ‘html-helper-mode.el’ file (or from the byte compiled
file ‘html-helper-mode.elc’, if it exists.)
The file must be located
in a directory specified by load-path.
The documentation says that
this is a mode to help you edit documents written in the HyperText
Markup Language.
You can call this mode interactively by typing
M-x html-helper-mode.
(You need to duplicate the function’s regular
documentation in the autoload expression because the regular function is
not yet loaded, so its documentation is not available.)
" 7 0) (90.00003051757812 480.9290771484375 449.3565979003906 506.1072692871094 "See section “Autoload” in The GNU Emacs Lisp Reference Manual, for
more information.
" 8 0) (90.00003051757812 545.900390625 443.0364685058594 560.2736206054688 "16.11 A Simple Extension: line-to-top-of-window
" 9 0) (89.99969482421875 573.80908203125 449.3343505859375 598.9873046875 "Here is a simple extension to Emacs that moves the line point is on to
the top of the window. I use this all the time, to make text easier to read.
" 10 0) (89.99972534179688 605.4890747070312 449.3442687988281 630.7872924804688 "You can put the following code into a separate file and then load it from
your ‘.emacs’ file, or you can include it within your ‘.emacs’ file.
" 11 0)) (243 (90.0 47.60907745361328 449.4981384277344 60.90726852416992 "A Simple Extension: line-to-top-of-window
225
" 0 0) (105.0003662109375 80.24909210205078 208.15664672851562 93.54727935791016 "Here is the definition:
" 1 0) (89.99951171875 99.21762084960938 449.4330749511719 257.80975341796875 ";;; Line to top of window;
;;; replace three keystroke sequence
C-u 0 C-l
(defun line-to-top-of-window ()
\"Move the line point is on to top of window.\"
(interactive)
(recenter 0))
Now for the keybinding.
Nowadays, function keys as well as mouse button events and non-ascii
characters are written within square brackets, without quotation marks. (In
Emacs version 18 and before, you had to write different function key bindings
for each different make of terminal.)
I bind line-to-top-of-window to my ⟨
" 2 0) (295.6679992675781 242.031982421875 305.50799560546875 242.51197814941406 "<image: None, width: 1, height: 1, bpc: 1>" 3 1) (295.67999267578125 243.2423858642578 305.42742919921875 251.21249389648438 "F6
" 4 0) (295.6679992675781 250.6719970703125 305.50799560546875 251.15199279785156 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (304.9200134277344 238.2890625 415.0254211425781 257.44976806640625 "⟩ function key like this:
" 6 0) (90.0006103515625 257.6175842285156 449.4771423339844 332.2272644042969 "(global-set-key [f6] ’line-to-top-of-window)
For more information, see section “Rebinding Keys in Your Init File” in
The GNU Emacs Manual.
If you run two versions of GNU Emacs, such as versions 20 and 21, and
use one ‘.emacs’ file, you can select which code to evaluate with the following
conditional:
" 7 0) (90.00177001953125 337.8976135253906 449.8439025878906 460.8673095703125 "(cond
((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
;; evaluate version 20 code
( ... ))
((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
;; evaluate version 21 code
( ... )))
For example, in contrast to version 20, version 21 blinks its cursor by
default. I hate such blinking, as well as some other features in version 21,
so I placed the following in my ‘.emacs’ file2:
" 8 0) (111.60176086425781 466.53765869140625 379.4029541015625 537.7840576171875 "(if (string-equal \"21\" (substring (emacs-version) 10 12))
(progn
(blink-cursor-mode 0)
;; Insert newline when you press ‘C-n’ (next-line)
;; at the end of the buffer
(setq next-line-add-newlines t)
" 9 0) (139.80267333984375 542.3777465820312 252.5625 563.7041015625 ";; Turn on image viewing
(auto-image-file-mode t)
" 10 0) (89.98799896240234 576.83203125 233.98800659179688 577.31201171875 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (95.87999725341797 577.7752075195312 449.695556640625 601.5015869140625 "2 When I start instances of Emacs that do not load my ‘.emacs’ file or any site file, I
also turn off blinking:
" 12 0) (111.60002136230469 607.6576538085938 369.92974853515625 616.6240234375 "emacs -q --no-site-file -eval ’(blink-cursor-mode nil)’
" 13 0)) (244 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "226
Chapter 16: Your ‘.emacs’ File
" 0 0) (139.79983520507812 81.33761596679688 323.05126953125 115.14396667480469 ";; Turn on menu bar (this bar has text)
;; (Use numeric argument to turn on)
(menu-bar-mode 1)
" 1 0) (139.7993621826172 119.73757934570312 332.3942565917969 153.54393005371094 ";; Turn off tool bar (this bar has icons)
;; (Use numeric argument to turn on)
(tool-bar-mode nil)
" 2 0) (89.9983139038086 158.13754272460938 449.42047119140625 317.1070861816406 ";; Turn off tooltip mode for tool bar
;; (This mode causes icon explanations to pop up)
;; (Use numeric argument to turn on)
(tooltip-mode nil)
;; If tooltips turned on, make tips appear promptly
(setq tooltip-delay 0.1)
; default is one second
))
(You will note that instead of typing (number-to-string 21), I decided to
save typing and wrote ‘21’ as a string, \"21\", rather than convert it from
an integer to a string. In this instance, this expression is better than the
longer, but more general (number-to-string 21). However, if you do not
know ahead of time what type of information will be returned, then the
number-to-string function will be needed.)
" 3 0) (89.99819946289062 334.4601745605469 213.5362548828125 348.8207092285156 "16.12 X11 Colors
" 4 0) (89.99786376953125 356.8489074707031 449.4737243652344 410.58709716796875 "You can specify colors when you use Emacs with the MIT X Windowing
system.
I dislike the default colors and specify my own.
Here are the expressions in my ‘.emacs’ file that set values:
" 5 0) (111.59766387939453 415.8974609375 233.58056640625 437.22381591796875 ";; Set cursor color
(set-cursor-color \"white\")
" 6 0) (111.59765625 453.2174377441406 228.9090576171875 474.663818359375 ";; Set mouse color
(set-mouse-color \"white\")
" 7 0) (111.59715270996094 490.5374450683594 266.4002685546875 524.4638671875 ";; Set foreground and background
(set-foreground-color \"white\")
(set-background-color \"darkblue\")
" 8 0) (111.59686279296875 532.5375366210938 337.1236267089844 566.4638671875 ";;; Set highlighting colors for isearch and drag
(set-face-foreground ’highlight \"white\")
(set-face-background ’highlight \"blue\")
" 9 0) (111.59764099121094 574.6575317382812 280.6638488769531 595.98388671875 "(set-face-foreground ’region \"cyan\")
(set-face-background ’region \"blue\")
" 10 0) (111.59764099121094 604.1775512695312 360.43914794921875 625.6239013671875 "(set-face-foreground ’secondary-selection \"skyblue\")
(set-face-background ’secondary-selection \"darkblue\")
" 11 0)) (245 (90.0 47.60907745361328 449.7377624511719 60.90726852416992 "A Modified Mode Line
227
" 0 0) (89.99899291992188 81.33761596679688 449.4208068847656 221.2272186279297 ";; Set calendar highlighting colors
(setq calendar-load-hook
’(lambda ()
(set-face-foreground ’diary-face
\"skyblue\")
(set-face-background ’holiday-face \"slate blue\")
(set-face-foreground ’holiday-face \"white\")))
The various shades of blue soothe my eye and prevent me from seeing the
screen flicker.
Alternatively, I could have set my specifications in various X initialization
files.
For example, I could set the foreground, background, cursor, and
pointer (i.e., mouse) colors in my ‘~/.Xresources’ file like this:
" 1 0) (90.00018310546875 228.21755981445312 449.4210205078125 303.3071594238281 "Emacs*foreground:
white
Emacs*background:
darkblue
Emacs*cursorColor:
white
Emacs*pointerColor: white
In any event, since it is not part of Emacs, I set the root color of my X
window in my ‘~/.xinitrc’ file, like this3:
" 2 0) (111.60017395019531 310.2975158691406 262.00592041015625 331.7438659667969 "# I use TWM for window manager.
xsetroot -solid Navy -fg white &
" 3 0) (90.00057983398438 355.94024658203125 422.62066650390625 370.3134765625 "16.13 Miscellaneous Settings for a ‘.emacs’ File
" 4 0) (105.00030517578125 380.12896728515625 284.8038635253906 393.4271545410156 "Here are a few miscellaneous settings:
" 5 0) (95.88038635253906 403.0489807128906 324.239990234375 424.0926513671875 "− Set the shape and color of the mouse cursor:
" 6 0) (133.2006072998047 424.4175109863281 363.4073791503906 470.7038879394531 "; Cursor shapes are defined in
; ‘/usr/include/X11/cursorfont.h’;
; for example, the ‘target’ cursor is number 128;
; the ‘top_left_arrow’ cursor is number 132.
" 7 0) (133.2008514404297 478.89752197265625 377.26629638671875 576.06396484375 "(let ((mpointer (x-get-resource \"*mpointer\"
\"*emacs*mpointer\")))
;; If you have not set your mouse pointer
;;
then set it, otherwise leave as is:
(if (eq mpointer nil)
(setq mpointer \"132\")) ; top_left_arrow
(setq x-pointer-shape (string-to-int mpointer))
(set-mouse-color \"white\"))
" 8 0) (89.98799896240234 594.5919799804688 233.98800659179688 595.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (95.87999725341797 595.5352172851562 449.712646484375 630.3015747070312 "3 I occasionally run more modern window managers, such as Sawfish with GNOME,
Enlightenment, SCWM, or KDE; in those cases, I often specify an image rather than
a plain color.
" 10 0)) (246 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "228
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.99984741210938 77.30034637451172 296.3206481933594 91.66089630126953 "16.14 A Modified Mode Line
" 1 0) (104.99964904785156 118.64917755126953 354.27215576171875 131.94737243652344 "Finally, a feature I really like: a modified mode line.
" 2 0) (89.99966430664062 152.0091552734375 449.3778381347656 177.18736267089844 "When I work over a network, I forget which machine I am using. Also, I
tend to I lose track of where I am, and which line point is on.
" 3 0) (104.99942016601562 197.2491455078125 299.32275390625 210.54734802246094 "So I reset my mode line to look like this:
" 4 0) (111.59967041015625 234.81765747070312 421.7272033691406 243.78404235839844 "-:-- foo.texi
rattlesnake:/home/bob/
Line 1
(Texinfo Fill) Top
" 5 0) (89.99969482421875 264.2091064453125 449.3335266113281 301.3872985839844 "I am visiting a file called ‘foo.texi’, on my machine ‘rattlesnake’ in
my ‘/home/bob’ buffer. I am on line 1, in Texinfo mode, and am at the top
of the buffer.
" 6 0) (104.9998779296875 321.4490966796875 342.7850646972656 334.7472839355469 "My ‘.emacs’ file has a section that looks like this:
" 7 0) (111.5999755859375 359.13763427734375 416.73065185546875 630.6642456054688 ";; Set a Mode Line that tells me which machine, which directory,
;; and which line I am on, plus the other customary information.
(setq default-mode-line-format
(quote
(#(\"-\" 0 1
(help-echo
\"mouse-1: select window, mouse-2: delete others ...\"))
mode-line-mule-info
mode-line-modified
mode-line-frame-identification
\"
\"
mode-line-buffer-identification
\"
\"
(:eval (substring
(system-name) 0 (string-match \"\\\\..+\" (system-name))))
\":\"
default-directory
#(\" \" 0 1
(help-echo
\"mouse-1: select window, mouse-2: delete others ...\"))
(line-number-mode \" Line %l \")
global-mode-string
" 8 0)) (247 (90.0 47.60907745361328 449.7377624511719 60.90726852416992 "A Modified Mode Line
229
" 0 0) (89.99972534179688 81.33761596679688 449.5201721191406 397.26702880859375 "#(\"
%[(\" 0 6
(help-echo
\"mouse-1: select window, mouse-2: delete others ...\"))
(:eval (mode-line-mode-name))
mode-line-process
minor-mode-alist
#(\"%n\" 0 2 (help-echo \"mouse-2: widen\" local-map (keymap ...)))
\")%] \"
(-3 . \"%P\")
;;
\"-%-\"
)))
Here, I redefine the default mode line. Most of the parts are from the original;
but I make a few changes. I set the default mode line format so as to permit
various modes, such as Info, to override it.
Many elements in the list are self-explanatory: mode-line-modified is
a variable that tells whether the buffer has been modified, mode-name tells
the name of the mode, and so on. However, the format looks complicated
because of two features we have not discussed.
The first string in the mode line is a dash or hyphen, ‘-’. In the old days,
it would have been specified simply as \"-\". But nowadays, Emacs can add
properties to a string, such as highlighting or, as in this case, a help feature.
If you place your mouse cursor over the hyphen, some help information ap-
pears (By default, you must wait one second before the information appears.
You can change that timing by changing the value of tooltip-delay.)
The new string format has a special syntax:
" 1 0) (89.99746704101562 403.7774963378906 449.70263671875 630.7872314453125 "#(\"-\" 0 1 (help-echo \"mouse-1: select window, ...\"))
The #( begins a list. The first element of the list is the string itself, just one
‘-’. The second and third elements specify the range over which the fourth
element applies. A range starts after a character, so a zero means the range
starts just before the first character; a 1 means that the range ends just
after the first character. The third element is the property for the range.
It consists of a property list, a property name, in this case, ‘help-echo’,
followed by a value, in this case, a string. The second, third, and fourth
elements of this new string format can be repeated.
See section “Text Properties in String” in The GNU Emacs Lisp Refer-
ence Manual, and see section “Mode Line Format” in The GNU Emacs Lisp
Reference Manual, for more information.
mode-line-buffer-identification displays the current buffer name.
It is a list beginning (#(\"%12b\" 0 4 .... The #( begins the list.
The ‘\"%12b\"’ displays the current buffer name, using the buffer-name
function with which we are familiar; the ‘12’ specifies the maximum number
of characters that will be displayed. When a name has fewer characters,
whitespace is added to fill out to this number. (Buffer names can and often
" 2 0)) (248 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "230
Chapter 16: Your ‘.emacs’ File
" 0 0) (89.99917602539062 77.48908233642578 449.3553161621094 190.5072479248047 "should be longer than 12 characters; this length works well in a typical 80
column wide window.)
:eval is a new feature in GNU Emacs version 21. It says to evaluate
the following form and use the result as a string to display. In this case, the
expression displays the first component of the full system name. The end of
the first component is a ‘.’ (‘period’), so I use the string-match function
to tell me the length of the first component. The substring from the zeroth
character to that length is the name of the machine.
This is the expression:
" 1 0) (89.9991455078125 195.45761108398438 449.4214172363281 343.1471252441406 "(:eval (substring
(system-name) 0 (string-match \"\\\\..+\" (system-name))))
‘%[’ and ‘%]’ cause a pair of square brackets to appear for each recursive
editing level. ‘%n’ says ‘Narrow’ when narrowing is in effect. ‘%P’ tells you
the percentage of the buffer that is above the bottom of the window, or
‘Top’, ‘Bottom’, or ‘All’. (A lower case ‘p’ tell you the percentage above the
top of the window.) ‘%-’ inserts enough dashes to fill out the line.
Remember, “You don’t have to like Emacs to like it” — your own Emacs
can have different colors, different commands, and different keys than a
default Emacs.
On the other hand, if you want to bring up a plain ‘out of the box’ Emacs,
with no customization, type:
" 2 0) (89.99972534179688 348.21746826171875 448.9084777832031 383.4671325683594 "emacs -q
This will start an Emacs that does not load your ‘~/.emacs’ initialization
file. A plain, default Emacs. Nothing more.
" 3 0)) (249 (90.0 47.60907745361328 449.8577575683594 60.90726852416992 "debug
231
" 0 0) (90.0 75.14844512939453 209.640869140625 92.38106536865234 "17 Debugging
" 1 0) (89.99993896484375 118.76905059814453 449.4760437011719 155.94725036621094 "GNU Emacs has two debuggers, debug and edebug. The first is built
into the internals of Emacs and is always with you; the second requires that
you instrument a function before you can use it.
" 2 0) (89.99966430664062 159.68896484375 449.4106750488281 196.86717224121094 "Both debuggers are described extensively in section “Debugging Lisp Pro-
grams” in The GNU Emacs Lisp Reference Manual. In this chapter, I will
walk through a short example of each.
" 3 0) (89.99916076660156 225.6202392578125 163.8074951171875 239.9934539794922 "17.1 debug
" 4 0) (89.99832153320312 250.76898193359375 449.5943908691406 299.9471740722656 "Suppose you have written a function definition that is intended to return
the sum of the numbers 1 through a given number. (This is the triangle
function discussed earlier.
See “Example with Decrementing Counter”,
page 129, for a discussion.)
" 5 0) (89.99783325195312 303.68896484375 449.3213806152344 328.8671569824219 "However, your function definition has a bug. You have mistyped ‘1=’ for
‘1-’. Here is the broken definition:
" 6 0) (111.5978012084961 336.9375 360.49871826171875 420.6639099121094 "(defun triangle-bugged (number)
\"Return sum of numbers 1 through NUMBER inclusive.\"
(let ((total 0))
(while (> number 0)
(setq total (+ total number))
(setq number (1= number)))
; Error here.
total))
" 7 0) (89.99765014648438 425.1289978027344 449.4194641113281 450.30718994140625 "If you are reading this in Info, you can evaluate this definition in the
normal fashion. You will see triangle-bugged appear in the echo area.
" 8 0) (104.99725341796875 454.16900634765625 432.64068603515625 467.4671936035156 "Now evaluate the triangle-bugged function with an argument of 4:
" 9 0) (111.59686279296875 475.53753662109375 200.87939453125 484.50390625 "(triangle-bugged 4)
" 10 0) (89.9962158203125 488.72900390625 449.428955078125 514.0272216796875 "In GNU Emacs version 21, you will create and enter a ‘*Backtrace*’ buffer
that says:
" 11 0) (111.59619140625 522.0975952148438 370.0963134765625 630.6639404296875 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function 1=)
(1= number)
(setq number (1= number))
(while (> number 0) (setq total (+ total number))
(setq number (1= number)))
(let ((total 0)) (while (> number 0) (setq total ...)
(setq number ...)) total)
triangle-bugged(4)
" 12 0)) (250 (90.0 47.60907745361328 449.7052917480469 60.90726852416992 "232
Chapter 17: Debugging
" 0 0) (90.000244140625 81.33761596679688 449.72747802734375 222.18724060058594 "eval((triangle-bugged 4))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(I have reformatted this example slightly; the debugger does not fold long
lines. As usual, you can quit the debugger by typing q in the ‘*Backtrace*’
buffer.)
In practice, for a bug as simple as this, the ‘Lisp error’ line will tell you
what you need to know to correct the definition. The function 1= is ‘void’.
In GNU Emacs 20 and before, you will see:
" 1 0) (90.00033569335938 228.21755981445312 449.79351806640625 396.0672302246094 "Symbol’s function definition is void: 1=
which has the same meaning as the ‘*Backtrace*’ buffer line in version 21.
However, suppose you are not quite certain what is going on? You can
read the complete backtrace.
In this case, you need to run GNU Emacs 21, which automatically starts
the debugger that puts you in the ‘*Backtrace*’ buffer; or else, you need to
start the debugger manually as described below.
Read the ‘*Backtrace*’ buffer from the bottom up; it tells you what
Emacs did that led to the error. Emacs made an interactive call to C-x C-
e (eval-last-sexp), which led to the evaluation of the triangle-bugged
expression. Each line above tells you what the Lisp interpreter evaluated
next.
The third line from the top of the buffer is
" 2 0) (89.99984741210938 402.09759521484375 449.0939636230469 438.42724609375 "(setq number (1= number))
Emacs tried to evaluate this expression; in order to do so, it tried to evaluate
the inner expression shown on the second line from the top:
" 3 0) (89.99957275390625 444.4576110839844 344.79180908203125 468.9072570800781 "(1= number)
This is where the error occurred; as the top line says:
" 4 0) (89.99951171875 474.9376220703125 449.268310546875 511.26727294921875 "Debugger entered--Lisp error: (void-function 1=)
You can correct the mistake, re-evaluate the function definition, and then
run your test again.
" 5 0) (89.99955749511719 531.620361328125 230.68991088867188 545.9935913085938 "17.2 debug-on-entry
" 6 0) (89.99832153320312 554.7291259765625 449.40924072265625 630.787353515625 "GNU Emacs 21 starts the debugger automatically when your function
has an error. GNU Emacs version 20 and before did not; it simply presented
you with an error message. You had to start the debugger manually.
You can start the debugger manually for all versions of Emacs; the ad-
vantage is that the debugger runs even if you do not have a bug in your
code. Sometimes your code will be free of bugs!
" 7 0)) (251 (90.0 47.60907745361328 449.759765625 60.90726852416992 "debug-on-entry
233
" 0 0) (89.99948120117188 77.48908233642578 449.57415771484375 102.66727447509766 "You can enter the debugger when you call the function by calling debug-
on-entry.
" 1 0) (89.9994888305664 107.36908721923828 117.58861541748047 120.66727447509766 "Type:
" 2 0) (111.59953308105469 129.69760131835938 308.9515380859375 138.6639862060547 "M-x debug-on-entry RET triangle-bugged RET
" 3 0) (89.99925231933594 143.96905517578125 224.41024780273438 157.2672576904297 "Now, evaluate the following:
" 4 0) (111.59932708740234 166.29757690429688 200.88185119628906 175.2639617919922 "(triangle-bugged 5)
" 5 0) (89.9990234375 180.44903564453125 449.24578857421875 205.7472381591797 "All versions of Emacs will create a ‘*Backtrace*’ buffer and tell you that it
is beginning to evaluate the triangle-bugged function:
" 6 0) (111.59938049316406 214.77755737304688 304.0321960449219 311.9438171386719 "---------- Buffer: *Backtrace* ----------
Debugger entered--entering a function:
* triangle-bugged(5)
eval((triangle-bugged 5))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 7 0) (90.00021362304688 317.36883544921875 449.37847900390625 342.5470275878906 "In the ‘*Backtrace*’ buffer, type d. Emacs will evaluate the first expres-
sion in triangle-bugged; the buffer will look like this:
" 8 0) (111.59967041015625 351.577392578125 398.2072448730469 422.82379150390625 "---------- Buffer: *Backtrace* ----------
Debugger entered--beginning evaluation of function call form:
* (let ((total 0)) (while (> number 0) (setq total ...)
(setq number ...)) total)
* triangle-bugged(5)
eval((triangle-bugged 5))
" 9 0) (111.60005187988281 427.41741943359375 304.0321044921875 473.70379638671875 "eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 10 0) (90.00042724609375 479.1288757324219 449.40045166015625 504.42706298828125 "Now, type d again, eight times, slowly. Each time you type d, Emacs will
evaluate another expression in the function definition.
" 11 0)) (252 (90.0 47.60907745361328 449.7052917480469 60.90726852416992 "234
Chapter 17: Debugging
" 0 0) (104.99993896484375 77.48908233642578 296.290771484375 90.78726959228516 "Eventually, the buffer will look like this:
" 1 0) (111.59968566894531 103.05758666992188 398.207275390625 261.4237365722656 "---------- Buffer: *Backtrace* ----------
Debugger entered--beginning evaluation of function call form:
* (setq number (1= number))
* (while (> number 0) (setq total (+ total number))
(setq number (1= number)))
* (let ((total 0)) (while (> number 0) (setq total ...)
(setq number ...)) total)
* triangle-bugged(5)
eval((triangle-bugged 5))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 2 0) (90.00027465820312 270.08880615234375 449.42193603515625 295.2669982910156 "Finally, after you type d two more times, Emacs will reach the error, and
the top two lines of the ‘*Backtrace*’ buffer will look like this:
" 3 0) (111.60057067871094 307.5373229980469 337.10186767578125 366.3036804199219 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function 1=)
* (1= number)
...
---------- Buffer: *Backtrace* ----------
" 4 0) (105.00100708007812 374.9687805175781 375.38262939453125 388.2757873535156 "By typing d, you were able to step through the function.
" 5 0) (90.00067138671875 396.2087707519531 449.25885009765625 421.5069580078125 "You can quit a ‘*Backtrace*’ buffer by typing q in it; this quits the trace,
but does not cancel debug-on-entry.
" 6 0) (90.00041198730469 429.3287658691406 450.06536865234375 454.626953125 "To cancel the effect of debug-on-entry, call cancel-debug-on-entry
and the name of the function, like this:
" 7 0) (111.60076904296875 466.8973083496094 341.7730712890625 475.8636779785156 "M-x cancel-debug-on-entry RET triangle-bugged RET
" 8 0) (90.00077819824219 484.28875732421875 384.5679626464844 497.5869445800781 "(If you are reading this in Info, cancel debug-on-entry now.)
" 9 0) (90.00112915039062 543.02001953125 311.1403503417969 557.3932495117188 "17.3 debug-on-quit and (debug)
" 10 0) (90.002197265625 572.3687744140625 449.38018798828125 597.5469970703125 "In addition to setting debug-on-error or calling debug-on-entry, there
are two other ways to start debug.
" 11 0) (90.00314331054688 605.48876953125 449.3376159667969 630.7869873046875 "You can start debug whenever you type C-g (keyboard-quit) by setting
the variable debug-on-quit to t. This is useful for debugging infinite loops.
" 12 0)) (253 (90.0 47.60907745361328 449.6074523925781 60.90726852416992 "The edebug Source Level Debugger
235
" 0 0) (90.00088500976562 84.92908477783203 449.3564453125 110.1072769165039 "Or, you can insert a line that says (debug) into your code where you
want the debugger to start, like this:
" 1 0) (111.60133361816406 120.45761108398438 362.31689453125 216.5438690185547 "(defun triangle-bugged (number)
\"Return sum of numbers 1 through NUMBER inclusive.\"
(let ((total 0))
(while (> number 0)
(setq total (+ total number))
(debug)
; Start debugger.
(setq number (1= number)))
; Error here.
total))
" 2 0) (90.00149536132812 223.2889404296875 449.28082275390625 248.58714294433594 "The debug function is described in detail in section “The Lisp Debugger”
in The GNU Emacs Lisp Reference Manual.
" 3 0) (90.0010986328125 286.22021484375 371.6729431152344 300.59344482421875 "17.4 The edebug Source Level Debugger
" 4 0) (90.00030517578125 313.64892578125 449.40069580078125 350.8271179199219 "Edebug is a source level debugger. Edebug normally displays the source
of the code you are debugging, with an arrow at the left that shows which
line you are currently executing.
" 5 0) (89.99984741210938 356.84893798828125 449.4544982910156 382.1471252441406 "You can walk through the execution of a function, line by line, or run
quickly until reaching a breakpoint where execution stops.
" 6 0) (90.00018310546875 388.0489501953125 449.44317626953125 413.3471374511719 "Edebug is described in section “Edebug” in The GNU Emacs Lisp Ref-
erence Manual.
" 7 0) (90.00006103515625 419.24896240234375 449.4328918457031 456.5471496582031 "Here is a bugged function definition for triangle-recursively.
See
Section 11.3.4, “Recursion in place of a counter”, page 137, for a review of
it.
" 8 0) (111.599853515625 466.7774963378906 355.8294982910156 562.9839477539062 "(defun triangle-recursively-bugged (number)
\"Return sum of numbers 1 through NUMBER inclusive.
Uses recursion.\"
(if (= number 1)
1
(+ number
(triangle-recursively-bugged
(1= number)))))
; Error here.
" 9 0) (89.99929809570312 569.6090087890625 449.44305419921875 630.7872314453125 "Normally, you would install this definition by positioning your cursor after
the function’s closing parenthesis and typing C-x C-e (eval-last-sexp) or
else by positioning your cursor within the definition and typing C-M-x (eval-
defun). (By default, the eval-defun command works only in Emacs Lisp
mode or in Lisp Interactive mode.)
" 10 0)) (254 (90.0 47.60907745361328 449.7052917480469 60.90726852416992 "236
Chapter 17: Debugging
" 0 0) (89.99969482421875 79.76905059814453 449.5307922363281 116.9472427368164 "However, to prepare this function definition for Edebug, you must first
instrument the code using a different command. You can do this by posi-
tioning your cursor within the definition and typing
" 1 0) (89.999755859375 122.13748168945312 449.2470703125 183.7960205078125 "M-x edebug-defun RET
This will cause Emacs to load Edebug automatically if it is not already
loaded, and properly instrument the function.
After instrumenting the function, place your cursor after the following
expression and type C-x C-e (eval-last-sexp):
" 2 0) (89.9986572265625 189.09756469726562 450.0429382324219 272.4671936035156 "(triangle-recursively-bugged 3)
You will be jumped back to the source for triangle-recursively-bugged
and the cursor positioned at the beginning of the if line of the function.
Also, you will see an arrowhead at the left hand side of that line.
The
arrowhead marks the line where the function is executing. (In the following
examples, we show the arrowhead with ‘=>’; in a windowing system, you
may see the arrowhead as a solid triangle in the window ‘fringe’.)
" 3 0) (89.99859619140625 277.6551513671875 449.2233581542969 333.169677734375 "=>⋆(if (= number 1)
In the example, the location of point is displayed with a star, ‘⋆’ (in Info, it
is displayed as ‘-!-’).
If you now press ⟨
" 4 0) (196.42800903320312 317.3919677734375 213.10800170898438 317.8719787597656 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (196.44000244140625 318.6024475097656 212.98594665527344 326.5725402832031 "SPC
" 6 0) (196.42800903320312 326.031982421875 213.10800170898438 326.5119934082031 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (90.0001220703125 314.009033203125 449.770751953125 339.3072204589844 "⟩, point will move to the next expression to be
executed; the line will look like this:
" 8 0) (90.00045013427734 344.49517822265625 209.8671112060547 373.9697570800781 "=>(if ⋆(= number 1)
As you continue to press ⟨
" 9 0) (209.2679901123047 358.1919860839844 225.947998046875 358.6719970703125 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (209.27999877929688 359.4024353027344 225.82594299316406 367.3725280761719 "SPC
" 11 0) (209.2679901123047 366.7120056152344 225.947998046875 367.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (89.99957275390625 354.80908203125 449.5962219238281 403.9872741699219 "⟩, point will move from expression to expression.
At the same time, whenever an expression returns a value, that value will be
displayed in the echo area. For example, after you move point past number,
you will see the following:
" 13 0) (89.9998779296875 409.1776428222656 449.410888671875 470.8273010253906 "Result: 3 = C-c
This means the value of number is 3, which is ascii ‘control-c’ (the third
letter of the alphabet).
You can continue moving through the code until you reach the line with
the error. Before evaluation, that line looks like this:
" 14 0) (89.99934387207031 476.0152587890625 357.9283752441406 505.6098327636719 "=>
⋆(1= number)))))
; Error here.
When you press ⟨
" 15 0) (175.30799865722656 489.8320007324219 191.98800659179688 490.31201171875 "<image: None, width: 1, height: 1, bpc: 1>" 16 1) (175.32000732421875 491.04241943359375 191.86595153808594 499.01251220703125 "SPC
" 17 0) (175.30799865722656 498.35198974609375 191.98800659179688 498.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 18 1) (90.00021362304688 486.0890808105469 449.4761657714844 511.6272888183594 "⟩ once again, you will produce an error message that
says:
" 19 0) (89.99929809570312 516.9376831054688 449.44342041015625 630.787353515625 "Symbol’s function definition is void: 1=
This is the bug.
Press q to quit Edebug.
To remove instrumentation from a function definition, simply re-evaluate
it with a command that does not instrument it. For example, you could
place your cursor after the definition’s closing parenthesis and type C-x C-e.
Edebug does a great deal more than walk with you through a function.
You can set it so it races through on its own, stopping only at an error or at
specified stopping points; you can cause it to display the changing values of
" 20 0)) (255 (90.0 47.60907745361328 449.7165222167969 60.90726852416992 "Debugging Exercises
237
" 0 0) (89.999267578125 77.48908233642578 449.44244384765625 128.58726501464844 "various expressions; you can find out how many times a function is called,
and more.
Edebug is described in section “Edebug” in The GNU Emacs Lisp Ref-
erence Manual.
" 1 0) (89.99943542480469 143.90032958984375 272.0467529296875 158.2608642578125 "17.5 Debugging Exercises
" 2 0) (98.99880981445312 164.009033203125 449.4974670410156 320.56976318359375 "• Install the count-words-region function and then cause it to enter
the built-in debugger when you call it. Run the command on a region
containing two words. You will need to press d a remarkable number of
times. On your system, is a ‘hook’ called after the command finishes?
(For information on hooks, see section “Command Loop Overview” in
The GNU Emacs Lisp Reference Manual.)
• Copy count-words-region into the ‘*scratch*’ buffer, instrument the
function for Edebug, and walk through its execution. The function does
not need to have a bug, although you can introduce one if you wish. If
the function lacks a bug, the walk-through completes without problems.
• While running Edebug, type ? to see a list of all the Edebug commands.
(The global-edebug-prefix is usually C-x X, i.e. ⟨
" 3 0) (360.1080017089844 304.7919921875 377.74798583984375 305.2720031738281 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (360.1199951171875 306.0024108886719 377.6382751464844 313.9725036621094 "CTL
" 5 0) (360.1080017089844 313.43194580078125 377.74798583984375 313.9119567871094 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (99.0001220703125 301.4090576171875 449.9346618652344 470.2272644042969 "⟩-x followed by
an upper case X; use this prefix for commands made outside of the
Edebug debugging buffer.)
• In the Edebug debugging buffer, use the p (edebug-bounce-point)
command to see where in the region the count-words-region is work-
ing.
• Move point to some spot further down function and then type the h
(edebug-goto-here) command to jump to that location.
• Use the t (edebug-trace-mode) command to cause Edebug to walk
through the function on its own; use an upper case T for edebug-Trace-
fast-mode.
• Set a breakpoint, then run Edebug in Trace mode until it reaches the
stopping point.
" 7 0)) (256 (90.0 47.60907745361328 449.7052917480469 60.90726852416992 "238
Chapter 17: Debugging
" 0 0)) (257 (90.0 47.60907745361328 449.80377197265625 60.90726852416992 "Conclusion
239
" 0 0) (90.0 75.14844512939453 211.89610290527344 92.38106536865234 "18 Conclusion
" 1 0) (89.99923706054688 107.72907257080078 449.71612548828125 630.7874145507812 "We have now reached the end of this Introduction. You have now learned
enough about programming in Emacs Lisp to set values, to write simple
‘.emacs’ files for yourself and your friends, and write simple customizations
and extensions to Emacs.
This is a place to stop. Or, if you wish, you can now go onward, and
teach yourself.
You have learned some of the basic nuts and bolts of programming. But
only some. There are a great many more brackets and hinges that are easy
to use that we have not touched.
A path you can follow right now lies among the sources to GNU Emacs
and in The GNU Emacs Lisp Reference Manual.
The Emacs Lisp sources are an adventure. When you read the sources
and come across a function or expression that is unfamiliar, you need to
figure out or find out what it does.
Go to the Reference Manual. It is a thorough, complete, and fairly easy-
to-read description of Emacs Lisp. It is written not only for experts, but
for people who know what you know. (The Reference Manual comes with
the standard GNU Emacs distribution. Like this introduction, it comes as
a Texinfo source file, so you can read it on-line and as a typeset, printed
book.)
Go to the other on-line help that is part of GNU Emacs: the on-line
documentation for all functions, and find-tags, the program that takes
you to sources.
Here is an example of how I explore the sources. Because of its name,
‘simple.el’ is the file I looked at first, a long time ago. As it happens some
of the functions in ‘simple.el’ are complicated, or at least look complicated
at first sight. The open-line function, for example, looks complicated.
You may want to walk through this function slowly, as we did with
the forward-sentence function. (See Section 12.3, “forward-sentence”,
page 151.)
Or you may want to skip that function and look at another,
such as split-line. You don’t need to read all the functions. According
to count-words-in-defun, the split-line function contains 27 words and
symbols.
Even though it is short, split-line contains four expressions we have
not studied: skip-chars-forward, indent-to, current-column and ‘?\\n’.
Consider the skip-chars-forward function. (It is part of the function
definition for back-to-indentation, which is shown in Section 3.11, “Re-
view”, page 46.)
In GNU Emacs, you can find out more about skip-chars-forward by
typing C-h f (describe-function) and the name of the function. This gives
you the function documentation.
" 2 0)) (258 (90.0 47.60907745361328 449.7052307128906 60.90726852416992 "240
Chapter 18: Conclusion
" 0 0) (89.99966430664062 77.48908233642578 449.879638671875 608.8273315429688 "You may be able to guess what is done by a well named function such as
indent-to; or you can look it up, too. Incidentally, the describe-function
function itself is in ‘help.el’; it is one of those long, but decipherable func-
tions. You can look up describe-function using the C-h f command!
In this instance, since the code is Lisp, the ‘*Help*’ buffer contains the
name of the library containing the function’s source. You can put point over
the name of the library and press the RET key, which in this situation is
bound to help-follow, and be taken directly to the source, in the same way
as M-. (find-tag).
The definition for describe-function illustrates how to customize the
interactive expression without using the standard character codes; and it
shows how to create a temporary buffer.
(The indent-to function is written in C rather than Emacs Lisp; it is a
‘built-in’ function. help-follow only provides you with the documentation
of a built-in function; it does not take you to the source. But find-tag will
take you to the source, if properly set up.)
You can look at a function’s source using find-tag, which is bound to
M-. Finally, you can find out what the Reference Manual has to say by
visiting the manual in Info, and typing i (Info-index) and the name of the
function, or by looking up skip-chars-forward in the index to a printed
copy of the manual.
Similarly, you can find out what is meant by ‘?\\n’. You can try using
Info-index with ‘?\\n’. It turns out that this action won’t help; but don’t
give up. If you search the index for ‘\\n’ without the ‘?’, you will be taken
directly to the relevant section of the manual. (See section “Character Type”
in The GNU Emacs Lisp Reference Manual. ‘?\\n’ stands for the newline
character.)
Other interesting source files include ‘paragraphs.el’, ‘loaddefs.el’,
and ‘loadup.el’. The ‘paragraphs.el’ file includes short, easily understood
functions as well as longer ones. The ‘loaddefs.el’ file contains the many
standard autoloads and many keymaps. I have never looked at it all; only at
parts. ‘loadup.el’ is the file that loads the standard parts of Emacs; it tells
you a great deal about how Emacs is built. (See section “Building Emacs”
in The GNU Emacs Lisp Reference Manual, for more about building.)
As I said, you have learned some nuts and bolts; however, and very
importantly, we have hardly touched major aspects of programming; I have
said nothing about how to sort information, except to use the predefined
sort function; I have said nothing about how to store information, except
to use variables and lists; I have said nothing about how to write programs
that write programs. These are topics for another, and different kind of
book, a different kind of learning.
What you have done is learn enough for much practical work with GNU
Emacs. What you have done is get started. This is the end of a beginning.
" 1 0)) (259 (90.0 47.60907745361328 449.7167053222656 60.90726852416992 "The the-the Function
241
" 0 0) (89.99993896484375 75.14844512939453 385.3857421875 92.39627838134766 "Appendix A The the-the Function
" 1 0) (89.99908447265625 116.36908721923828 449.3442687988281 165.5472869873047 "Sometimes when you you write text, you duplicate words—as with “you
you” near the beginning of this sentence.
I find that most frequently, I
duplicate “the’; hence, I call the function for detecting duplicated words,
the-the.
" 2 0) (89.9990234375 168.80908203125 449.18048095703125 194.10728454589844 "As a first step, you could use the following regular expression to search
for duplicates:
" 3 0) (111.59898376464844 201.69760131835938 209.98439025878906 210.6639862060547 "\\\\(\\\\w+[ \\t\\n]+\\\\)\\\\1
" 4 0) (89.99728393554688 214.4090576171875 449.40875244140625 311.3472595214844 "This regexp matches one or more word-constituent characters followed by
one or more spaces, tabs, or newlines. However, it does not detect duplicated
words on different lines, since the ending of the first word, the end of the
line, is different from the ending of the second word, a space. (For more
information about regular expressions, see Chapter 12, “Regular Expression
Searches”, page 149, as well as section “Syntax of Regular Expressions” in
The GNU Emacs Manual, and section “Regular Expressions” in The GNU
Emacs Lisp Reference Manual.)
" 5 0) (89.99703979492188 314.60906982421875 449.298583984375 351.7872619628906 "You might try searching just for duplicated word-constituent characters
but that does not work since the pattern detects doubles such as the two
occurrences of ‘th’ in ‘with the’.
" 6 0) (89.99652099609375 355.049072265625 449.3636779785156 404.2272644042969 "Another possible regexp searches for word-constituent characters followed
by non-word-constituent characters, reduplicated. Here, ‘\\\\w+’ matches one
or more word-constituent characters and ‘\\\\W*’ matches zero or more non-
word-constituent characters.
" 7 0) (111.59663391113281 411.8175048828125 219.0765380859375 420.78387451171875 "\\\\(\\\\(\\\\w+\\\\)\\\\W*\\\\)\\\\1
" 8 0) (89.99663543701172 424.5289611816406 174.82574462890625 437.8271484375 "Again, not useful.
" 9 0) (89.99600219726562 441.0889587402344 449.39605712890625 490.26715087890625 "Here is the pattern that I use. It is not perfect, but good enough. ‘\\\\b’
matches the empty string, provided it is at the beginning or end of a word;
‘[^@ \\n\\t]+’ matches one or more occurrences of any characters that are
not an @-sign, space, newline, or tab.
" 10 0) (111.59626770019531 497.8575134277344 266.407958984375 506.8238830566406 "\\\\b\\\\([^@ \\n\\t]+\\\\)[ \\n\\t]+\\\\1\\\\b
" 11 0) (89.9959716796875 510.5689697265625 449.286865234375 535.7471923828125 "One can write more complicated expressions, but I found that this ex-
pression is good enough, so I use it.
" 12 0) (89.99673461914062 539.0089721679688 449.3086853027344 564.3071899414062 "Here is the the-the function, as I include it in my ‘.emacs’ file, along
with a handy global key binding:
" 13 0) (111.59669494628906 571.8975219726562 355.9373474121094 630.6639404296875 "(defun the-the ()
\"Search forward for for a duplicated word.\"
(interactive)
(message \"Searching for for duplicated words ...\")
(push-mark)
" 14 0)) (260 (90.0 47.60907745361328 449.4977722167969 60.90726852416992 "242
Appendix A: The the-the Function
" 0 0) (120.9596176147461 81.33761596679688 360.63751220703125 152.5839080810547 ";; This regexp is not perfect
;; but is fairly good over all:
(if (re-search-forward
\"\\\\b\\\\([^@ \\n\\t]+\\\\)[ \\n\\t]+\\\\1\\\\b\" nil ’move)
(message \"Found duplicated word.\")
(message \"End of buffer\")))
" 1 0) (111.59918212890625 160.65750122070312 271.2027587890625 182.10386657714844 ";; Bind ‘the-the’ to
C-c \\
(global-set-key \"\\C-c\\\\\" ’the-the)
" 2 0) (104.99959564208984 195.32891845703125 184.79949951171875 208.6271209716797 "Here is test text:
" 3 0) (89.99990844726562 213.57748413085938 449.48699951171875 261.6671447753906 "one two two three four five
five six seven
You can substitute the other regular expressions shown above in the func-
tion definition and try each of them on this list.
" 4 0)) (261 (90.0 47.60907745361328 449.5860900878906 60.90726852416992 "The rotate-yank-pointer Function
243
" 0 0) (90.00033569335938 75.14844512939453 397.6617126464844 92.38106536865234 "Appendix B Handling the Kill Ring
" 1 0) (89.99948120117188 109.40906524658203 449.63983154296875 158.58726501464844 "The kill ring is a list that is transformed into a ring by the workings of the
rotate-yank-pointer function. The yank and yank-pop commands use the
rotate-yank-pointer function. This appendix describes the rotate-yank-
pointer function as well as both the yank and the yank-pop commands.
" 2 0) (89.99972534179688 179.78033447265625 362.2185974121094 194.15354919433594 "B.1 The rotate-yank-pointer Function
" 3 0) (89.9993896484375 203.1290283203125 449.4104919433594 267.5472106933594 "The rotate-yank-pointer function changes the element in the kill ring
to which kill-ring-yank-pointer points.
For example, it can change
kill-ring-yank-pointer from pointing to the second element to point to
the third element.
Here is the code for rotate-yank-pointer:
" 4 0) (111.59986877441406 273.6975402832031 327.68035888671875 319.9838562011719 "(defun rotate-yank-pointer (arg)
\"Rotate the yanking point in the kill ring.\"
(interactive \"p\")
(let ((length (length kill-ring)))
" 5 0) (130.43954467773438 324.57757568359375 280.7508544921875 358.3839416503906 "(if (zerop length)
;; then-part
(error \"Kill ring is empty\")
" 6 0) (89.99948120117188 362.9752502441406 449.3123474121094 498.9073486328125 ";; else-part
(setq kill-ring-yank-pointer
(nthcdr (% (+ arg
(- length
(length
kill-ring-yank-pointer)))
length)
kill-ring)))))
The rotate-yank-pointer function looks complex, but as usual, it can
be understood by taking it apart piece by piece. First look at it in skeletal
form:
" 7 0) (89.99908447265625 505.0577087402344 449.52984619140625 630.7874145507812 "(defun rotate-yank-pointer (arg)
\"Rotate the yanking point in the kill ring.\"
(interactive \"p\")
(let varlist
body...)
This function takes one argument, called arg. It has a brief documen-
tation string; and it is interactive with a small ‘p’, which means that the
argument must be a processed prefix passed to the function as a number.
The body of the function definition is a let expression, which itself has
a body as well as a varlist.
" 8 0)) (262 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "244
Appendix B: Handling the Kill Ring
" 0 0) (89.99810791015625 77.48908233642578 449.4527587890625 212.34727478027344 "The let expression declares a variable that will be only usable within
the bounds of this function. This variable is called length and is bound to
a value that is equal to the number of items in the kill ring. This is done
by using the function called length. (Note that this function has the same
name as the variable called length; but one use of the word is to name the
function and the other is to name the variable. The two are quite distinct.
Similarly, an English speaker will distinguish between the meanings of the
word ‘ship’ when he says: \"I must ship this package immediately.\" and \"I
must get aboard the ship immediately.\")
The function length tells the number of items there are in a list, so
(length kill-ring) returns the number of items there are in the kill ring.
" 1 0) (89.99765014648438 223.92181396484375 344.27325439453125 237.03736877441406 "B.1.1 The Body of rotate-yank-pointer
" 2 0) (89.99658203125 245.12908935546875 449.4191589355469 334.14727783203125 "The body of rotate-yank-pointer is a let expression and the body of
the let expression is an if expression.
The purpose of the if expression is to find out whether there is anything
in the kill ring. If the kill ring is empty, the error function stops evaluation
of the function and prints a message in the echo area. On the other hand, if
the kill ring has something in it, the work of the function is done.
Here is the if-part and then-part of the if expression:
" 3 0) (89.99295043945312 339.09521484375 449.54620361328125 630.787353515625 "(if (zerop length)
; if-part
(error \"Kill ring is empty\")
; then-part
...
If there is not anything in the kill ring, its length must be zero and an error
message sent to the user: ‘Kill ring is empty’. The if expression uses the
function zerop which returns true if the value it is testing is zero. When
zerop tests true, the then-part of the if is evaluated.
The then-part is
a list starting with the function error, which is a function that is similar
to the message function (see Section 1.8.5, “message”, page 16), in that it
prints a one-line message in the echo area. However, in addition to printing
a message, error also stops evaluation of the function within which it is
embedded. This means that the rest of the function will not be evaluated if
the length of the kill ring is zero.
(In my opinion, it is slightly misleading, at least to humans, to use the
term ‘error’ as the name of the error function. A better term would be
‘cancel’. Strictly speaking, of course, you cannot point to, much less rotate
a pointer to a list that has no length, so from the point of view of the
computer, the word ‘error’ is correct. But a human expects to attempt this
sort of thing, if only to find out whether the kill ring is full or empty. This
is an act of exploration.
(From the human point of view, the act of exploration and discovery is
not necessarily an error, and therefore should not be labelled as one, even in
the bowels of a computer. As it is, the code in Emacs implies that a human
who is acting virtuously, by exploring his or her environment, is making an
" 4 0)) (263 (90.0 47.60907745361328 449.59625244140625 60.90726852416992 "The else-part of the if expression
245
" 0 0) (89.99960327148438 77.48908233642578 449.30206298828125 114.66727447509766 "error. This is bad. Even though the computer takes the same steps as it
does when there is an ‘error’, a term such as ‘cancel’ would have a clearer
connotation.)
" 1 0) (89.99960327148438 142.80181884765625 307.27386474609375 155.91737365722656 "The else-part of the if expression
" 2 0) (89.99932861328125 168.9290771484375 449.3880615234375 206.10728454589844 "The else-part of the if expression is dedicated to setting the value of
kill-ring-yank-pointer when the kill ring has something in it. The code
looks like this:
" 3 0) (111.59935760498047 216.09762573242188 374.2825927734375 287.3439025878906 "(setq kill-ring-yank-pointer
(nthcdr (% (+ arg
(- length
(length kill-ring-yank-pointer)))
length)
kill-ring)))))
" 4 0) (89.99948120117188 293.6090087890625 449.3883056640625 342.7872009277344 "This needs some examination. Clearly, kill-ring-yank-pointer is be-
ing set to be equal to some cdr of the kill ring, using the nthcdr function
that is described in an earlier section. (See Section 8.5, “copy-region-as-kill”,
page 102.) But exactly how does it do this?
" 5 0) (89.99923706054688 348.4490051269531 449.6280517578125 373.627197265625 "Before looking at the details of the code let’s first consider the purpose
of the rotate-yank-pointer function.
" 6 0) (89.99945068359375 379.28900146484375 449.8468933105469 464.2272033691406 "The rotate-yank-pointer function changes what kill-ring-yank-
pointer points to. If kill-ring-yank-pointer starts by pointing to the
first element of a list, a call to rotate-yank-pointer causes it to point to
the second element; and if kill-ring-yank-pointer points to the second
element, a call to rotate-yank-pointer causes it to point to the third ele-
ment. (And if rotate-yank-pointer is given an argument greater than 1,
it jumps the pointer that many elements.)
" 7 0) (89.99969482421875 469.8890075683594 449.65057373046875 542.947265625 "The rotate-yank-pointer function uses setq to reset what the kill-
ring-yank-pointer points to. If kill-ring-yank-pointer points to the
first element of the kill ring, then, in the simplest case, the rotate-yank-
pointer function must cause it to point to the second element. Put another
way, kill-ring-yank-pointer must be reset to have a value equal to the
cdr of the kill ring.
" 8 0) (104.99984741210938 548.6090087890625 273.90509033203125 561.9072265625 "That is, under these circumstances,
" 9 0) (111.59974670410156 571.8975830078125 398.1379699707031 593.2239379882812 "(setq kill-ring-yank-pointer
(\"some text\" \"a different piece of text\" \"yet more text\"))
" 10 0) (111.59976196289062 609.2175903320312 398.13800048828125 630.6639404296875 "(setq kill-ring
(\"some text\" \"a different piece of text\" \"yet more text\"))
" 11 0)) (264 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "246
Appendix B: Handling the Kill Ring
" 0 0) (90.0 80.12909698486328 204.185302734375 93.42728424072266 "the code should do this:
" 1 0) (90.00028991699219 98.97763061523438 381.4365234375 122.94730377197266 "(setq kill-ring-yank-pointer (cdr kill-ring))
As a result, the kill-ring-yank-pointer will look like this:
" 2 0) (90.00003051757812 128.49765014648438 449.5750427246094 218.2273406982422 "kill-ring-yank-pointer
⇒ (\"a different piece of text\" \"yet more text\"))
The actual setq expression uses the nthcdr function to do the job.
As we have seen before (see Section 7.3, “nthcdr”, page 85), the nthcdr
function works by repeatedly taking the cdr of a list—it takes the cdr of
the cdr of the cdr . . .
The two following expressions produce the same result:
" 3 0) (111.6005859375 223.77767944335938 322.8389892578125 232.7440643310547 "(setq kill-ring-yank-pointer (cdr kill-ring))
" 4 0) (90.00112915039062 248.61758422851562 449.34625244140625 296.7073059082031 "(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
In the rotate-yank-pointer function, however, the first argument to
nthcdr is a rather complex looking expression with lots of arithmetic inside
of it:
" 5 0) (90.00030517578125 302.2576599121094 449.85797119140625 440.82733154296875 "(% (+ arg
(- length
(length kill-ring-yank-pointer)))
length)
As usual, we need to look at the most deeply embedded expression first
and then work our way towards the light.
The most deeply embedded expression is (length kill-ring-yank-
pointer). This finds the length of the current value of the kill-ring-
yank-pointer. (Remember that the kill-ring-yank-pointer is the name
of a variable whose value is a list.)
The measurement of the length is inside the expression:
" 6 0) (89.99703979492188 446.377685546875 449.5494079589844 630.787353515625 "(- length (length kill-ring-yank-pointer))
In this expression, the first length is the variable that was assigned the
length of the kill ring in the let statement at the beginning of the function.
(One might think this function would be clearer if the variable length were
named length-of-kill-ring instead; but if you look at the text of the
whole function, you will see that it is so short that naming this variable
length is not a bother, unless you are pulling the function apart into very
tiny pieces as we are doing here.)
So the line (- length (length kill-ring-yank-pointer)) tells the dif-
ference between the length of the kill ring and the length of the list whose
name is kill-ring-yank-pointer.
To see how all this fits into the rotate-yank-pointer function, let’s
begin by analyzing the case where kill-ring-yank-pointer points to the
first element of the kill ring, just as kill-ring does, and see what happens
when rotate-yank-pointer is called with an argument of 1.
" 7 0)) (265 (90.0 47.60907745361328 449.6838073730469 60.90726852416992 "The % remainder function
247
" 0 0) (89.99972534179688 77.48908233642578 449.68310546875 126.66727447509766 "The variable length and the value of the expression (length kill-ring-
yank-pointer) will be the same since the variable length is the length of
the kill ring and the kill-ring-yank-pointer is pointing to the whole kill
ring. Consequently, the value of
" 1 0) (89.99969482421875 133.05764770507812 449.26861572265625 169.74729919433594 "(- length (length kill-ring-yank-pointer))
will be zero. Since the value of arg will be 1, this will mean that the value
of the whole expression
" 2 0) (90.00006103515625 176.13766479492188 449.410888671875 228.1873016357422 "(+ arg (- length (length kill-ring-yank-pointer)))
will be 1.
Consequently, the argument to nthcdr will be found as the result of the
expression
" 3 0) (111.60005950927734 234.57766723632812 167.8306121826172 243.54405212402344 "(% 1 length)
" 4 0) (89.99999237060547 261.60186767578125 254.54827880859375 274.7174377441406 "The % remainder function
" 5 0) (89.99942016601562 284.129150390625 449.3667907714844 315.28985595703125 "To understand (% 1 length), we need to understand %. According to its
documentation (which I just found by typing C-h f % ⟨
" 6 0) (350.8680114746094 299.51202392578125 368.9880065917969 299.9920349121094 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (350.8800048828125 300.7224426269531 368.9801330566406 308.6925354003906 "RET
" 8 0) (350.8680114746094 308.031982421875 368.9880065917969 308.5119934082031 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (90.00033569335938 296.129150390625 449.8035888671875 549.9728393554688 "⟩), the % function
returns the remainder of its first argument divided by its second argument.
For example, the remainder of 5 divided by 2 is 1. (2 goes into 5 twice with
a remainder of 1.)
What surprises people who don’t often do arithmetic is that a smaller
number can be divided by a larger number and have a remainder. In the
example we just used, 5 was divided by 2. We can reverse that and ask,
what is the result of dividing 2 by 5? If you can use fractions, the answer
is obviously 2/5 or .4; but if, as here, you can only use whole numbers, the
result has to be something different. Clearly, 5 can go into 2 zero times, but
what of the remainder? To see what the answer is, consider a case that has
to be familiar from childhood:
• 5 divided by 5 is 1 with a remainder of 0;
• 6 divided by 5 is 1 with a remainder of 1;
• 7 divided by 5 is 1 with a remainder of 2.
• Similarly, 10 divided by 5 is 2 with a remainder of 0;
• 11 divided by 5 is 2 with a remainder of 1;
• 12 divided by 5 is 1 with a remainder of 2.
" 10 0) (89.99810791015625 548.7291870117188 382.10009765625 602.412841796875 "By considering the cases as parallel, we can see that
• zero divided by 5 must be zero with a remainder of zero;
• 1 divided by 5 must be zero with a remainder of 1;
" 11 0) (98.9991455078125 597.8092041015625 354.3260803222656 618.8528442382812 "• 2 divided by 5 must be zero with a remainder of 2;
" 12 0) (89.999267578125 617.4891967773438 139.03549194335938 630.7874145507812 "and so on.
" 13 0)) (266 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "248
Appendix B: Handling the Kill Ring
" 0 0) (105.0 79.64905548095703 449.1590270996094 92.9472427368164 "So, in this code, if the value of length is 5, then the result of evaluating
" 1 0) (89.99970245361328 98.13748168945312 449.22479248046875 133.51593017578125 "(% 1 5)
is 1. (I just checked this by placing the cursor after the expression and typing
C-x C-e. Indeed, 1 is printed in the echo area.)
" 2 0) (89.99960327148438 147.24169921875 288.00830078125 160.3572540283203 "Using % in rotate-yank-pointer
" 3 0) (89.99893188476562 168.5689697265625 449.3772277832031 205.74717712402344 "When the kill-ring-yank-pointer points to the beginning of the kill
ring, and the argument passed to rotate-yank-pointer is 1, the % expres-
sion returns 1:
" 4 0) (89.99905395507812 210.81753540039062 308.3424987792969 248.10716247558594 "(- length (length kill-ring-yank-pointer))
⇒ 0
therefore,
" 5 0) (89.99905395507812 253.17752075195312 345.97137451171875 290.3471374511719 "(+ arg (- length (length kill-ring-yank-pointer)))
⇒ 1
and consequently:
" 6 0) (89.99925231933594 295.5375061035156 449.29046630859375 370.2671813964844 "(% (+ arg (- length (length kill-ring-yank-pointer)))
length)
⇒ 1
regardless of the value of length.
As a result of this, the setq kill-ring-yank-pointer expression simplifies
to:
" 7 0) (89.99874877929688 375.4575500488281 449.3985900878906 534.667236328125 "(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
What it does is now easy to understand. Instead of pointing as it did to the
first element of the kill ring, the kill-ring-yank-pointer is set to point
to the second element.
Clearly, if the argument passed to rotate-yank-pointer is two, then
the kill-ring-yank-pointer is set to (nthcdr 2 kill-ring); and so on
for different values of the argument.
Similarly, if the kill-ring-yank-pointer starts out pointing to the sec-
ond element of the kill ring, its length is shorter than the length of the kill
ring by 1, so the computation of the remainder is based on the expression
(% (+ arg 1) length). This means that the kill-ring-yank-pointer is
moved from the second element of the kill ring to the third element if the
argument passed to rotate-yank-pointer is 1.
" 8 0) (89.99937438964844 548.4017944335938 270.2720947265625 561.5057983398438 "Pointing to the last element
" 9 0) (89.99728393554688 569.6090087890625 449.88897705078125 630.7872314453125 "The final question is, what happens if the kill-ring-yank-pointer is
set to the last element of the kill ring? Will a call to rotate-yank-pointer
mean that nothing more can be taken from the kill ring? The answer is no.
What happens is different and useful. The kill-ring-yank-pointer is set
to point to the beginning of the kill ring instead.
" 10 0)) (267 (90.0 47.60907745361328 449.8687438964844 60.90726852416992 "yank
249
" 0 0) (89.99960327148438 77.48908233642578 449.35595703125 126.66727447509766 "Let’s see how this works by looking at the code, assuming the length of
the kill ring is 5 and the argument passed to rotate-yank-pointer is 1.
When the kill-ring-yank-pointer points to the last element of the kill
ring, its length is 1. The code looks like this:
" 1 0) (111.59956359863281 138.33761596679688 398.0950927734375 147.3040008544922 "(% (+ arg (- length (length kill-ring-yank-pointer))) length)
" 2 0) (90.00009155273438 155.24908447265625 449.2903747558594 180.5472869873047 "When the variables are replaced by their numeric values, the expression
looks like this:
" 3 0) (111.6001205444336 192.33761596679688 200.92491149902344 201.3040008544922 "(% (+ 1 (- 5 1)) 5)
" 4 0) (89.99957275390625 209.12908935546875 449.4755859375 258.3072814941406 "This expression can be evaluated by looking at the most embedded inner
expression first and working outwards: The value of (- 5 1) is 4; the sum
of (+ 1 4) is 5; and the remainder of dividing 5 by 5 is zero.
So what
rotate-yank-pointer will do is
" 5 0) (111.60002899169922 269.9776306152344 346.32427978515625 278.9440002441406 "(setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
" 6 0) (90.0 286.88909912109375 449.33428955078125 312.0672912597656 "which will set the kill-ring-yank-pointer to point to the beginning of
the kill ring.
" 7 0) (89.99960327148438 319.5292053222656 449.4432678222656 392.58740234375 "So what happens with successive calls to rotate-yank-pointer is that
it moves the kill-ring-yank-pointer from element to element in the kill
ring until it reaches the end; then it jumps back to the beginning. And this
is why the kill ring is called a ring, since by jumping back to the beginning,
it is as if the list has no end! (And what is a ring, but an entity with no
end?)
" 8 0) (89.99960327148438 435.9804992675781 151.69439697265625 450.3537292480469 "B.2 yank
" 9 0) (89.99942016601562 464.7292175292969 449.5086975097656 502.02740478515625 "After learning about rotate-yank-pointer, the code for the yank func-
tion is almost easy. It has only one tricky part, which is the computation of
the argument to be passed to rotate-yank-pointer.
" 10 0) (104.99951171875 509.4892578125 220.8540496826172 522.7874755859375 "The code looks like this:
" 11 0) (111.5993423461914 534.4578247070312 374.7461242675781 630.6641845703125 "(defun yank (&optional arg)
\"Reinsert the last stretch of killed text.
More precisely, reinsert the stretch of killed text most
recently killed OR yanked.
With just C-U as argument, same but put point in front
(and mark at end).
With argument n, reinsert the nth
most recently killed stretch of killed text.
See also the command \\\\[yank-pop].\"
" 12 0)) (268 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "250
Appendix B: Handling the Kill Ring
" 0 0) (90.0003662109375 93.81759643554688 449.487548828125 288.9071350097656 "(interactive \"*P\")
(rotate-yank-pointer (if (listp arg) 0
(if (eq arg ’-) -1
(1- arg))))
(push-mark (point))
(insert (car kill-ring-yank-pointer))
(if (consp arg)
(exchange-point-and-mark)))
Glancing over this code, we can understand the last few lines readily
enough. The mark is pushed, that is, remembered; then the first element
(the car) of what the kill-ring-yank-pointer points to is inserted; and
then, if the argument passed the function is a cons, point and mark are
exchanged so the point is put in the front of the inserted text rather than at
the end. This option is explained in the documentation. The function itself
is interactive with \"*P\". This means it will not work on a read-only buffer,
and that the unprocessed prefix argument is passed to the function.
" 1 0) (90.00021362304688 304.44171142578125 229.5188446044922 317.54571533203125 "Passing the argument
" 2 0) (90.00021362304688 326.24896240234375 449.5088195800781 416.7070617675781 "The hard part of yank is understanding the computation that determines
the value of the argument passed to rotate-yank-pointer. Fortunately, it
is not so difficult as it looks at first sight.
What happens is that the result of evaluating one or both of the if
expressions will be a number and that number will be the argument passed
to rotate-yank-pointer.
Laid out with comments, the code looks like this:
" 3 0) (89.99798583984375 422.375 449.4751281738281 630.7871704101562 "(if (listp arg)
; if-part
0
; then-part
(if (eq arg ’-)
; else-part, inner if
-1
; inner if’s then-part
(1- arg))))
; inner if’s else-part
This code consists of two if expression, one the else-part of the other.
The first or outer if expression tests whether the argument passed to
yank is a list. Oddly enough, this will be true if yank is called without an
argument—because then it will be passed the value of nil for the optional
argument and an evaluation of (listp nil) returns true! So, if no argument
is passed to yank, the argument passed to rotate-yank-pointer inside of
yank is zero. This means the pointer is not moved and the first element to
which kill-ring-yank-pointer points is inserted, as we expect. Similarly,
if the argument for yank is C-u, this will be read as a list, so again, a zero will
be passed to rotate-yank-pointer. (C-u produces an unprocessed prefix
argument of (4), which is a list of one element.) At the same time, later in
the function, this argument will be read as a cons so point will be put in the
" 4 0)) (269 (90.0 47.60907745361328 449.6509094238281 60.90726852416992 "Passing a negative argument
251
" 0 0) (90.00015258789062 77.48908233642578 449.6723327636719 187.36976623535156 "front and mark at the end of the insertion. (The P argument to interactive
is designed to provide these values for the case when an optional argument
is not provided or when it is C-u.)
The then-part of the outer if expression handles the case when there is
no argument or when it is C-u. The else-part handles the other situations.
The else-part is itself another if expression.
The inner if expression tests whether the argument is a minus sign. (This
is done by pressing the ⟨
" 1 0) (210.947998046875 171.59197998046875 236.26800537109375 172.0719757080078 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (210.9600067138672 172.8024444580078 236.24652099609375 180.77255249023438 "META
" 3 0) (210.947998046875 180.11199951171875 236.26800537109375 180.5919952392578 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (235.67999267578125 167.84906005859375 431.02630615234375 187.36976623535156 "⟩ and - keys at the same time, or the ⟨
" 5 0) (430.3080139160156 171.59197998046875 446.9880065917969 172.0719757080078 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (430.32000732421875 172.8024444580078 446.865966796875 180.77255249023438 "ESC
" 7 0) (430.3080139160156 180.11199951171875 446.9880065917969 180.5919952392578 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (90.0 171.45310974121094 450.0766906738281 328.5072326660156 "⟩
key and then the - key). In this case, the rotate-yank-pointer function
is passed -1 as an argument.
This moves the kill-ring-yank-pointer
backwards, which is what is desired.
If the true-or-false-test of the inner if expression is false (that is, if the
argument is not a minus sign), the else-part of the expression is evaluated.
This is the expression (1- arg). Because of the two if expressions, it will
only occur when the argument is a positive number or when it is a negative
number (not just a minus sign on its own). What (1- arg) does is decrement
the number and return it. (The 1- function subtracts one from its argument.)
This means that if the argument to rotate-yank-pointer is 1, it is reduced
to zero, which means the first element to which kill-ring-yank-pointer
points is yanked back, as you would expect.
" 9 0) (90.00054931640625 346.32177734375 274.2267761230469 359.42578125 "Passing a negative argument
" 10 0) (89.99920654296875 369.0890197753906 449.4876403808594 508.98724365234375 "Finally, the question arises, what happens if either the remainder func-
tion, %, or the nthcdr function is passed a negative argument, as they quite
well may?
The answers can be found by a quick test. When (% -1 5) is evaluated, a
negative number is returned; and if nthcdr is called with a negative number,
it returns the same value as if it were called with a first argument of zero.
This can be seen be evaluating the following code.
Here the ‘⇒’ points to the result of evaluating the code preceding it.
This was done by positioning the cursor after the code and typing C-x C-e
(eval-last-sexp) in the usual fashion. You can do this if you are reading
this in Info inside of GNU Emacs.
" 11 0) (111.59890747070312 515.4976196289062 158.65769958496094 542.6897583007812 "(% -1 5)
⇒ -1
" 12 0) (111.59886932373047 545.0176391601562 285.2336120605469 572.2097778320312 "(setq animals ’(cats dogs elephants))
⇒ (cats dogs elephants)
" 13 0) (111.59896850585938 574.6576538085938 224.18704223632812 601.729736328125 "(nthcdr 1 animals)
⇒ (dogs elephants)
" 14 0) (111.59898376464844 604.1776123046875 247.6729736328125 631.3697509765625 "(nthcdr 0 animals)
⇒ (cats dogs elephants)
" 15 0)) (270 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "252
Appendix B: Handling the Kill Ring
" 0 0) (89.99945068359375 81.33761596679688 449.5417785644531 287.4673156738281 "(nthcdr -1 animals)
⇒ (cats dogs elephants)
So, if a minus sign or a negative number is passed to yank, the kill-
ring-yank-point is rotated backwards until it reaches the beginning of the
list. Then it stays there. Unlike the other case, when it jumps from the end
of the list to the beginning of the list, making a ring, it stops. This makes
sense. You often want to get back to the most recently clipped out piece of
text, but you don’t usually want to insert text from as many as thirty kill
commands ago. So you need to work through the ring to get to the end, but
won’t cycle around it inadvertently if you are trying to come back to the
beginning.
Incidentally, any number passed to yank with a minus sign preceding
it will be treated as −1. This is evidently a simplification for writing the
program. You don’t need to jump back towards the beginning of the kill
ring more than one place at a time and doing this is easier than writing a
function to determine the magnitude of the number that follows the minus
sign.
" 1 0) (89.99951171875 305.3004150390625 181.41964721679688 319.67364501953125 "B.3 yank-pop
" 2 0) (89.99945068359375 327.68914794921875 449.4103088378906 352.9873352050781 "After understanding yank, the yank-pop function is easy. Leaving out
the documentation to save space, it looks like this:
" 3 0) (111.60003662109375 358.2976989746094 337.0495300292969 404.5840759277344 "(defun yank-pop (arg)
(interactive \"*p\")
(if (not (eq last-command ’yank))
(error \"Previous command was not a yank\"))
" 4 0) (89.99868774414062 409.17779541015625 450.00921630859375 630.7874755859375 "(setq this-command ’yank)
(let ((before (< (point) (mark))))
(delete-region (point) (mark))
(rotate-yank-pointer arg)
(set-mark (point))
(insert (car kill-ring-yank-pointer))
(if before (exchange-point-and-mark))))
The function is interactive with a small ‘p’ so the prefix argument is
processed and passed to the function. The command can only be used after
a previous yank; otherwise an error message is sent. This check uses the
variable last-command which is discussed elsewhere. (See Section 8.5, “copy-
region-as-kill”, page 102.)
The let clause sets the variable before to true or false depending whether
point is before or after mark and then the region between point and mark
is deleted. This is the region that was just inserted by the previous yank
and it is this text that will be replaced. Next the kill-ring-yank-pointer
is rotated so that the previously inserted text is not reinserted yet again.
Mark is set at the beginning of the place the new text will be inserted and
" 5 0)) (271 (90.0 47.60907745361328 449.82574462890625 60.90726852416992 "yank-pop
253
" 0 0) (89.99951171875 77.48908233642578 449.34539794921875 126.66727447509766 "then the first element to which kill-ring-yank-pointer points is inserted.
This leaves point after the new text. If in the previous yank, point was left
before the inserted text, point and mark are now exchanged so point is again
left in front of the newly inserted text. That is all there is to it!
" 1 0)) (272 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "254
Appendix B: Handling the Kill Ring
" 0 0)) (273 (90.0 47.60907745361328 449.6721496582031 60.90726852416992 "A Graph with Labelled Axes
255
" 0 0) (89.9993896484375 75.14844512939453 447.5566101074219 92.38106536865234 "Appendix C A Graph with Labelled Axes
" 1 0) (89.99835205078125 106.76911163330078 449.42095947265625 268.8670959472656 "Printed axes help you understand a graph. They convey scale. In an
earlier chapter (see Chapter 15, “Readying a Graph”, page 203), we wrote
the code to print the body of a graph. Here we write the code for printing
and labelling vertical and horizontal axes, along with the body itself.
Since insertions fill a buffer to the right and below point, the new graph
printing function should first print the Y or vertical axis, then the body of
the graph, and finally the X or horizontal axis. This sequence lays out for
us the contents of the function:
1. Set up code.
2. Print Y axis.
3. Print body of graph.
4. Print X axis.
" 2 0) (104.9991226196289 274.04888916015625 371.9224853515625 287.3470764160156 "Here is an example of how a finished graph should look:
" 3 0) (89.99874877929688 293.0174255371094 449.3005065917969 478.26708984375 "10 -
*
*
*
*
**
*
***
5 -
*
*******
* *** *******
*************
***************
1 - ****************
|
|
|
|
1
5
10
15
In this graph, both the vertical and the horizontal axes are labelled with
numbers. However, in some graphs, the horizontal axis is time and would
be better labelled with months, like this:
" 4 0) (89.99771118164062 483.93743896484375 449.36541748046875 630.787109375 "5 -
*
* ** *
*******
********** **
1 - **************
|
^
|
Jan
June
Jan
Indeed, with a little thought, we can easily come up with a variety of
vertical and horizontal labelling schemes. Our task could become compli-
cated. But complications breed confusion. Rather than permit this, it is
better choose a simple labelling scheme for our first effort, and to modify or
replace it later.
" 5 0)) (274 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "256
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99948120117188 81.08905792236328 449.66058349609375 106.38724517822266 "These considerations suggest the following outline for the print-graph
function:
" 1 0) (104.99861145019531 112.89767456054688 449.51800537109375 213.90721130371094 "(defun print-graph (numbers-list)
\"documentation...\"
(let ((height
...
...))
(print-Y-axis height ... )
(graph-body-print numbers-list)
(print-X-axis ... )))
We can work on each part of the print-graph function definition in turn.
" 2 0) (89.9979248046875 236.540283203125 288.4836120605469 250.9134979248047 "C.1 The print-graph Varlist
" 3 0) (89.99514770507812 260.2490234375 449.81109619140625 514.9873046875 "In writing the print-graph function, the first task is to write the varlist in
the let expression. (We will leave aside for the moment any thoughts about
making the function interactive or about the contents of its documentation
string.)
The varlist should set several values. Clearly, the top of the label for
the vertical axis must be at least the height of the graph, which means that
we must obtain this information here. Note that the print-graph-body
function also requires this information. There is no reason to calculate the
height of the graph in two different places, so we should change print-
graph-body from the way we defined it earlier to take advantage of the
calculation.
Similarly, both the function for printing the X axis labels and the print-
graph-body function need to learn the value of the width of each symbol.
We can perform the calculation here and change the definition for print-
graph-body from the way we defined it in the previous chapter.
The length of the label for the horizontal axis must be at least as long
as the graph. However, this information is used only in the function that
prints the horizontal axis, so it does not need to be calculated here.
These thoughts lead us directly to the following form for the varlist in
the let for print-graph:
" 4 0) (89.99490356445312 521.4951782226562 366.8747253417969 559.1472778320312 "(let ((height (apply ’max numbers-list)) ; First version.
(symbol-width (length graph-blank)))
As we shall see, this expression is not quite right.
" 5 0) (89.99440002441406 581.9003295898438 310.682861328125 596.2735595703125 "C.2 The print-Y-axis Function
" 6 0) (89.99533081054688 605.4890747070312 449.14361572265625 630.7872924804688 "The job of the print-Y-axis function is to print a label for the vertical
axis that looks like this:
" 7 0)) (275 (90.0 47.60907745361328 449.6291198730469 60.90726852416992 "Side Trip: Compute a Remainder
257
" 0 0) (130.44036865234375 81.33761596679688 149.29061889648438 90.30400085449219 "10 -
" 1 0) (135.12034606933594 143.61758422851562 149.29913330078125 152.58396911621094 "5 -
" 2 0) (89.99700927734375 193.41757202148438 449.4646301269531 630.7872924804688 "1 -
The function should be passed the height of the graph, and then should
construct and insert the appropriate numbers and marks.
It is easy enough to see in the figure what the Y axis label should look
like; but to say in words, and then to write a function definition to do the
job is another matter. It is not quite true to say that we want a number
and a tic every five lines: there are only three lines between the ‘1’ and the
‘5’ (lines 2, 3, and 4), but four lines between the ‘5’ and the ‘10’ (lines 6, 7,
8, and 9). It is better to say that we want a number and a tic mark on the
base line (number 1) and then that we want a number and a tic on the fifth
line from the bottom and on every line that is a multiple of five.
The next issue is what height the label should be? Suppose the maximum
height of tallest column of the graph is seven. Should the highest label on
the Y axis be ‘5 -’, and should the graph stick up above the label? Or should
the highest label be ‘7 -’, and mark the peak of the graph? Or should the
highest label be 10 -, which is a multiple of five, and be higher than the
topmost value of the graph?
The latter form is preferred. Most graphs are drawn within rectangles
whose sides are an integral number of steps long—5, 10, 15, and so on for a
step distance of five. But as soon as we decide to use a step height for the ver-
tical axis, we discover that the simple expression in the varlist for computing
the height is wrong. The expression is (apply ’max numbers-list). This
returns the precise height, not the maximum height plus whatever is neces-
sary to round up to the nearest multiple of five. A more complex expression
is required.
As usual in cases like this, a complex problem becomes simpler if it is
divided into several smaller problems.
First, consider the case when the highest value of the graph is an integral
multiple of five—when it is 5, 10, 15 ,or some higher multiple of five. We
can use this value as the Y axis height.
A fairly simply way to determine whether a number is a multiple of five
is to divide it by five and see if the division results in a remainder. If there is
no remainder, the number is a multiple of five. Thus, seven divided by five
has a remainder of two, and seven is not an integral multiple of five. Put in
slightly different language, more reminiscent of the classroom, five goes into
" 3 0)) (276 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "258
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99905395507812 77.48908233642578 449.279052734375 102.66727447509766 "seven once, with a remainder of two. However, five goes into ten twice, with
no remainder: ten is an integral multiple of five.
" 1 0) (89.99957275390625 117.601806640625 347.92327880859375 130.70579528808594 "C.2.1 Side Trip: Compute a Remainder
" 2 0) (89.99822998046875 139.2889404296875 449.431884765625 194.3296661376953 "In Lisp, the function for computing a remainder is %. The function returns
the remainder of its first argument divided by its second argument.
As
it happens, % is a function in Emacs Lisp that you cannot discover using
apropos: you find nothing if you type M-x apropos ⟨
" 3 0) (342.8280029296875 178.43194580078125 360.947998046875 178.9119415283203 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (342.8399963378906 179.7624053955078 360.94012451171875 187.73251342773438 "RET
" 5 0) (342.8280029296875 187.072021484375 360.947998046875 187.55201721191406 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (360.4800109863281 177.2069854736328 426.4665832519531 194.3297882080078 "⟩ remainder ⟨
" 7 0) (425.7480163574219 178.43194580078125 443.8680114746094 178.9119415283203 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (425.760009765625 179.7624053955078 443.8601379394531 187.73251342773438 "RET
" 9 0) (425.7480163574219 187.072021484375 443.8680114746094 187.55201721191406 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (90.0 175.1690673828125 450.03271484375 250.62730407714844 "⟩.
The only way to learn of the existence of % is to read about it in a book
such as this or in the Emacs Lisp sources. The % function is used in the
code for rotate-yank-pointer, which is described in an appendix. (See
Section B.1.1, “The Body of rotate-yank-pointer”, page 244.)
You can try the % function by evaluating the following two expressions:
" 11 0) (111.6009521484375 256.1776428222656 144.47412109375 265.1440124511719 "(% 7 5)
" 12 0) (90.00003051757812 281.1376647949219 449.366943359375 343.6273498535156 "(% 10 5)
The first expression returns 2 and the second expression returns 0.
To test whether the returned value is zero or some other number, we can
use the zerop function. This function returns t if its argument, which must
be a number, is zero.
" 13 0) (111.60008239746094 349.0577087402344 182.0936279296875 376.2498779296875 "(zerop (% 7 5))
⇒ nil
" 14 0) (89.99981689453125 386.4977111816406 449.3231201171875 434.9473876953125 "(zerop (% 10 5))
⇒ t
Thus, the following expression will return t if the height of the graph is
evenly divisible by five:
" 15 0) (89.99893188476562 440.49774169921875 449.57354736328125 586.387451171875 "(zerop (% height 5))
(The value of height, of course, can be found from (apply ’max numbers-
list).)
On the other hand, if the value of height is not a multiple of five, we want
to reset the value to the next higher multiple of five. This is straightforward
arithmetic using functions with which we are already familiar.
First, we
divide the value of height by five to determine how many times five goes
into the number. Thus, five goes into twelve twice. If we add one to this
quotient and multiply by five, we will obtain the value of the next multiple
of five that is larger than the height. Five goes into twelve twice. Add one
to two, and multiply by five; the result is fifteen, which is the next multiple
of five that is higher than twelve. The Lisp expression for this is:
" 16 0) (89.99877166748047 591.9378051757812 369.92578125 615.7874145507812 "(* (1+ (/ height 5)) 5)
For example, if you evaluate the following, the result is 15:
" 17 0) (111.59886169433594 621.3377685546875 200.91517639160156 630.3041381835938 "(* (1+ (/ 12 5)) 5)
" 18 0)) (277 (90.0 47.60907745361328 449.6725158691406 60.90726852416992 "Construct a Y Axis Element
259
" 0 0) (89.99929809570312 77.48908233642578 449.8138427734375 153.4272918701172 "All through this discussion, we have been using ‘five’ as the value for
spacing labels on the Y axis; but we may want to use some other value. For
generality, we should replace ‘five’ with a variable to which we can assign
a value. The best name I can think of for this variable is Y-axis-label-
spacing.
Using this term, and an if expression, we produce the following:
" 1 0) (89.99874877929688 159.21762084960938 449.5844421386719 295.9872131347656 "(if (zerop (% height Y-axis-label-spacing))
height
;; else
(* (1+ (/ height Y-axis-label-spacing))
Y-axis-label-spacing))
This expression returns the value of height itself if the height is an even
multiple of the value of the Y-axis-label-spacing or else it computes and
returns a value of height that is equal to the next higher multiple of the
value of the Y-axis-label-spacing.
We can now include this expression in the let expression of the print-
graph function (after first setting the value of Y-axis-label-spacing):
" 2 0) (111.59906005859375 301.7775573730469 351.17388916015625 323.2239074707031 "(defvar Y-axis-label-spacing 5
\"Number of lines from one Y axis label to next.\")
" 3 0) (111.59867858886719 331.29754638671875 350.8221740722656 390.0639343261719 "...
(let* ((height (apply ’max numbers-list))
(height-of-top-line
(if (zerop (% height Y-axis-label-spacing))
height
" 4 0) (89.99801635742188 394.6551513671875 449.2777404785156 505.3872375488281 ";; else
(* (1+ (/ height Y-axis-label-spacing))
Y-axis-label-spacing)))
(symbol-width (length graph-blank))))
...
(Note use of the let* function: the initial value of height is computed once
by the (apply ’max numbers-list) expression and then the resulting value
of height is used to compute its final value. See “The let* expression”,
page 156, for more about let*.)
" 5 0) (89.99803161621094 521.0418090820312 314.651123046875 534.1458129882812 "C.2.2 Construct a Y Axis Element
" 6 0) (89.9959716796875 542.9690551757812 449.4183654785156 630.7872924804688 "When we print the vertical axis, we want to insert strings such as ‘5 -’
and ‘10 - ’ every five lines. Moreover, we want the numbers and dashes to
line up, so shorter numbers must be padded with leading spaces. If some
of the strings use two digit numbers, the strings with single digit numbers
must include a leading blank space before the number.
To figure out the length of the number, the length function is used. But
the length function works only with a string, not with a number. So the
" 7 0)) (278 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "260
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99853515625 77.48908233642578 449.3438415527344 102.66727447509766 "number has to be converted from being a number to being a string. This is
done with the number-to-string function. For example,
" 1 0) (111.59895324707031 109.29763793945312 252.51634216308594 136.4898223876953 "(length (number-to-string 35))
⇒ 2
" 2 0) (89.99874877929688 146.61764526367188 449.4311218261719 236.22727966308594 "(length (number-to-string 100))
⇒ 3
(number-to-string is also called int-to-string; you will see this alterna-
tive name in various sources.)
In addition, in each label, each number is followed by a string such as
‘ - ’, which we will call the Y-axis-tic marker. This variable is defined
with defvar:
" 3 0) (89.99911499023438 242.85763549804688 449.3984069824219 292.3872985839844 "(defvar Y-axis-tic \" - \"
\"String that follows number in a Y axis label.\")
The length of the Y label is the sum of the length of the Y axis tic mark
and the length of the number of the top of the graph.
" 4 0) (89.99716186523438 299.0176696777344 449.3975524902344 423.06732177734375 "(length (concat (number-to-string height) Y-axis-tic)))
This value will be calculated by the print-graph function in its varlist as
full-Y-label-width and passed on. (Note that we did not think to include
this in the varlist when we first proposed it.)
To make a complete vertical axis label, a tic mark is concatenated with
a number; and the two together may be preceded by one or more spaces
depending on how long the number is. The label consists of three parts:
the (optional) leading spaces, the number, and the tic mark. The function
is passed the value of the number for the specific row, and the value of the
width of the top line, which is calculated (just once) by print-graph.
" 5 0) (111.59710693359375 429.6976623535156 341.4010314941406 551.7041015625 "(defun Y-axis-element (number full-Y-label-width)
\"Construct a NUMBERed label element.
A numbered element looks like this ‘
5 - ’,
and is padded as needed so all line up with
the element for the largest number.\"
(let* ((leading-spaces
(- full-Y-label-width
(length
(concat (number-to-string number)
Y-axis-tic)))))
" 6 0) (89.99734497070312 556.2977294921875 449.2445983886719 630.787353515625 "(concat
(make-string leading-spaces ? )
(number-to-string number)
Y-axis-tic)))
The Y-axis-element function concatenates together the leading spaces,
if any; the number, as a string; and the tic mark.
" 7 0)) (279 (90.0 47.60907745361328 449.5087585449219 60.90726852416992 "The Not Quite Final Version of print-Y-axis
261
" 0 0) (89.99957275390625 77.48908233642578 449.4211730957031 190.74729919433594 "To figure out how many leading spaces the label will need, the function
subtracts the actual length of the label—the length of the number plus the
length of the tic mark—from the desired label width.
Blank spaces are inserted using the make-string function. This function
takes two arguments: the first tells it how long the string will be and the
second is a symbol for the character to insert, in a special format.
The
format is a question mark followed by a blank space, like this, ‘? ’.
See
section “Character Type” in The GNU Emacs Lisp Reference Manual, for a
description of the syntax for characters.
" 1 0) (90.00042724609375 193.88909912109375 449.3670654296875 231.0673065185547 "The number-to-string function is used in the concatenation expression,
to convert the number to a string that is concatenated with the leading
spaces and the tic mark.
" 2 0) (90.0010986328125 251.641845703125 291.08172607421875 264.745849609375 "C.2.3 Create a Y Axis Column
" 3 0) (90.00088500976562 275.12908935546875 449.488037109375 312.4272766113281 "The preceding functions provide all the tools needed to construct a func-
tion that generates a list of numbered and blank strings to insert as the label
for the vertical axis:
" 4 0) (111.60086822509766 319.7776184082031 384.0219421386719 577.8642578125 "(defun Y-axis-column (height width-of-label)
\"Construct list of Y axis labels and blank strings.
For HEIGHT of line above base and WIDTH-OF-LABEL.\"
(let (Y-axis)
(while (> height 1)
(if (zerop (% height Y-axis-label-spacing))
;; Insert label.
(setq Y-axis
(cons
(Y-axis-element height width-of-label)
Y-axis))
;; Else, insert blanks.
(setq Y-axis
(cons
(make-string width-of-label ? )
Y-axis)))
(setq height (1- height)))
;; Insert base line.
(setq Y-axis
(cons (Y-axis-element 1 width-of-label) Y-axis))
(nreverse Y-axis)))
" 5 0) (90.00057983398438 581.6093139648438 449.4992370605469 630.7875366210938 "In this function, we start with the value of height and repetitively sub-
tract one from its value.
After each subtraction, we test to see whether
the value is an integral multiple of the Y-axis-label-spacing. If it is,
we construct a numbered label using the Y-axis-element function; if not,
" 6 0)) (280 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "262
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99868774414062 77.48908233642578 449.38763427734375 102.66727447509766 "we construct a blank label using the make-string function. The base line
consists of the number one followed by a tic mark.
" 1 0) (89.99888610839844 118.92181396484375 419.0520935058594 132.03736877441406 "C.2.4 The Not Quite Final Version of print-Y-axis
" 2 0) (89.99884033203125 140.96905517578125 449.431640625 166.2672576904297 "The list constructed by the Y-axis-column function is passed to the
print-Y-axis function, which inserts the list as a column.
" 3 0) (89.99761962890625 172.17758178710938 449.3975524902344 401.947021484375 "(defun print-Y-axis (height full-Y-label-width)
\"Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
Height must be the maximum height of the graph.
Full width is the width of the highest label element.\"
;; Value of height and full-Y-label-width
;; are passed by ‘print-graph’.
(let ((start (point)))
(insert-rectangle
(Y-axis-column height full-Y-label-width))
;; Place point ready for inserting graph.
(goto-char start)
;; Move point forward by value of full-Y-label-width
(forward-char full-Y-label-width)))
The print-Y-axis uses the insert-rectangle function to insert the Y
axis labels created by the Y-axis-column function. In addition, it places
point at the correct position for printing the body of the graph.
You can test print-Y-axis:
1. Install
" 4 0) (95.87767791748047 408.8173828125 256.6451110839844 484.2670593261719 "Y-axis-label-spacing
Y-axis-tic
Y-axis-element
Y-axis-column
print-Y-axis
2. Copy the following expression:
" 5 0) (95.87794494628906 491.1374206542969 449.4634094238281 593.9295654296875 "(print-Y-axis 12 5)
3. Switch to the ‘*scratch*’ buffer and place the cursor where you want
the axis labels to start.
4. Type M-: (eval-expression).
5. Yank the graph-body-print expression into the minibuffer with C-y
(yank).
6. Press ⟨
" 6 0) (143.26800537109375 578.1519775390625 161.38800048828125 578.6319580078125 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (143.27999877929688 579.3623657226562 161.38011169433594 587.33251953125 "RET
" 8 0) (143.26800537109375 586.6719970703125 161.38800048828125 587.1519775390625 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (160.9199981689453 574.4090576171875 294.7418212890625 593.5697631835938 "⟩ to evaluate the expression.
" 10 0) (89.99951171875 593.609130859375 449.55218505859375 630.787353515625 "Emacs will print labels vertically, the top one being ‘10 - ’. (The print-
graph function will pass the value of height-of-top-line, which in this
case would end up as 15.)
" 11 0)) (281 (90.0 47.60907745361328 449.7704772949219 60.90726852416992 "X Axis Tic Marks
263
" 0 0) (89.99972534179688 77.30034637451172 310.68817138671875 91.67356872558594 "C.3 The print-X-axis Function
" 1 0) (89.99969482421875 100.76911163330078 449.4432678222656 126.06729888916016 "X axis labels are much like Y axis labels, except that the tics are on a
line above the numbers. Labels should look like this:
" 2 0) (89.9986572265625 132.45767211914062 450.0753173828125 407.7073669433594 "|
|
|
|
1
5
10
15
The first tic is under the first column of the graph and is preceded by
several blank spaces. These spaces provide room in rows above for the Y
axis labels. The second, third, fourth, and subsequent tics are all spaced
equally, according to the value of X-axis-label-spacing.
The second row of the X axis consists of numbers, preceded by several
blank spaces and also separated according to the value of the variable X-
axis-label-spacing.
The value of the variable X-axis-label-spacing should itself be mea-
sured in units of symbol-width, since you may want to change the width
of the symbols that you are using to print the body of the graph without
changing the ways the graph is labelled.
The print-X-axis function is constructed in more or less the same fash-
ion as the print-Y-axis function except that it has two lines: the line of
tic marks and the numbers. We will write a separate function to print each
line and then combine them within the print-X-axis function.
This is a three step process:
1. Write a function to print the X axis tic marks, print-X-axis-tic-line.
2. Write a function to print the X numbers, print-X-axis-numbered-
line.
" 3 0) (95.8792724609375 410.84918212890625 449.38824462890625 436.0273742675781 "3. Write a function to print both lines, the print-X-axis function, using
print-X-axis-tic-line and print-X-axis-numbered-line.
" 4 0) (89.99951171875 453.721923828125 247.00743103027344 466.825927734375 "C.3.1 X Axis Tic Marks
" 5 0) (89.99951171875 476.2491760253906 449.41033935546875 501.54736328125 "The first function should print the X axis tic marks. We must specify the
tic marks themselves and their spacing:
" 6 0) (89.99826049804688 507.9377136230469 449.56195068359375 630.7874145507812 "(defvar X-axis-label-spacing
(if (boundp ’graph-blank)
(* 5 (length graph-blank)) 5)
\"Number of units from one X axis label to next.\")
(Note that the value of graph-blank is set by another defvar.
The
boundp predicate checks whether it has already been set; boundp returns
nil if it has not.
If graph-blank were unbound and we did not use
this conditional construction, in GNU Emacs 21, we would enter the de-
bugger and see an error message saying ‘Debugger entered--Lisp error:
(void-variable graph-blank)’.)
" 7 0)) (282 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "264
Appendix C: A Graph with Labelled Axes
" 0 0) (104.99905395507812 83.24909210205078 315.72967529296875 96.54727935791016 "Here is the defvar for X-axis-tic-symbol:
" 1 0) (111.59895324707031 105.33755493164062 360.52484130859375 126.78392028808594 "(defvar X-axis-tic-symbol \"|\"
\"String to insert to point to a column in X axis.\")
" 2 0) (104.99864196777344 132.80902099609375 324.70745849609375 146.1072235107422 "The goal is to make a line that looks like this:
" 3 0) (144.59837341308594 154.89755249023438 215.16014099121094 163.8639373779297 "|
|
|
|
" 4 0) (89.99844360351562 168.68902587890625 449.3767395019531 193.8672332763672 "The first tic is indented so that it is under the first column, which is
indented to provide space for the Y axis labels.
" 5 0) (89.99838256835938 198.32904052734375 449.38739013671875 235.5072479248047 "A tic element consists of the blank spaces that stretch from one tic to the
next plus a tic symbol. The number of blanks is determined by the width of
the tic symbol and the X-axis-label-spacing.
" 6 0) (104.99884033203125 239.96905517578125 220.85337829589844 253.2672576904297 "The code looks like this:
" 7 0) (111.59888458251953 262.0575866699219 313.15948486328125 395.4638977050781 ";;; X-axis-tic-element
...
(concat
(make-string
;; Make a string of blanks.
(-
(* symbol-width X-axis-label-spacing)
(length X-axis-tic-symbol))
? )
;; Concatenate blanks with tic symbol.
X-axis-tic-symbol)
...
" 8 0) (89.99911499023438 400.64898681640625 449.7913818359375 437.8271789550781 "Next, we determine how many blanks are needed to indent the first tic
mark to the first column of the graph. This uses the value of full-Y-label-
width passed it by the print-graph function.
" 9 0) (104.99964904785156 442.28900146484375 386.3997802734375 455.5871887207031 "The code to make X-axis-leading-spaces looks like this:
" 10 0) (111.59962463378906 464.2575378417969 276.1229553222656 510.6639404296875 ";; X-axis-leading-spaces
...
(make-string full-Y-label-width ? )
...
" 11 0) (89.99935913085938 515.72900390625 449.399169921875 541.0272216796875 "We also need to determine the length of the horizontal axis, which is the
length of the numbers list, and the number of tics in the horizontal axis:
" 12 0) (111.59881591796875 549.6975708007812 209.9842987060547 583.6240234375 ";; X-length
...
(length numbers-list)
" 13 0) (111.59880828857422 591.6976318359375 284.9764099121094 625.6240234375 ";; tic-width
...
(* symbol-width X-axis-label-spacing)
" 14 0)) (283 (90.0 47.60907745361328 449.7704772949219 60.90726852416992 "X Axis Tic Marks
265
" 0 0) (111.5997314453125 81.33761596679688 280.4428405761719 127.62394714355469 ";; number-of-X-tics
(if (zerop (% (X-length tic-width)))
(/ (X-length tic-width))
(1+ (/ (X-length tic-width))))
" 1 0) (104.99951934814453 135.68902587890625 446.12646484375 148.9872283935547 "All this leads us directly to the function for printing the X axis tic line:
" 2 0) (111.59933471679688 159.69754028320312 397.8294677734375 370.0236511230469 "(defun print-X-axis-tic-line
(number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
\"Print tics for X axis.\"
(insert X-axis-leading-spaces)
(insert X-axis-tic-symbol)
; Under first column.
;; Insert second tic in the right spot.
(insert (concat
(make-string
(-
(* symbol-width X-axis-label-spacing)
;; Insert white space up to second tic symbol.
(* 2 (length X-axis-tic-symbol)))
? )
X-axis-tic-symbol))
;; Insert remaining tics.
(while (> number-of-X-tics 1)
(insert X-axis-tic-element)
(setq number-of-X-tics (1- number-of-X-tics))))
" 3 0) (105.00019836425781 377.00872802734375 328.63616943359375 390.3069152832031 "The line of numbers is equally straightforward:
" 4 0) (90.0 396.8087158203125 449.3999328613281 421.9869079589844 "First, we create a numbered element with blank spaces before each num-
ber:
" 5 0) (111.59996795654297 432.697265625 346.41802978515625 516.4237060546875 "(defun X-axis-element (number)
\"Construct a numbered X axis element.\"
(let ((leading-spaces
(-
(* symbol-width X-axis-label-spacing)
(length (number-to-string number)))))
(concat (make-string leading-spaces ? )
(number-to-string number))))
" 6 0) (90.00018310546875 523.52880859375 449.31292724609375 548.70703125 "Next, we create the function to print the numbered line, starting with
the number “1” under the first column:
" 7 0) (111.60023498535156 559.4173583984375 308.46380615234375 630.6636962890625 "(defun print-X-axis-numbered-line
(number-of-X-tics X-axis-leading-spaces)
\"Print line of X-axis numbers\"
(let ((number X-axis-label-spacing))
(insert X-axis-leading-spaces)
(insert \"1\")
" 8 0)) (284 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "266
Appendix C: A Graph with Labelled Axes
" 0 0) (89.9981689453125 81.33761596679688 449.8344421386719 334.9870300292969 "(insert (concat
(make-string
;; Insert white space up to next number.
(-
(* symbol-width X-axis-label-spacing) 2)
? )
(number-to-string number)))
;; Insert remaining numbers.
(setq number (+ number X-axis-label-spacing))
(while (> number-of-X-tics 1)
(insert (X-axis-element number))
(setq number (+ number X-axis-label-spacing))
(setq number-of-X-tics (1- number-of-X-tics)))))
Finally, we need to write the print-X-axis that uses print-X-axis-
tic-line and print-X-axis-numbered-line.
The function must determine the local values of the variables used by both
print-X-axis-tic-line and print-X-axis-numbered-line, and then it
must call them. Also, it must print the carriage return that separates the
two lines.
The function consists of a varlist that specifies five local variables, and
calls to each of the two line printing functions:
" 1 0) (111.59791564941406 341.49737548828125 346.2444152832031 387.78375244140625 "(defun print-X-axis (numbers-list)
\"Print X axis labels to length of NUMBERS-LIST.\"
(let* ((leading-spaces
(make-string full-Y-label-width ? ))
" 2 0) (144.59779357910156 392.37506103515625 374.2818603515625 426.183837890625 ";; symbol-width is provided by graph-body-print
(tic-width (* symbol-width X-axis-label-spacing))
(X-length (length numbers-list))
" 3 0) (144.59848022460938 430.7774658203125 210.0520782470703 464.5838317871094 "(X-tic
(concat
(make-string
" 4 0) (130.43841552734375 469.175048828125 393.1747131347656 630.6638793945312 ";; Make a string of blanks.
(-
(* symbol-width X-axis-label-spacing)
(length X-axis-tic-symbol))
? )
;; Concatenate blanks with tic symbol.
X-axis-tic-symbol))
(tic-number
(if (zerop (% X-length tic-width))
(/ X-length tic-width)
(1+ (/ X-length tic-width)))))
(print-X-axis-tic-line tic-number leading-spaces X-tic)
(insert \"\\n\")
(print-X-axis-numbered-line tic-number leading-spaces)))
" 5 0)) (285 (90.0 47.60907745361328 449.68304443359375 60.90726852416992 "Printing the Whole Graph
267
" 0 0) (104.99929809570312 81.80908966064453 240.5119171142578 95.1072769165039 "You can test print-X-axis:
" 1 0) (95.87918090820312 99.20911407470703 450.119384765625 136.38731384277344 "1. Install X-axis-tic-symbol, X-axis-label-spacing, print-X-axis-
tic-line, as well as X-axis-element, print-X-axis-numbered-line,
and print-X-axis.
" 2 0) (95.87995910644531 140.4891357421875 256.64739990234375 153.78733825683594 "2. Copy the following expression:
" 3 0) (133.2001953125 162.21768188476562 358.8282775878906 220.98399353027344 "(progn
(let ((full-Y-label-width 5)
(symbol-width 1))
(print-X-axis
’(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
" 4 0) (95.88055419921875 225.6890869140625 449.3019714355469 250.98728942871094 "3. Switch to the ‘*scratch*’ buffer and place the cursor where you want
the axis labels to start.
" 5 0) (95.88060760498047 255.089111328125 258.1096496582031 268.3961181640625 "4. Type M-: (eval-expression).
" 6 0) (95.88084411621094 272.369140625 406.8659973144531 285.6761474609375 "5. Yank the test expression into the minibuffer with C-y (yank).
" 7 0) (95.88128662109375 289.7691650390625 143.98782348632812 308.92987060546875 "6. Press ⟨
" 8 0) (143.26800537109375 293.1519775390625 161.38800048828125 293.6319885253906 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (143.27999877929688 294.3624572753906 161.38011169433594 302.3325500488281 "RET
" 10 0) (143.26800537109375 301.6719970703125 161.38800048828125 302.1520080566406 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (160.9199981689453 289.4090576171875 294.7418212890625 308.56976318359375 "⟩ to evaluate the expression.
" 12 0) (105.00018310546875 311.60906982421875 319.7672424316406 324.9072570800781 "Emacs will print the horizontal axis like this:
" 13 0) (135.12014770507812 332.2575988769531 229.19342041015625 353.7039794921875 "|
|
|
|
|
1
5
10
15
20
" 14 0) (89.9998779296875 379.2203369140625 309.8974609375 393.58087158203125 "C.4 Printing the Whole Graph
" 15 0) (89.99874877929688 403.76904296875 449.2793884277344 457.2672424316406 "Now we are nearly ready to print the whole graph.
The function to print the graph with the proper labels follows the out-
line we created earlier (see Appendix C, “A Graph with Labelled Axes”,
page 255), but with additions.
" 16 0) (104.99864196777344 460.4090576171875 195.93673706054688 473.7072448730469 "Here is the outline:
" 17 0) (111.59864807128906 481.1776123046875 275.7784729003906 565.864013671875 "(defun print-graph (numbers-list)
\"documentation...\"
(let ((height
...
...))
(print-Y-axis height ... )
(graph-body-print numbers-list)
(print-X-axis ... )))
" 18 0) (89.9969482421875 569.609130859375 449.4405212402344 630.787353515625 "The final version is different from what we planned in two ways: first, it
contains additional values calculated once in the varlist; second, it carries
an option to specify the labels’ increment per row. This latter feature turns
out to be essential; otherwise, a graph may have more rows than fit on a
display or on a sheet of paper.
" 19 0)) (286 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "268
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99884033203125 103.16907501220703 449.3114929199219 128.34727478027344 "This new feature requires a change to the Y-axis-column function, to
add vertical-step to it. The function looks like this:
" 1 0) (111.59844970703125 156.93511962890625 341.68597412109375 277.9837341308594 ";;; Final version.
(defun Y-axis-column
(height width-of-label &optional vertical-step)
\"Construct list of labels for Y axis.
HEIGHT is maximum height of graph.
WIDTH-OF-LABEL is maximum width of label.
VERTICAL-STEP, an option, is a positive integer
that specifies how much a Y axis label increments
for each line.
For example, a step of 5 means
that each line is five units of the graph.\"
" 2 0) (120.9591064453125 282.5774841308594 341.3428955078125 417.0638427734375 "(let (Y-axis
(number-per-line (or vertical-step 1)))
(while (> height 1)
(if (zerop (% height Y-axis-label-spacing))
;; Insert label.
(setq Y-axis
(cons
(Y-axis-element
(* height number-per-line)
width-of-label)
Y-axis))
" 3 0) (139.79937744140625 421.6550598144531 327.876708984375 492.7838439941406 ";; Else, insert blanks.
(setq Y-axis
(cons
(make-string width-of-label ? )
Y-axis)))
(setq height (1- height)))
" 4 0) (130.43948364257812 497.37506103515625 318.6019287109375 568.6239013671875 ";; Insert base line.
(setq Y-axis (cons (Y-axis-element
(or vertical-step 1)
width-of-label)
Y-axis))
(nreverse Y-axis)))
" 5 0) (89.9990234375 593.6089477539062 449.79156494140625 630.7871704101562 "The values for the maximum height of graph and the width of a symbol
are computed by print-graph in its let expression; so graph-body-print
must be changed to accept them.
" 6 0)) (287 (90.0 47.60907745361328 449.68304443359375 60.90726852416992 "Printing the Whole Graph
269
" 0 0) (111.5992431640625 81.33521270751953 383.81500244140625 316.5036926269531 ";;; Final version.
(defun graph-body-print (numbers-list height symbol-width)
\"Print a bar graph of the NUMBERS-LIST.
The numbers-list consists of the Y-axis values.
HEIGHT is maximum height of graph.
SYMBOL-WIDTH is number of each column.\"
(let (from-position)
(while numbers-list
(setq from-position (point))
(insert-rectangle
(column-of-graph height (car numbers-list)))
(goto-char from-position)
(forward-char symbol-width)
;; Draw graph column by column.
(sit-for 0)
(setq numbers-list (cdr numbers-list)))
;; Place point for X axis labels.
(forward-line height)
(insert \"\\n\")))
" 1 0) (105.00045776367188 326.48876953125 331.9966125488281 339.7869567871094 "Finally, the code for the print-graph function:
" 2 0) (111.59939575195312 352.4148864746094 336.89447021484375 411.1838073730469 ";;; Final version.
(defun print-graph
(numbers-list &optional vertical-step)
\"Print labelled bar graph of the NUMBERS-LIST.
The numbers-list consists of the Y-axis values.
" 3 0) (111.59902954101562 419.2574462890625 337.13470458984375 516.4238891601562 "Optionally, VERTICAL-STEP, a positive integer,
specifies how much a Y axis label increments for
each line.
For example, a step of 5 means that
each row is five units.\"
(let* ((symbol-width (length graph-blank))
;; height is both the largest number
;; and the number with the most digits.
(height (apply ’max numbers-list))
" 4 0) (153.96043395996094 521.0175170898438 360.1839294433594 630.6638793945312 "(height-of-top-line
(if (zerop (% height Y-axis-label-spacing))
height
;; else
(* (1+ (/ height Y-axis-label-spacing))
Y-axis-label-spacing)))
(vertical-step (or vertical-step 1))
(full-Y-label-width
(length
" 5 0)) (288 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "270
Appendix C: A Graph with Labelled Axes
" 0 0) (163.43905639648438 81.33761596679688 346.2966613769531 127.62394714355469 "(concat
(number-to-string
(* height-of-top-line vertical-step))
Y-axis-tic))))
" 1 0) (130.43862915039062 135.81753540039062 379.1685791015625 195.6638641357422 "(print-Y-axis
height-of-top-line full-Y-label-width vertical-step)
(graph-body-print
numbers-list height-of-top-line symbol-width)
(print-X-axis numbers-list)))
" 2 0) (89.99974060058594 215.40167236328125 256.5772705078125 228.51722717285156 "C.4.1 Testing print-graph
" 3 0) (104.9997787475586 239.0089111328125 428.6830749511719 252.30711364746094 "We can test the print-graph function with a short list of numbers:
" 4 0) (95.88009643554688 256.2889404296875 449.42169189453125 281.5871276855469 "1. Install the final versions of Y-axis-column, graph-body-print, and
print-graph (in addition to the rest of the code.)
" 5 0) (95.88058471679688 285.5689697265625 256.64801025390625 298.8671569824219 "2. Copy the following expression:
" 6 0) (133.20083618164062 307.1775817871094 330.629150390625 316.1439514160156 "(print-graph ’(3 2 5 6 7 5 3 4 6 4 3 2 1))
" 7 0) (95.880859375 320.6090393066406 449.3022766113281 345.7872314453125 "3. Switch to the ‘*scratch*’ buffer and place the cursor where you want
the axis labels to start.
" 8 0) (95.88091278076172 349.76904296875 258.1099548339844 363.0760498046875 "4. Type M-: (eval-expression).
" 9 0) (95.88114929199219 367.0490417480469 406.8663024902344 380.3560485839844 "5. Yank the test expression into the minibuffer with C-y (yank).
" 10 0) (95.881591796875 384.32904052734375 143.98812866210938 403.48974609375 "6. Press ⟨
" 11 0) (143.26800537109375 387.7120056152344 161.38800048828125 388.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (143.27999877929688 388.92242431640625 161.38011169433594 396.89251708984375 "RET
" 13 0) (143.26800537109375 396.2319641113281 161.38800048828125 396.71197509765625 "<image: None, width: 1, height: 1, bpc: 1>" 14 1) (160.9199981689453 383.9690856933594 294.7418212890625 403.1297912597656 "⟩ to evaluate the expression.
" 15 0) (105.00018310546875 406.04913330078125 319.1890869140625 419.3473205566406 "Emacs will print a graph that looks like this:
" 16 0) (111.59999084472656 426.5776672363281 130.4502410888672 435.5440368652344 "10 -
" 17 0) (116.27993774414062 464.0176696777344 195.86790466308594 547.6240844726562 "*
**
*
5 -
****
*
**** ***
* *********
************
1 - *************
" 18 0) (135.1199493408203 563.6177368164062 205.6817169189453 585.0640869140625 "|
|
|
|
1
5
10
15
" 19 0) (89.99932861328125 588.6891479492188 449.37762451171875 613.9873657226562 "On the other hand, if you pass print-graph a vertical-step value of
2, by evaluating this expression:
" 20 0) (111.59935760498047 621.3377075195312 318.4991149902344 630.3040771484375 "(print-graph ’(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
" 21 0)) (289 (90.0 47.60907745361328 449.56317138671875 60.90726852416992 "Graphing Numbers of Words and Symbols
271
" 0 0) (89.99942016601562 88.28907012939453 211.7229461669922 101.5872573852539 "The graph looks like this:
" 1 0) (111.59944152832031 115.41763305664062 130.44969177246094 124.38401794433594 "20 -
" 2 0) (111.59944915771484 152.73764038085938 195.86732482910156 236.4639129638672 "*
**
*
10 -
****
*
**** ***
* *********
************
2 - *************
" 3 0) (135.11936950683594 252.33755493164062 205.68113708496094 273.7839050292969 "|
|
|
|
1
5
10
15
" 4 0) (89.99859619140625 284.489013671875 449.32208251953125 321.7872009277344 "(A question: is the ‘2’ on the bottom of the vertical axis a bug or a feature?
If you think it is a bug, and should be a ‘1’ instead, (or even a ‘0’), you can
modify the sources.)
" 5 0) (89.99859619140625 361.32177734375 404.93109130859375 374.42578125 "C.4.2 Graphing Numbers of Words and Symbols
" 6 0) (89.9981689453125 391.2890319824219 449.34344482421875 440.46722412109375 "Now for the graph for which all this code was written: a graph that shows
how many function definitions contain fewer than 10 words and symbols, how
many contain between 10 and 19 words and symbols, how many contain
between 20 and 29 words and symbols, and so on.
" 7 0) (89.99838256835938 449.8490295410156 449.4311828613281 475.147216796875 "This is a multi-step process. First make sure you have loaded all the
requisite code.
" 8 0) (89.998046875 484.6490173339844 449.3216857910156 509.94720458984375 "It is a good idea to reset the value of top-of-ranges in case you have
set it to some different value. You can evaluate the following:
" 9 0) (111.59828186035156 523.6575927734375 214.93736267089844 607.3839721679688 "(setq top-of-ranges
’(10
20
30
40
50
60
70
80
90 100
110 120 130 140 150
160 170 180 190 200
210 220 230 240 250
260 270 280 290 300)
" 10 0) (89.99757385253906 617.489013671875 419.4406433105469 630.7872314453125 "Next create a list of the number of words and symbols in each range.
" 11 0)) (290 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "272
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99905395507812 85.52906036376953 199.13357543945312 98.8272476196289 "Evaluate the following:
" 1 0) (111.59905242919922 109.77761840820312 350.70257568359375 205.98387145996094 "(setq list-for-graph
(defuns-per-range
(sort
(recursive-lengths-list-many-files
(directory-files \"/usr/local/emacs/lisp\"
t \".+el$\"))
’<)
top-of-ranges))
" 2 0) (89.99907684326172 213.32891845703125 449.562255859375 250.5071258544922 "On my machine, this takes about an hour. It looks though 303 Lisp files in
my copy of Emacs version 19.23. After all that computing, the list-for-
graph has this value:
" 3 0) (111.59922790527344 261.4574890136719 374.7881774902344 282.9038391113281 "(537 1027 955 785 594 483 349 292 224 199 166 120 116 99
90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
" 4 0) (89.99832153320312 290.2489013671875 449.32208251953125 339.4270935058594 "This means that my copy of Emacs has 537 function definitions with fewer
than 10 words or symbols in them, 1,027 function definitions with 10 to 19
words or symbols in them, 955 function definitions with 20 to 29 words or
symbols in them, and so on.
" 5 0) (89.99761962890625 346.0489196777344 449.495849609375 371.22711181640625 "Clearly, just by looking at this list we can see that most function defini-
tions contain ten to thirty words and symbols.
" 6 0) (89.99813842773438 377.84893798828125 449.38671875 427.0271301269531 "Now for printing. We do not want to print a graph that is 1,030 lines
high . . . Instead, we should print a graph that is fewer than twenty-five
lines high. A graph that height can be displayed on almost any monitor,
and easily printed on a sheet of paper.
" 7 0) (89.99905395507812 433.6489562988281 449.3000793457031 458.9471435546875 "This means that each value in list-for-graph must be reduced to one-
fiftieth its present value.
" 8 0) (89.99853515625 465.5689697265625 449.4093933105469 490.7471618652344 "Here is a short function to do just that, using two functions we have not
yet seen, mapcar and lambda.
" 9 0) (111.59843444824219 501.8175048828125 365.1625061035156 535.6239013671875 "(defun one-fiftieth (full-range)
\"Return list, each number one-fiftieth of previous.\"
(mapcar ’(lambda (arg) (/ arg 50)) full-range))
" 10 0) (89.9986572265625 566.4016723632812 390.32379150390625 579.5172119140625 "C.4.3 A lambda Expression: Useful Anonymity
" 11 0) (89.99859619140625 593.6089477539062 449.4422912597656 630.7871704101562 "lambda is the symbol for an anonymous function, a function without a
name. Every time you use an anonymous function, you need to include its
whole body.
" 12 0)) (291 (90.0 47.60907745361328 449.7275695800781 60.90726852416992 "The mapcar Function
273
" 0 0) (90.00082397460938 79.52906036376953 117.10994720458984 92.8272476196289 "Thus,
" 1 0) (90.00009155273438 97.89761352539062 449.9237060546875 183.06724548339844 "(lambda (arg) (/ arg 50))
is a function definition that says ‘return the value resulting from dividing
whatever is passed to me as arg by 50’.
Earlier, for example, we had a function multiply-by-seven; it multiplied
its argument by 7. This function is similar, except it divides its argument by
50; and, it has no name. The anonymous equivalent of multiply-by-seven
is:
" 2 0) (89.99880981445312 188.01760864257812 349.9627685546875 225.42723083496094 "(lambda (number) (* 7 number))
(See Section 3.1, “The defun Special Form”, page 29.)
If we want to multiply 3 by 7, we can write:
" 3 0) (202.4762725830078 252.53228759765625 322.9636535644531 262.5538024902344 "(multiply-by-seven 3)
" 4 0) (230.0399932861328 288.5328369140625 338.93988037109375 298.5543518066406 "function
argument
" 5 0) (89.99979400634766 326.609619140625 218.78172302246094 353.94781494140625 "This expression returns 21.
Similarly, we can write:
" 6 0) (168.99729919433594 381.01287841796875 364.0721130371094 391.0343933105469 "((lambda (number) (* 7 number)) 3)
" 7 0) (196.55999755859375 414.1997985839844 372.95989990234375 424.2213134765625 "anonymous function
argument
" 8 0) (90.0 453.2090759277344 305.0616760253906 466.50726318359375 "If we want to divide 100 by 50, we can write:
" 9 0) (183.39761352539062 493.4923095703125 361.2599182128906 503.5138244628906 "((lambda (arg) (/ arg 50)) 100)
" 10 0) (204.77200317382812 528.9298095703125 358.6719055175781 538.9512939453125 "anonymous function argument
" 11 0) (89.99948120117188 567.6890869140625 449.334228515625 630.7872924804688 "This expression returns 2. The 100 is passed to the function, which divides
that number by 50.
See section “Lambda Expressions” in The GNU Emacs Lisp Reference
Manual, for more about lambda. Lisp and lambda expressions derive from
the Lambda Calculus.
" 12 0)) (292 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "274
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99905395507812 78.2418212890625 262.4652099609375 91.35738372802734 "C.4.4 The mapcar Function
" 1 0) (89.99789428710938 99.44916534423828 449.4208679199219 200.7073211669922 "mapcar is a function that calls its first argument with each element of its
second argument, in turn. The second argument must be a sequence.
The ‘map’ part of the name comes from the mathematical phrase, ‘map-
ping over a domain’, meaning to apply a function to each of the elements in
a domain. The mathematical phrase is based on the metaphor of a surveyor
walking, one step at a time, over an area he is mapping. And ‘car’, of course,
comes from the Lisp notion of the first of a list.
For example,
" 2 0) (89.99740600585938 205.65768432617188 449.3864440917969 317.8273010253906 "(mapcar ’1+ ’(2 4 6))
⇒ (3 5 7)
The function 1+ which adds one to its argument, is executed on each element
of the list, and a new list is returned.
Contrast this with apply, which applies its first argument to all the re-
maining. (See Chapter 15, “Readying a Graph”, page 203, for a explanation
of apply.)
In the definition of one-fiftieth, the first argument is the anonymous
function:
" 3 0) (89.99748992919922 322.8976745605469 449.56085205078125 372.42742919921875 "(lambda (arg) (/ arg 50))
and the second argument is full-range, which will be bound to list-for-
graph.
The whole expression looks like this:
" 4 0) (89.99728393554688 377.4977722167969 449.5282287597656 450.7874450683594 "(mapcar ’(lambda (arg) (/ arg 50)) full-range))
See section “Mapping Functions” in The GNU Emacs Lisp Reference
Manual, for more about mapcar.
Using the one-fiftieth function, we can generate a list in which each
element is one-fiftieth the size of the corresponding element in list-for-
graph.
" 5 0) (104.99748992919922 455.8577880859375 280.46600341796875 493.0274353027344 "(setq fiftieth-list-for-graph
(one-fiftieth list-for-graph))
The resulting list looks like this:
" 6 0) (89.99761962890625 498.0977783203125 449.45257568359375 570.7874755859375 "(10 20 19 15 11 9 6 5 4 3 3 2 2
1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
This, we are almost ready to print! (We also notice the loss of information:
many of the higher ranges are 0, meaning that fewer than 50 defuns had
that many words or symbols—but not necessarily meaning that none had
that many words or symbols.)
" 7 0) (89.99722290039062 584.2820434570312 341.7310485839844 597.3860473632812 "C.4.5 Another Bug . . . Most Insidious
" 8 0) (89.99752807617188 605.4892578125 449.68060302734375 630.7874755859375 "I said ‘almost ready to print’! Of course, there is a bug in the print-
graph function . . . It has a vertical-step option, but not a horizontal-
" 9 0)) (293 (90.0 47.60907745361328 449.6291809082031 60.90726852416992 "Another Bug . . . Most Insidious
275
" 0 0) (89.99880981445312 77.48908233642578 449.562744140625 252.42723083496094 "step option. The top-of-range scale goes from 10 to 300 by tens. But the
print-graph function will print only by ones.
This is a classic example of what some consider the most insidious type
of bug, the bug of omission. This is not the kind of bug you can find by
studying the code, for it is not in the code; it is an omitted feature. Your
best actions are to try your program early and often; and try to arrange,
as much as you can, to write code that is easy to understand and easy to
change. Try to be aware, whenever you can, that whatever you have written,
will be rewritten, if not soon, eventually. A hard maxim to follow.
It is the print-X-axis-numbered-line function that needs the work;
and then the print-X-axis and the print-graph functions need to be
adapted.
Not much needs to be done; there is one nicety: the numbers
ought to line up under the tic marks. This takes a little thought.
Here is the corrected print-X-axis-numbered-line:
" 1 0) (111.59893798828125 257.3775939941406 341.8304748535156 328.6239929199219 "(defun print-X-axis-numbered-line
(number-of-X-tics X-axis-leading-spaces
&optional horizontal-step)
\"Print line of X-axis numbers\"
(let ((number X-axis-label-spacing)
(horizontal-step (or horizontal-step 1)))
" 2 0) (130.43826293945312 333.2176208496094 369.61968994140625 416.8242492675781 "(insert X-axis-leading-spaces)
;; Delete extra leading spaces.
(delete-char
(- (1-
(length (number-to-string horizontal-step)))))
(insert (concat
(make-string
" 3 0) (130.438232421875 421.41546630859375 374.4958801269531 630.664306640625 ";; Insert white space.
(-
(* symbol-width
X-axis-label-spacing)
(1-
(length
(number-to-string horizontal-step)))
2)
? )
(number-to-string
(* number horizontal-step))))
;; Insert remaining numbers.
(setq number (+ number X-axis-label-spacing))
(while (> number-of-X-tics 1)
(insert (X-axis-element
(* number horizontal-step)))
(setq number (+ number X-axis-label-spacing))
(setq number-of-X-tics (1- number-of-X-tics)))))
" 4 0)) (294 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "276
Appendix C: A Graph with Labelled Axes
" 0 0) (89.99868774414062 79.52906036376953 449.5727844238281 116.8272476196289 "If you are reading this in Info, you can see the new versions of print-X-
axis print-graph and evaluate them. If you are reading this in a printed
book, you can see the changed lines here (the full text is too much to print).
" 1 0) (111.59869384765625 121.77761840820312 346.194091796875 168.06394958496094 "(defun print-X-axis (numbers-list horizontal-step)
...
(print-X-axis-numbered-line
tic-number leading-spaces horizontal-step))
" 2 0) (111.59808349609375 174.57754516601562 336.755615234375 233.34385681152344 "(defun print-graph
(numbers-list
&optional vertical-step horizontal-step)
...
(print-X-axis numbers-list horizontal-step))
" 3 0)) (295 (90.0 47.60907745361328 449.7485656738281 60.90726852416992 "The Printed Graph
277
" 0 0) (89.99981689453125 78.2418212890625 255.3708038330078 91.34580993652344 "C.4.6 The Printed Graph
" 1 0) (89.9993896484375 99.32910919189453 449.3230285644531 124.6272964477539 "When made and installed, you can call the print-graph command like
this:
" 2 0) (104.99911499023438 129.57766723632812 313.6144104003906 153.0673065185547 "(print-graph fiftieth-list-for-graph 50 10)
Here is the graph:
" 3 0) (111.59910583496094 179.97763061523438 309.206787109375 450.4238586425781 "1000 -
*
**
**
**
**
750 -
***
***
***
***
****
500 - *****
******
******
******
*******
250 - ********
*********
*
***********
*
*************
*
50 - ***************** *
*
|
|
|
|
|
|
|
|
10
50
100
150
200
250
300
350
" 4 0) (104.99923706054688 475.7689514160156 447.00970458984375 489.067138671875 "The largest group of functions contain 10 – 19 words and symbols each.
" 5 0)) (296 (90.0 47.60907745361328 449.6065368652344 60.90726852416992 "278
Appendix C: A Graph with Labelled Axes
" 0 0)) (297 (90.0 47.60907745361328 449.6186828613281 60.90726852416992 "GNU Free Documentation License
279
" 0 0) (90.00091552734375 71.18842315673828 429.5884094238281 107.26107025146484 "Appendix D GNU Free Documentation
License
" 1 0) (111.60115051269531 118.28907012939453 394.5724182128906 159.06724548339844 "Version 1.1, March 2000
Copyright c⃝ 2000 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
" 2 0) (95.88043212890625 170.60906982421875 449.52105712890625 630.7872924804688 "Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other
written document free in the sense of freedom: to assure everyone the
effective freedom to copy and redistribute it, with or without modifying
it, either commercially or noncommercially. Secondarily, this License
preserves for the author and publisher a way to get credit for their
work, while not being considered responsible for modifications made by
others.
This License is a kind of “copyleft”, which means that derivative works
of the document must themselves be free in the same sense. It com-
plements the GNU General Public License, which is a copyleft license
designed for free software.
We have designed this License in order to use it for manuals for free soft-
ware, because free software needs free documentation: a free program
should come with manuals providing the same freedoms that the soft-
ware does. But this License is not limited to software manuals; it can
be used for any textual work, regardless of subject matter or whether it
is published as a printed book. We recommend this License principally
for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work that contains a notice
placed by the copyright holder saying it can be distributed under the
terms of this License. The “Document”, below, refers to any such man-
ual or work. Any member of the public is a licensee, and is addressed
as “you”.
A “Modified Version” of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with modifica-
tions and/or translated into another language.
A “Secondary Section” is a named appendix or a front-matter section
of the Document that deals exclusively with the relationship of the pub-
lishers or authors of the Document to the Document’s overall subject
(or to related matters) and contains nothing that could fall directly
within that overall subject. (For example, if the Document is in part
a textbook of mathematics, a Secondary Section may not explain any
" 3 0)) (298 (90.0 47.60907745361328 449.4979248046875 60.90726852416992 "280
Appendix D: GNU Free Documentation License
" 0 0) (95.87757873535156 77.48908233642578 449.9007568359375 630.7872924804688 "mathematics.) The relationship could be a matter of historical connec-
tion with the subject or with related matters, or of legal, commercial,
philosophical, ethical or political position regarding them.
The “Invariant Sections” are certain Secondary Sections whose titles are
designated, as being those of Invariant Sections, in the notice that says
that the Document is released under this License.
The “Cover Texts” are certain short passages of text that are listed, as
Front-Cover Texts or Back-Cover Texts, in the notice that says that the
Document is released under this License.
A “Transparent” copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the general
public, whose contents can be viewed and edited directly and straight-
forwardly with generic text editors or (for images composed of pixels)
generic paint programs or (for drawings) some widely available drawing
editor, and that is suitable for input to text formatters or for automatic
translation to a variety of formats suitable for input to text formatters.
A copy made in an otherwise Transparent file format whose markup
has been designed to thwart or discourage subsequent modification by
readers is not Transparent. A copy that is not “Transparent” is called
“Opaque”.
Examples of suitable formats for Transparent copies include plain ascii
without markup, Texinfo input format, LaTEX input format, sgml
or xml using a publicly available dtd, and standard-conforming sim-
ple html designed for human modification. Opaque formats include
PostScript, pdf, proprietary formats that can be read and edited only
by proprietary word processors, sgml or xml for which the dtd and/or
processing tools are not generally available, and the machine-generated
html produced by some word processors for output purposes only.
The “Title Page” means, for a printed book, the title page itself, plus
such following pages as are needed to hold, legibly, the material this
License requires to appear in the title page. For works in formats which
do not have any title page as such, “Title Page” means the text near the
most prominent appearance of the work’s title, preceding the beginning
of the body of the text.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either com-
mercially or noncommercially, provided that this License, the copyright
notices, and the license notice saying this License applies to the Docu-
ment are reproduced in all copies, and that you add no other conditions
whatsoever to those of this License. You may not use technical mea-
sures to obstruct or control the reading or further copying of the copies
you make or distribute. However, you may accept compensation in ex-
change for copies. If you distribute a large enough number of copies you
must also follow the conditions in section 3.
" 1 0)) (299 (90.0 47.60907745361328 449.6186828613281 60.90726852416992 "GNU Free Documentation License
281
" 0 0) (95.87884521484375 77.48908233642578 449.5521545410156 630.7872924804688 "You may also lend copies, under the same conditions stated above, and
you may publicly display copies.
3. COPYING IN QUANTITY
If you publish printed copies of the Document numbering more than
100, and the Document’s license notice requires Cover Texts, you must
enclose the copies in covers that carry, clearly and legibly, all these Cover
Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly identify you as
the publisher of these copies. The front cover must present the full title
with all words of the title equally prominent and visible. You may add
other material on the covers in addition. Copying with changes limited
to the covers, as long as they preserve the title of the Document and
satisfy these conditions, can be treated as verbatim copying in other
respects.
If the required texts for either cover are too voluminous to fit legibly,
you should put the first ones listed (as many as fit reasonably) on the
actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transpar-
ent copy along with each Opaque copy, or state in or with each Opaque
copy a publicly-accessible computer-network location containing a com-
plete Transparent copy of the Document, free of added material, which
the general network-using public has access to download anonymously
at no charge using public-standard network protocols. If you use the
latter option, you must take reasonably prudent steps, when you begin
distribution of Opaque copies in quantity, to ensure that this Transpar-
ent copy will remain thus accessible at the stated location until at least
one year after the last time you distribute an Opaque copy (directly or
through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the
Document well before redistributing any large number of copies, to give
them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release
the Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution and
modification of the Modified Version to whoever possesses a copy of it.
In addition, you must do these things in the Modified Version:
A. Use in the Title Page (and on the covers, if any) a title distinct
from that of the Document, and from those of previous versions
(which should, if there were any, be listed in the History section of
the Document). You may use the same title as a previous version
if the original publisher of that version gives permission.
" 1 0)) (300 (90.0 47.60907745361328 449.4979248046875 60.90726852416992 "282
Appendix D: GNU Free Documentation License
" 0 0) (112.92091369628906 77.48908233642578 449.5851745605469 589.5075073242188 "B. List on the Title Page, as authors, one or more persons or enti-
ties responsible for authorship of the modifications in the Modified
Version, together with at least five of the principal authors of the
Document (all of its principal authors, if it has less than five).
C. State on the Title page the name of the publisher of the Modified
Version, as the publisher.
D. Preserve all the copyright notices of the Document.
E. Add an appropriate copyright notice for your modifications adja-
cent to the other copyright notices.
F. Include, immediately after the copyright notices, a license notice
giving the public permission to use the Modified Version under the
terms of this License, in the form shown in the Addendum below.
G. Preserve in that license notice the full lists of Invariant Sections
and required Cover Texts given in the Document’s license notice.
H. Include an unaltered copy of this License.
I. Preserve the section entitled “History”, and its title, and add to it
an item stating at least the title, year, new authors, and publisher
of the Modified Version as given on the Title Page. If there is no
section entitled “History” in the Document, create one stating the
title, year, authors, and publisher of the Document as given on its
Title Page, then add an item describing the Modified Version as
stated in the previous sentence.
J. Preserve the network location, if any, given in the Document for
public access to a Transparent copy of the Document, and likewise
the network locations given in the Document for previous versions
it was based on. These may be placed in the “History” section. You
may omit a network location for a work that was published at least
four years before the Document itself, or if the original publisher of
the version it refers to gives permission.
K. In any section entitled “Acknowledgments” or “Dedications”, pre-
serve the section’s title, and preserve in the section all the substance
and tone of each of the contributor acknowledgments and/or dedi-
cations given therein.
L. Preserve all the Invariant Sections of the Document, unaltered in
their text and in their titles. Section numbers or the equivalent are
not considered part of the section titles.
M. Delete any section entitled “Endorsements”. Such a section may
not be included in the Modified Version.
N. Do not retitle any existing section as “Endorsements” or to conflict
in title with any Invariant Section.
" 1 0) (111.60079956054688 593.6092529296875 449.43377685546875 630.7874755859375 "If the Modified Version includes new front-matter sections or appendices
that qualify as Secondary Sections and contain no material copied from
the Document, you may at your option designate some or all of these
" 2 0)) (301 (90.0 47.60907745361328 449.6186828613281 60.90726852416992 "GNU Free Documentation License
283
" 0 0) (95.88288879394531 77.48908233642578 449.52032470703125 630.7874755859375 "sections as invariant. To do this, add their titles to the list of Invariant
Sections in the Modified Version’s license notice. These titles must be
distinct from any other section titles.
You may add a section entitled “Endorsements”, provided it contains
nothing but endorsements of your Modified Version by various parties—
for example, statements of peer review or that the text has been ap-
proved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a
passage of up to 25 words as a Back-Cover Text, to the end of the list of
Cover Texts in the Modified Version. Only one passage of Front-Cover
Text and one of Back-Cover Text may be added by (or through ar-
rangements made by) any one entity. If the Document already includes
a cover text for the same cover, previously added by you or by arrange-
ment made by the same entity you are acting on behalf of, you may not
add another; but you may replace the old one, on explicit permission
from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or imply
endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under
this License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the Invari-
ant Sections of all of the original documents, unmodified, and list them
all as Invariant Sections of your combined work in its license notice.
The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single copy.
If there are multiple Invariant Sections with the same name but different
contents, make the title of each such section unique by adding at the end
of it, in parentheses, the name of the original author or publisher of that
section if known, or else a unique number. Make the same adjustment
to the section titles in the list of Invariant Sections in the license notice
of the combined work.
In the combination, you must combine any sections entitled “History”
in the various original documents, forming one section entitled “His-
tory”; likewise combine any sections entitled “Acknowledgments”, and
any sections entitled “Dedications”. You must delete all sections enti-
tled “Endorsements.”
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other docu-
ments released under this License, and replace the individual copies of
this License in the various documents with a single copy that is included
in the collection, provided that you follow the rules of this License for
verbatim copying of each of the documents in all other respects.
" 1 0)) (302 (90.0 47.60907745361328 449.4979248046875 60.90726852416992 "284
Appendix D: GNU Free Documentation License
" 0 0) (90.47881317138672 77.48908233642578 449.57354736328125 630.7874145507812 "You may extract a single document from such a collection, and distribute
it individually under this License, provided you insert a copy of this
License into the extracted document, and follow this License in all other
respects regarding verbatim copying of that document.
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage
or distribution medium, does not as a whole count as a Modified Ver-
sion of the Document, provided no compilation copyright is claimed for
the compilation. Such a compilation is called an “aggregate”, and this
License does not apply to the other self-contained works thus compiled
with the Document, on account of their being thus compiled, if they are
not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies
of the Document, then if the Document is less than one quarter of the
entire aggregate, the Document’s Cover Texts may be placed on covers
that surround only the Document within the aggregate. Otherwise they
must appear on covers around the whole aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute
translations of the Document under the terms of section 4. Replacing
Invariant Sections with translations requires special permission from
their copyright holders, but you may include translations of some or all
Invariant Sections in addition to the original versions of these Invariant
Sections. You may include a translation of this License provided that
you also include the original English version of this License. In case of
a disagreement between the translation and the original English version
of this License, the original English version will prevail.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document ex-
cept as expressly provided for under this License. Any other attempt
to copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License. However, par-
ties who have received copies, or rights, from you under this License will
not have their licenses terminated so long as such parties remain in full
compliance.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions
of the GNU Free Documentation License from time to time.
Such
new versions will be similar in spirit to the present version, but
may differ in detail to address new problems or concerns.
See
http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number.
If the Document specifies that a particular numbered version of this
" 1 0)) (303 (90.0 47.60907745361328 449.6186828613281 60.90726852416992 "GNU Free Documentation License
285
" 0 0) (111.60031127929688 77.48908233642578 449.4544372558594 150.5472869873047 "License “or any later version” applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation. If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.
" 1 0)) (304 (90.0 47.60907745361328 449.4979248046875 60.90726852416992 "286
Appendix D: GNU Free Documentation License
" 0 0)) (305 (90.0 47.60907745361328 449.8577575683594 60.90726852416992 "Index
287
" 0 0) (90.0 75.14844512939453 137.87603759765625 92.38106536865234 "Index
" 1 0) (90.0 115.10033416748047 103.45673370361328 129.46087646484375 "%
" 2 0) (90.0 133.895263671875 262.37646484375 142.8640594482422 "% (remainder function) . . . . . . . . . . . . . . 258
" 3 0) (89.99989318847656 162.62042236328125 96.28353118896484 176.98095703125 "(
" 4 0) (89.99989318847656 181.41534423828125 262.3677673339844 190.38414001464844 "(debug) in code . . . . . . . . . . . . . . . . . . . . 235
" 5 0) (90.00018310546875 209.780517578125 98.07709503173828 224.14105224609375 "*
" 6 0) (89.99983215332031 228.575439453125 262.3905944824219 259.7442321777344 "* (multiplication) . . . . . . . . . . . . . . . . . . . . 31
* for read-only buffer. . . . . . . . . . . . . . . . . 65
‘*scratch*’ buffer . . . . . . . . . . . . . . . . . . 123
" 7 0) (89.99990844726562 276.3804931640625 94.49027252197266 290.74102783203125 ".
" 8 0) (89.99990844726562 295.1754150390625 262.37786865234375 315.3041687011719 "‘.emacs’ file . . . . . . . . . . . . . . . . . . . . . . . . 213
‘.emacs’ file, beginning of . . . . . . . . . . . 216
" 9 0) (90.00067138671875 334.4605407714844 98.07758331298828 348.8210754394531 "/
" 10 0) (90.00067138671875 353.2554931640625 262.39373779296875 362.2242736816406 "/ (division). . . . . . . . . . . . . . . . . . . . . . . . . . 72
" 11 0) (90.00106811523438 379.0076599121094 97.38935852050781 393.3538818359375 ">
" 12 0) (90.00106811523438 397.7756042480469 262.3291931152344 406.744384765625 "> (greater than). . . . . . . . . . . . . . . . . . . . 40
" 13 0) (90.00152587890625 423.52777099609375 97.38981628417969 437.8739929199219 "<
" 14 0) (90.00152587890625 442.29571533203125 262.37445068359375 451.2644958496094 "<= (less than or equal) . . . . . . . . . . . . . . 127
" 15 0) (90.00186157226562 470.06085205078125 102.19612884521484 484.42138671875 "A
" 16 0) (90.00115966796875 488.8558044433594 262.4238586425781 630.30224609375 "Accumulate, type of recursive pattern
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
add-hook. . . . . . . . . . . . . . . . . . . . . . . . . . . 218
and. . . . . . . . . . . . . . . . . . . . . . . . . . . . 108, 156
and, introduced . . . . . . . . . . . . . . . . . . . . 108
Anonymous function . . . . . . . . . . . . . . . . 272
append-to-buffer . . . . . . . . . . . . . . . . . . . 56
apply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
apropos. . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Argument as local variable . . . . . . . . . . 131
‘argument’ defined . . . . . . . . . . . . . . . . . . . 12
‘argument list’ defined . . . . . . . . . . . . . . 30
Argument, wrong type of . . . . . . . . . . . . . 14
" 17 0) (277.4412841796875 119.13581085205078 449.8448791503906 216.7820587158203 "Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Arguments’ data types . . . . . . . . . . . . . . . 13
Arguments, variable number of. . . . . . . . 14
Asterisk for read-only buffer . . . . . . . . . . 65
Auto Fill mode turned on . . . . . . . . . . . 218
autoload. . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Automatic mode selection . . . . . . . . . . . 218
Axis, print horizontal . . . . . . . . . . . . . . . 263
Axis, print vertical. . . . . . . . . . . . . . . . . . 256
" 18 0) (277.44140625 235.2208251953125 288.9183654785156 249.58135986328125 "B
" 19 0) (277.439697265625 254.0157470703125 449.963623046875 395.8219299316406 "beginning-of-buffer. . . . . . . . . . . . . . . . 69
‘bind’ defined . . . . . . . . . . . . . . . . . . . . . . . 17
‘body’ defined . . . . . . . . . . . . . . . . . . . . . . . 30
Body of graph . . . . . . . . . . . . . . . . . . . . . . 203
Buffer size. . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Buffer, history of word . . . . . . . . . . . . . . . 24
buffer-file-name . . . . . . . . . . . . . . . . . . . 23
buffer-menu, bound to key . . . . . . . . . 221
buffer-name . . . . . . . . . . . . . . . . . . . . . . . . 23
Bug, most insidious type . . . . . . . . . . . . 274
Building robots . . . . . . . . . . . . . . . . . . . . . 134
Building Tags in the Emacs sources . . 164
Byte compiling . . . . . . . . . . . . . . . . . . . . . . . 8
" 20 0) (277.43890380859375 414.26068115234375 289.10235595703125 428.6212158203125 "C
" 21 0) (277.43450927734375 433.175537109375 449.8598937988281 630.304443359375 "C language primitives . . . . . . . . . . . . . . . . 29
C, a digression into . . . . . . . . . . . . . . . . . . 98
‘call’ defined . . . . . . . . . . . . . . . . . . . . . . . 27
cancel-debug-on-entry. . . . . . . . . . . . . 234
car, introduced . . . . . . . . . . . . . . . . . . . . . 81
cdr, introduced . . . . . . . . . . . . . . . . . . . . . 81
Changing a function definition . . . . . . . . 32
Chest of Drawers, metaphor for a symbol
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Clipping text . . . . . . . . . . . . . . . . . . . . . . . . 89
Code installation . . . . . . . . . . . . . . . . . . . . 36
‘command’ defined . . . . . . . . . . . . . . . . . . . . 23
Comments in Lisp code . . . . . . . . . . . . . . 32
Common Lisp. . . . . . . . . . . . . . . . . . . . . . . xiii
compare-windows . . . . . . . . . . . . . . . . . . . 220
concat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
cond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
condition-case . . . . . . . . . . . . . . . . . . . . . 95
" 22 0)) (306 (90.0 47.60907745361328 450.04339599609375 60.90726852416992 "288
Index
" 0 0) (89.99984741210938 81.33521270751953 262.4228515625 250.14186096191406 "Conditional ’twixt two versions of Emacs
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Conditional with if. . . . . . . . . . . . . . . . . . 39
cons, example. . . . . . . . . . . . . . . . . . . . . . 107
cons, introduced . . . . . . . . . . . . . . . . . . . . 83
copy-region-as-kill. . . . . . . . . . . . . . . 102
copy-to-buffer . . . . . . . . . . . . . . . . . . . . . 63
Count words recursively . . . . . . . . . . . . . 173
count-words-in-defun. . . . . . . . . . . . . . 185
count-words-region. . . . . . . . . . . . . . . . 167
Counting. . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Counting words in a defun . . . . . . 181, 183
current-buffer . . . . . . . . . . . . . . . . . . . . . 25
Customizing your ‘.emacs’ file . . . . . . . 213
Cutting and storing text. . . . . . . . . . . . . . 89
" 1 0) (90.00006103515625 270.62060546875 102.36648559570312 284.98114013671875 "D
" 2 0) (89.99969482421875 290.25543212890625 262.4266357421875 630.3016967773438 "Data types . . . . . . . . . . . . . . . . . . . . . . . . . . 13
debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
debug-on-entry . . . . . . . . . . . . . . . . . . . . 232
debug-on-quit . . . . . . . . . . . . . . . . . . . . . 234
debugging . . . . . . . . . . . . . . . . . . . . . . . . . . 231
default-mode-line-format . . . . . . . . . 228
‘default.el’ init file . . . . . . . . . . . . . . . . 213
defcustom . . . . . . . . . . . . . . . . . . . . . . . . . 214
Deferment in recursion . . . . . . . . . . . . . . 143
Defermentless solution . . . . . . . . . . . . . . 145
Definition installation . . . . . . . . . . . . . . . . 31
Definition writing . . . . . . . . . . . . . . . . . . . . 29
Definition, how to change. . . . . . . . . . . . . 32
defun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
defvar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
defvar for a user customizable variable
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
defvar with an asterisk . . . . . . . . . . . . . 101
delete-and-extract-region . . . . . . 96, 98
Deleting text . . . . . . . . . . . . . . . . . . . . . . . . 89
describe-function . . . . . . . . . . . . . . . . . . 53
describe-function, introduced . . . . . . 51
Digression into C . . . . . . . . . . . . . . . . . . . . 98
directory-files . . . . . . . . . . . . . . . . . . . 194
Division. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
dolist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
dotimes. . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Drawers, Chest of, metaphor for a symbol
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Duplicated words function . . . . . . . . . . . 241
" 3 0) (277.4441223144531 77.30046844482422 288.0316162109375 91.66101837158203 "E
" 4 0) (277.43896484375 96.21533966064453 449.9554443359375 349.9836730957031 "edebug. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
edit-options . . . . . . . . . . . . . . . . . . . . . . 101
Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Emacs version, choosing . . . . . . . . . . . . . 225
‘empty list’ defined . . . . . . . . . . . . . . . . . . 2
‘empty string’ defined . . . . . . . . . . . . . . . 48
eobp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
eq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
eq (example of use) . . . . . . . . . . . . . . . . . 104
equal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Erasing text . . . . . . . . . . . . . . . . . . . . . . . . . 89
error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Error for symbol without function. . . . . 11
Error for symbol without value . . . . . . . 11
Error message generation . . . . . . . . . . . . . . 4
etags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
‘evaluate’ defined . . . . . . . . . . . . . . . . . . . . 4
Evaluating inner lists. . . . . . . . . . . . . . . . . . 9
Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Evaluation practice . . . . . . . . . . . . . . . . . . 23
Every, type of recursive pattern . . . . . . 141
Example variable, fill-column . . . . . . . 10
‘expression’ defined . . . . . . . . . . . . . . . . . . 2
" 5 0) (277.43975830078125 368.9000549316406 287.58251953125 383.2605895996094 "F
" 6 0) (277.4371032714844 387.8149108886719 449.9739990234375 630.3014526367188 "Falsehood and truth in Emacs Lisp. . . . 43
FDL, GNU Free Documentation License
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
files-in-below-directory . . . . . . . . . 194
fill-column, an example variable . . . . 10
Find a File . . . . . . . . . . . . . . . . . . . . . . . . . 187
Find function documentation . . . . . . . . . 51
Find source of function . . . . . . . . . . . . . . . 51
find-tags. . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Flowers in a field . . . . . . . . . . . . . . . . . . . . . 1
Focusing attention (narrowing) . . . . . . . 77
‘form’ defined. . . . . . . . . . . . . . . . . . . . . . . . . 2
Formatting convention . . . . . . . . . . . . . . . 58
Formatting help . . . . . . . . . . . . . . . . . . . . . . 3
forward-paragraph . . . . . . . . . . . . . . . . . 155
forward-sentence . . . . . . . . . . . . . . . . . . 151
‘function’ defined . . . . . . . . . . . . . . . . . . 5, 6
‘function definition’ defined. . . . . . . . 29
Function definition installation. . . . . . . . 31
Function definition writing . . . . . . . . . . . 29
Function definition, how to change . . . . 32
Functions, primitive. . . . . . . . . . . . . . . . . . 29
" 7 0)) (307 (90.0 47.60907745361328 449.8577575683594 60.90726852416992 "Index
289
" 0 0) (90.0 77.30034637451172 102.68203735351562 91.66089630126953 "G
" 1 0) (90.0 96.09528350830078 262.3970642089844 193.5038299560547 "Generate an error message. . . . . . . . . . . . . 4
Getting a buffer . . . . . . . . . . . . . . . . . . . . . 25
Global set key . . . . . . . . . . . . . . . . . . . . . . 220
global-set-key . . . . . . . . . . . . . . . . . . . . 220
global-unset-key . . . . . . . . . . . . . . . . . . 221
Graph prototype. . . . . . . . . . . . . . . . . . . . 203
Graph, printing all. . . . . . . . . . . . . . . . . . 267
graph-body-print . . . . . . . . . . . . . . . . . . 208
graph-body-print Final version.. . . . . 268
" 2 0) (90.00143432617188 212.0601806640625 102.62609100341797 226.42071533203125 "H
" 3 0) (90.00143432617188 230.8551025390625 262.4039001464844 261.9014587402344 "Handling the kill ring . . . . . . . . . . . . . . . 243
Help typing lists . . . . . . . . . . . . . . . . . . . . . . 3
Horizontal axis printing . . . . . . . . . . . . . 263
" 4 0) (90.0023193359375 280.22021484375 96.01337432861328 294.58074951171875 "I
" 5 0) (90.00135803222656 299.01513671875 262.4073181152344 506.8215026855469 "if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
‘if-part’ defined . . . . . . . . . . . . . . . . . . . . 40
indent-tabs-mode . . . . . . . . . . . . . . . . . . 219
Indentation for formatting . . . . . . . . . . . . 58
Initialization file . . . . . . . . . . . . . . . . . . . . 213
Initializing a variable. . . . . . . . . . . . . . . . 100
Inner list evaluation. . . . . . . . . . . . . . . . . . . 9
insert-buffer . . . . . . . . . . . . . . . . . . . . . . 64
insert-buffer-substring . . . . . . . . . . . 56
Insidious type of bug. . . . . . . . . . . . . . . . 274
Install a Function Definition . . . . . . . . . . 31
Install code permanently . . . . . . . . . . . . . 36
interactive . . . . . . . . . . . . . . . . . . . . . . . . 33
‘interactive function’ defined. . . . . . . 23
Interactive functions . . . . . . . . . . . . . . . . . 33
Interactive options . . . . . . . . . . . . . . . . . . . 35
interactive, example use of . . . . . . . . . 65
Interpreter, Lisp, explained . . . . . . . . . . . . 4
Interpreter, what it does. . . . . . . . . . . . . . . 7
" 6 0) (90.00146484375 525.1402587890625 102.64046478271484 539.5007934570312 "K
" 7 0) (90.00115966796875 543.9352416992188 262.404541015625 630.3040161132812 "Keep, type of recursive pattern . . . . . . 143
Key setting globally. . . . . . . . . . . . . . . . . 220
Key unbinding. . . . . . . . . . . . . . . . . . . . . . 221
Keymaps. . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Kill ring handling. . . . . . . . . . . . . . . . . . . 243
Kill ring overview. . . . . . . . . . . . . . . . . . . 117
kill-append . . . . . . . . . . . . . . . . . . . . . . . 104
" 8 0) (277.441162109375 81.33521270751953 449.8414611816406 112.62165832519531 "kill-new. . . . . . . . . . . . . . . . . . . . . . . . . . . 105
kill-region . . . . . . . . . . . . . . . . . . . . . . . . 94
Killing text. . . . . . . . . . . . . . . . . . . . . . . . . . 89
" 9 0) (277.4407958984375 131.42041015625 287.1388244628906 145.78094482421875 "L
" 10 0) (277.43402099609375 150.45526123046875 449.9639892578125 449.58160400390625 "lambda. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
length. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
lengths-list-file . . . . . . . . . . . . . . . . . 188
lengths-list-many-files . . . . . . . . . . 190
let . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
let expression sample. . . . . . . . . . . . . . . . 38
let expression, parts of . . . . . . . . . . . . . . 37
let variables uninitialized . . . . . . . . . . . . 39
Library, as term for ‘file’ . . . . . . . . . . . . . 52
line-to-top-of-window. . . . . . . . . . . . . 224
Lisp Atoms. . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Lisp history . . . . . . . . . . . . . . . . . . . . . . . . xiii
Lisp interpreter, explained . . . . . . . . . . . . . 4
Lisp interpreter, what it does . . . . . . . . . . 7
Lisp Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Lisp macro . . . . . . . . . . . . . . . . . . . . . . . . . . 97
list-buffers, rebound . . . . . . . . . . . . . 221
Lists in a computer . . . . . . . . . . . . . . . . . 113
load-library . . . . . . . . . . . . . . . . . . . . . . 223
load-path . . . . . . . . . . . . . . . . . . . . . . . . . 223
Loading files. . . . . . . . . . . . . . . . . . . . . . . . 222
‘local variable’ defined . . . . . . . . . . . . . 37
Local variables list, per-buffer, . . . . . . . 218
Location of point . . . . . . . . . . . . . . . . . . . . 27
looking-at . . . . . . . . . . . . . . . . . . . . . . . . 159
Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Loops and recursion. . . . . . . . . . . . . . . . . 121
" 11 0) (277.433349609375 468.3803405761719 292.7407531738281 482.7408752441406 "M
" 12 0) (277.42828369140625 487.4151916503906 449.83624267578125 630.3016357421875 "Maclisp . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Macro, lisp . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Mail aliases . . . . . . . . . . . . . . . . . . . . . . . . 219
make tags . . . . . . . . . . . . . . . . . . . . . . . . . . 164
make-string . . . . . . . . . . . . . . . . . . . . . . . 261
mapcar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
mark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
mark-whole-buffer . . . . . . . . . . . . . . . . . . 54
match-beginning . . . . . . . . . . . . . . . . . . . 161
max . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
message. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
min . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Mode line format . . . . . . . . . . . . . . . . . . . 228
" 13 0)) (308 (90.0 47.60907745361328 450.04339599609375 60.90726852416992 "290
Index
" 0 0) (90.0 81.33521270751953 262.38665771484375 101.46168518066406 "Mode selection, automatic . . . . . . . . . . . 218
Motion by sentence and paragraph . . . 149
" 1 0) (90.00006103515625 120.26042938232422 102.62471771240234 134.6209716796875 "N
" 2 0) (89.99977111816406 139.17529296875 262.40301513671875 248.46385192871094 "Narrowing. . . . . . . . . . . . . . . . . . . . . . . . . . . 77
‘narrowing’ defined . . . . . . . . . . . . . . . . . . 28
nil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
nil, history of word. . . . . . . . . . . . . . . . . . 24
No deferment solution. . . . . . . . . . . . . . . 145
nreverse. . . . . . . . . . . . . . . . . . . . . . . . . . . 199
nth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
nthcdr . . . . . . . . . . . . . . . . . . . . . . . . . 85, 102
nthcdr, example . . . . . . . . . . . . . . . . . . . 107
number-to-string . . . . . . . . . . . . . . . . . . 259
" 3 0) (90.00041198730469 267.50018310546875 102.12295532226562 281.8607177734375 "O
" 4 0) (90.00013732910156 286.4150390625 262.4051208496094 351.1838684082031 "occur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
optional. . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Optional arguments . . . . . . . . . . . . . . . . . . 70
Options for interactive . . . . . . . . . . . . . 35
or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
other-buffer . . . . . . . . . . . . . . . . . . . . . . . 25
" 5 0) (90.00054931640625 368.42022705078125 101.03277587890625 382.78076171875 "P
" 6 0) (89.99996948242188 387.3350830078125 262.39910888671875 630.303955078125 "Paragraphs, movement by . . . . . . . . . . . 149
Parts of a Recursive Definition. . . . . . . 135
Parts of let expression . . . . . . . . . . . . . . . 37
Passing information to functions . . . . . . 12
Pasting text . . . . . . . . . . . . . . . . . . . . . . . . 117
Patterns, searching for . . . . . . . . . . . . . . 149
Per-buffer, local variables list . . . . . . . . 218
Permanent code installation . . . . . . . . . . 36
point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
‘point’ defined . . . . . . . . . . . . . . . . . . . . . . 27
Point location . . . . . . . . . . . . . . . . . . . . . . . 27
Point, mark, buffer preservation. . . . . . . 44
Practicing evaluation. . . . . . . . . . . . . . . . . 23
Preserving point, mark, and buffer . . . . 44
Primitive functions. . . . . . . . . . . . . . . . . . . 29
Primitives written in C. . . . . . . . . . . . . . . 29
Print horizontal axis . . . . . . . . . . . . . . . . 263
Print vertical axis. . . . . . . . . . . . . . . . . . . 256
print-elements-of-list . . . . . . . . . . . 123
print-elements-recursively . . . . . . . 136
print-graph Final version. . . . . . . . . . . 269
print-graph varlist . . . . . . . . . . . . . . . . . 256
" 7 0) (277.44158935546875 81.33515167236328 449.94439697265625 192.30140686035156 "print-X-axis . . . . . . . . . . . . . . . . . . . . . . 266
print-X-axis-numbered-line . . . . . . . 265
print-X-axis-tic-line. . . . . . . . . . . . . 265
print-Y-axis . . . . . . . . . . . . . . . . . . . . . . 262
Printing the whole graph . . . . . . . . . . . . 267
prog1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
progn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Program, running one . . . . . . . . . . . . . . . . . 4
Prototype graph . . . . . . . . . . . . . . . . . . . . 203
" 8 0) (277.44171142578125 219.98016357421875 289.4781799316406 234.3406982421875 "R
" 9 0) (277.4353942871094 242.375 449.9478759765625 630.30126953125 "re-search-forward . . . . . . . . . . . . . . . . . 150
Read-only buffer . . . . . . . . . . . . . . . . . . . . . 65
Readying a graph . . . . . . . . . . . . . . . . . . . 203
Rebinding keys . . . . . . . . . . . . . . . . . . . . . 221
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Recursion and loops. . . . . . . . . . . . . . . . . 121
Recursion without Deferments . . . . . . . 143
Recursive Definition Parts . . . . . . . . . . . 135
Recursive pattern: accumulate . . . . . . . 142
Recursive pattern: every . . . . . . . . . . . . 141
Recursive pattern: keep . . . . . . . . . . . . . 143
Recursive Patterns. . . . . . . . . . . . . . . . . . 140
recursive-count-words. . . . . . . . . . . . . 178
recursive-graph-body-print . . . . . . . 210
recursive-lengths-list-many-files
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Recursively counting words . . . . . . . . . . 173
regexp-quote . . . . . . . . . . . . . . . . . . . . . . 157
Region, what it is. . . . . . . . . . . . . . . . . . . . 44
Regular expression searches. . . . . . . . . . 149
Regular expressions for word counting
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Remainder function, %. . . . . . . . . . . . . . . 258
Repetition (loops) . . . . . . . . . . . . . . . . . . 121
Repetition for word counting . . . . . . . . 167
Retrieving text . . . . . . . . . . . . . . . . . . . . . 117
reverse. . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Ring, making a list like a . . . . . . . . . . . . 243
Robots, building . . . . . . . . . . . . . . . . . . . . 134
rotate-yank-pointer . . . . . . . . . . 117, 243
Run a program . . . . . . . . . . . . . . . . . . . . . . . 4
" 10 0)) (309 (90.0 47.60907745361328 449.8577575683594 60.90726852416992 "Index
291
" 0 0) (90.0 77.30034637451172 98.96637725830078 91.66089630126953 "S
" 1 0) (89.99928283691406 96.21521759033203 262.40789794921875 494.58123779296875 "Sample let expression . . . . . . . . . . . . . . . 38
save-excursion . . . . . . . . . . . . . . . . . . . . . 44
save-restriction . . . . . . . . . . . . . . . . . . . 77
search-forward . . . . . . . . . . . . . . . . . . . . . 92
Searches, illustrating . . . . . . . . . . . . . . . . 149
sentence-end . . . . . . . . . . . . . . . . . . . . . . 149
Sentences, movement by.. . . . . . . . . . . . 149
set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
set-buffer . . . . . . . . . . . . . . . . . . . . . . . . . 26
setcar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
setcdr. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
setcdr, example . . . . . . . . . . . . . . . . . . . 107
setq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Setting a key globally . . . . . . . . . . . . . . . 220
Setting value of variable . . . . . . . . . . . . . . 17
‘side effect’ defined . . . . . . . . . . . . . . . . . 8
Simple extension in ‘.emacs’ file . . . . . 224
simplified-beginning-of-buffer . . . . 52
‘site-init.el’ init file. . . . . . . . . . . . . . 213
‘site-load.el’ init file. . . . . . . . . . . . . . 213
Size of buffer . . . . . . . . . . . . . . . . . . . . . . . . 27
Solution without deferment . . . . . . . . . . 145
sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Source level debugger . . . . . . . . . . . . . . . 235
Special form . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Special form of defun . . . . . . . . . . . . . . . . 29
Storing and cutting text. . . . . . . . . . . . . . 89
‘string’ defined . . . . . . . . . . . . . . . . . . . . . . 3
switch-to-buffer . . . . . . . . . . . . . . . . . . . 26
Switching to a buffer . . . . . . . . . . . . . . . . . 26
Symbol names . . . . . . . . . . . . . . . . . . . . . . . . 6
Symbol without function error . . . . . . . . 11
Symbol without value error . . . . . . . . . . . 11
Symbolic expressions, introduced. . . . . . . 2
Symbols as a Chest of Drawers. . . . . . . 115
Syntax categories and tables . . . . . . . . . 182
" 2 0) (90.00112915039062 513.3800048828125 101.21985626220703 527.7405395507812 "T
" 3 0) (90.00044250488281 532.2948608398438 262.3994140625 630.3036499023438 "Tabs, preventing. . . . . . . . . . . . . . . . . . . . 219
‘TAGS’ file, create own . . . . . . . . . . . . . . . 163
Tags in the Emacs sources. . . . . . . . . . . 164
TAGS table, specifying . . . . . . . . . . . . . . . 51
Text between double quotation marks . . 3
Text Mode turned on . . . . . . . . . . . . . . . 218
Text retrieval. . . . . . . . . . . . . . . . . . . . . . . 117
the-the. . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
‘then-part’ defined . . . . . . . . . . . . . . . . . . 40
" 4 0) (277.4398193359375 81.33484649658203 449.833984375 134.7011260986328 "top-of-ranges . . . . . . . . . . . . . . . . . . . . . 198
triangle-bugged . . . . . . . . . . . . . . . . . . . 231
triangle-recursively. . . . . . . . . . . . . . 137
Truth and falsehood in Emacs Lisp. . . . 43
Types of data . . . . . . . . . . . . . . . . . . . . . . . 13
" 5 0) (277.4393310546875 153.2598876953125 289.8487854003906 167.62042236328125 "U
" 6 0) (277.4393310546875 172.17474365234375 449.8349914550781 192.1835174560547 "Unbinding key . . . . . . . . . . . . . . . . . . . . . . 221
Uninitialized let variables. . . . . . . . . . . . 39
" 7 0) (277.43927001953125 209.29986572265625 289.633544921875 223.660400390625 "V
" 8 0) (277.4372863769531 228.2147216796875 449.8435974121094 314.8209533691406 "Variable initialization . . . . . . . . . . . . . . . 100
Variable number of arguments . . . . . . . . 14
Variable, example of, fill-column . . . . 10
Variable, setting value. . . . . . . . . . . . . . . . 17
Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
‘varlist’ defined . . . . . . . . . . . . . . . . . . . . 37
Version of Emacs, choosing . . . . . . . . . . 225
Vertical axis printing. . . . . . . . . . . . . . . . 256
" 9 0) (277.43695068359375 333.37969970703125 294.10723876953125 347.740234375 "W
" 10 0) (277.43414306640625 352.2945556640625 449.9629821777344 483.4210205078125 "what-line. . . . . . . . . . . . . . . . . . . . . . . . . . . 78
while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Whitespace in lists . . . . . . . . . . . . . . . . . . . . 3
Whole graph printing . . . . . . . . . . . . . . . 267
Widening . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Widening, example of . . . . . . . . . . . . . . . . 78
Word counting in a defun . . . . . . . . . . . 181
Words and symbols in defun . . . . . . . . . 181
Words, counted recursively . . . . . . . . . . 173
Words, duplicated . . . . . . . . . . . . . . . . . . 241
Writing a function definition . . . . . . . . . . 29
Wrong type of argument. . . . . . . . . . . . . . 14
" 11 0) (277.4342346191406 501.979736328125 289.6285095214844 516.3402709960938 "X
" 12 0) (277.4342346191406 520.8945922851562 449.827880859375 541.0234375 "X axis printing . . . . . . . . . . . . . . . . . . . . . 263
X-axis-element . . . . . . . . . . . . . . . . . . . . 265
" 13 0) (277.4344787597656 558.019775390625 289.6287536621094 572.3803100585938 "Y
" 14 0) (277.43414306640625 576.9346313476562 449.828125 630.303466796875 "Y axis printing . . . . . . . . . . . . . . . . . . . . . 256
Y-axis-column . . . . . . . . . . . . . . . . . . . . . 261
Y-axis-column Final version. . . . . . . . . 268
Y-axis-label-spacing. . . . . . . . . . . . . . 259
Y-axis-tic . . . . . . . . . . . . . . . . . . . . . . . . 260
" 15 0)) (310 (90.0 47.60907745361328 450.04339599609375 60.90726852416992 "292
Index
" 0 0) (90.0 81.33521270751953 262.3816833496094 90.30400085449219 "yank . . . . . . . . . . . . . . . . . . . . . . . . . . 117, 249
" 1 0) (90.0001220703125 109.65522003173828 262.3616027832031 118.62400817871094 "yank-pop. . . . . . . . . . . . . . . . . . . . . . . . . . . 252
" 2 0) (277.44012451171875 77.30034637451172 287.310302734375 91.66089630126953 "Z
" 3 0) (277.43963623046875 97.77521514892578 449.8208312988281 118.62400817871094 "zap-to-char . . . . . . . . . . . . . . . . . . . . . . . . 90
zerop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
" 4 0)) (313 (226.44000244140625 199.049072265625 313.37457275390625 212.34727478027344 "About the Author
" 0 0) (111.59902954101562 225.4490966796875 427.9734802246094 325.8671569824219 "Robert J. Chassell has worked with GNU Emacs since 1985. He
writes and edits, teaches Emacs and Emacs Lisp, and speaks
throughout the world on software freedom. Chassell was a found-
ing Director and Treasurer of the Free Software Foundation, Inc.
He is co-author of the Texinfo manual, and has edited more than
a dozen other books. He graduated from Cambridge University, in
England. He has an abiding interest in social and economic history
and flies his own airplane.
" 1 0))))

(provide 'baleen)
;;; baleen.el ends here

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 19:29 displaying margins leads to Emacs hanging dalanicolai
@ 2023-02-24 19:41 ` Eli Zaretskii
  2023-02-24 20:26   ` dalanicolai
  0 siblings, 1 reply; 14+ messages in thread
From: Eli Zaretskii @ 2023-02-24 19:41 UTC (permalink / raw)
  To: dalanicolai; +Cc: emacs-devel

> From: dalanicolai <dalanicolai@gmail.com>
> Date: Fri, 24 Feb 2023 20:29:02 +0100
> 
> I am encountering the problem as described in the subject of this email.
> 
> I hope you could enlighten me again about this issue.
> 
> Some brief context:
> I am trying to build a kind of swiper/swoop for searching documents.
> I have tried to use Ivy/Vertico (see https://github.com/minad/consult/issues/625),
> but I think they are not well suited/too heavy for this. So, I concluded that,
> unfortunately, I have to 'reinvent the wheel'.
> 
> Anyway, to reproduce the issue starting from emacs -q,
> please load the attached file and do `M-x baleen` (the file is large because
> it includes the text of `An Introduction to Programming in Emacs Lisp`).

That's a huge file.

> Then type 'ho' and optionally continue typing to narrow down the results.
> Press RET to finish (I am just starting development, so never mind further
> 'testing' the current functionality. Although of course, suggestions for
> improvements are welcome).
> As you will find, hopefully, things seem to work fine.
> Page numbers are nicely displayed in the margins.
> 
> Now, do `M-x baleen2`. This time, the data consists of the contents of the
> the book `An Introduction to Programming in Emacs Lisp.' Now type e.g.
> 'emacs' to narrow down the results. The page numbers are not displayed
> in the margins, to show that things still work fine.
> 
> NOTE the next step should (well, should not of course) make Emacs hang:
> 
> Now just uncomment the line
>   ;; (set-window-margins nil 4)
> in the function `baleen2` and repeat the last step (`M-x baleen2`).
> Again, try to type 'emacs'. Unfortunately, Emacs more or less hangs.
> 
> I have no idea why suddenly Emacs hangs. I was wondering if any of
> you could explain this behavior, and hopefully suggest how to
> prevent it.
> (Of course, if there is no other solution, then I could just display the
> page numbers in the buffer text).
> 
> I also have a second question, but I will send it in another mail (with its
> own subject).

Did you try yourself to establish where Emacs loops and why?  The file
etc/DEBUG includes instructions for how to debug what looks like an
infloop; search for "If the symptom of the bug is that Emacs fails to
respond".

I notice that you say "more or less hangs".  What does this mean,
exactly?  Does C-g interrupt the "hang"?



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 19:41 ` Eli Zaretskii
@ 2023-02-24 20:26   ` dalanicolai
  2023-02-24 20:29     ` Eli Zaretskii
  0 siblings, 1 reply; 14+ messages in thread
From: dalanicolai @ 2023-02-24 20:26 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel

[-- Attachment #1: Type: text/plain, Size: 3736 bytes --]

I have not really looked at it yet, but just as a quick thought:
I am not sure if/why I should debug an infloop, because the functionality
works perfectly fine when not showing the margins (i.e. when just setting
the window margins to nil). So it seems to me its not about an infinite
loop.

I was saying 'more or less' because it does not really hang, it just takes
extremely long to update the buffer text. When waiting long enough,
then it seems to continue.

Of course, I don't want to waste your time, but I think my instructions
for reproducing the error, are very clear and short this time (i.e. take
less
than/about a minute). I think it would be most informative if you reproduce
the
error there.

That's a huge file.
>

The file is huge because I've added a lot of data in the file (i.e. the text
 of the book `An Introduction to Programming in Emacs Lisp`).
I've mentioned it exactly at the point where you write 'that file is huge'
in your previous message.

Of course, I will have a look at etc/DEBUG now, but I hope you can find
the minute to reproduce the error following my instruction (I guarantee
that the steps for reproducing are very clear and brief).

On Fri, 24 Feb 2023 at 20:41, Eli Zaretskii <eliz@gnu.org> wrote:

> > From: dalanicolai <dalanicolai@gmail.com>
> > Date: Fri, 24 Feb 2023 20:29:02 +0100
> >
> > I am encountering the problem as described in the subject of this email.
> >
> > I hope you could enlighten me again about this issue.
> >
> > Some brief context:
> > I am trying to build a kind of swiper/swoop for searching documents.
> > I have tried to use Ivy/Vertico (see
> https://github.com/minad/consult/issues/625),
> > but I think they are not well suited/too heavy for this. So, I concluded
> that,
> > unfortunately, I have to 'reinvent the wheel'.
> >
> > Anyway, to reproduce the issue starting from emacs -q,
> > please load the attached file and do `M-x baleen` (the file is large
> because
> > it includes the text of `An Introduction to Programming in Emacs Lisp`).
>
> That's a huge file.
>
> > Then type 'ho' and optionally continue typing to narrow down the results.
> > Press RET to finish (I am just starting development, so never mind
> further
> > 'testing' the current functionality. Although of course, suggestions for
> > improvements are welcome).
> > As you will find, hopefully, things seem to work fine.
> > Page numbers are nicely displayed in the margins.
> >
> > Now, do `M-x baleen2`. This time, the data consists of the contents of
> the
> > the book `An Introduction to Programming in Emacs Lisp.' Now type e.g.
> > 'emacs' to narrow down the results. The page numbers are not displayed
> > in the margins, to show that things still work fine.
> >
> > NOTE the next step should (well, should not of course) make Emacs hang:
> >
> > Now just uncomment the line
> >   ;; (set-window-margins nil 4)
> > in the function `baleen2` and repeat the last step (`M-x baleen2`).
> > Again, try to type 'emacs'. Unfortunately, Emacs more or less hangs.
> >
> > I have no idea why suddenly Emacs hangs. I was wondering if any of
> > you could explain this behavior, and hopefully suggest how to
> > prevent it.
> > (Of course, if there is no other solution, then I could just display the
> > page numbers in the buffer text).
> >
> > I also have a second question, but I will send it in another mail (with
> its
> > own subject).
>
> Did you try yourself to establish where Emacs loops and why?  The file
> etc/DEBUG includes instructions for how to debug what looks like an
> infloop; search for "If the symptom of the bug is that Emacs fails to
> respond".
>
> I notice that you say "more or less hangs".  What does this mean,
> exactly?  Does C-g interrupt the "hang"?
>

[-- Attachment #2: Type: text/html, Size: 5182 bytes --]

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 20:26   ` dalanicolai
@ 2023-02-24 20:29     ` Eli Zaretskii
  2023-02-24 20:41       ` dalanicolai
  0 siblings, 1 reply; 14+ messages in thread
From: Eli Zaretskii @ 2023-02-24 20:29 UTC (permalink / raw)
  To: dalanicolai; +Cc: emacs-devel

> From: dalanicolai <dalanicolai@gmail.com>
> Date: Fri, 24 Feb 2023 21:26:05 +0100
> Cc: emacs-devel@gnu.org
> 
> I have not really looked at it yet, but just as a quick thought:
> I am not sure if/why I should debug an infloop, because the functionality
> works perfectly fine when not showing the margins (i.e. when just setting 
> the window margins to nil). So it seems to me its not about an infinite loop.
> 
> I was saying 'more or less' because it does not really hang, it just takes
> extremely long to update the buffer text. When waiting long enough,
> then it seems to continue.
> 
> Of course, I don't want to waste your time, but I think my instructions
> for reproducing the error, are very clear and short this time (i.e. take less
> than/about a minute). I think it would be most informative if you reproduce the
> error there.

What should I do after I reproduce it, though?  What are your
expectations from me (or whoever else tries your recipe)?



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 20:29     ` Eli Zaretskii
@ 2023-02-24 20:41       ` dalanicolai
  2023-02-24 20:53         ` dalanicolai
  2023-02-24 21:25         ` Eli Zaretskii
  0 siblings, 2 replies; 14+ messages in thread
From: dalanicolai @ 2023-02-24 20:41 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel

[-- Attachment #1: Type: text/plain, Size: 1297 bytes --]

I hope you might have an idea what causes this behavior. And maybe you
have a suggestion how to prevent it. Furthermore, I guess the behavior might
be interesting for you to note/observe (but that is just a guess).

On Fri, 24 Feb 2023 at 21:29, Eli Zaretskii <eliz@gnu.org> wrote:

> > From: dalanicolai <dalanicolai@gmail.com>
> > Date: Fri, 24 Feb 2023 21:26:05 +0100
> > Cc: emacs-devel@gnu.org
> >
> > I have not really looked at it yet, but just as a quick thought:
> > I am not sure if/why I should debug an infloop, because the functionality
> > works perfectly fine when not showing the margins (i.e. when just
> setting
> > the window margins to nil). So it seems to me its not about an infinite
> loop.
> >
> > I was saying 'more or less' because it does not really hang, it just
> takes
> > extremely long to update the buffer text. When waiting long enough,
> > then it seems to continue.
> >
> > Of course, I don't want to waste your time, but I think my instructions
> > for reproducing the error, are very clear and short this time (i.e. take
> less
> > than/about a minute). I think it would be most informative if you
> reproduce the
> > error there.
>
> What should I do after I reproduce it, though?  What are your
> expectations from me (or whoever else tries your recipe)?
>

[-- Attachment #2: Type: text/html, Size: 1843 bytes --]

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 20:41       ` dalanicolai
@ 2023-02-24 20:53         ` dalanicolai
  2023-02-24 21:19           ` dalanicolai
  2023-02-25 10:51           ` Eli Zaretskii
  2023-02-24 21:25         ` Eli Zaretskii
  1 sibling, 2 replies; 14+ messages in thread
From: dalanicolai @ 2023-02-24 20:53 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel


[-- Attachment #1.1: Type: text/plain, Size: 1844 bytes --]

B.t.w if someone want to have a look, I'll attach a smaller file here where
I have just removed about 200 pages of the book text data, so that it is
the file is much smaller, but there is still enough date to clearly show the
'undesired' behavior.

So now, Emacs will not 'hang', but there will still be a clear difference
in time it
takes to update the buffer (between when window margins are displayed,
and when they are not).

On Fri, 24 Feb 2023 at 21:41, dalanicolai <dalanicolai@gmail.com> wrote:

> I hope you might have an idea what causes this behavior. And maybe you
> have a suggestion how to prevent it. Furthermore, I guess the behavior
> might
> be interesting for you to note/observe (but that is just a guess).
>
> On Fri, 24 Feb 2023 at 21:29, Eli Zaretskii <eliz@gnu.org> wrote:
>
>> > From: dalanicolai <dalanicolai@gmail.com>
>> > Date: Fri, 24 Feb 2023 21:26:05 +0100
>> > Cc: emacs-devel@gnu.org
>> >
>> > I have not really looked at it yet, but just as a quick thought:
>> > I am not sure if/why I should debug an infloop, because the
>> functionality
>> > works perfectly fine when not showing the margins (i.e. when just
>> setting
>> > the window margins to nil). So it seems to me its not about an infinite
>> loop.
>> >
>> > I was saying 'more or less' because it does not really hang, it just
>> takes
>> > extremely long to update the buffer text. When waiting long enough,
>> > then it seems to continue.
>> >
>> > Of course, I don't want to waste your time, but I think my instructions
>> > for reproducing the error, are very clear and short this time (i.e.
>> take less
>> > than/about a minute). I think it would be most informative if you
>> reproduce the
>> > error there.
>>
>> What should I do after I reproduce it, though?  What are your
>> expectations from me (or whoever else tries your recipe)?
>>
>

[-- Attachment #1.2: Type: text/html, Size: 2757 bytes --]

[-- Attachment #2: baleen.el --]
[-- Type: text/x-emacs-lisp, Size: 307154 bytes --]

;;; baleen.el --- Search documents by filtering.     -*- lexical-binding: t; -*-

;; Copyright (C) 2023  Daniel Nicolai

;; Author: Daniel Nicolai <dalanicolai@gmail.com>
;; Keywords: tools

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; 

;;; Code:
(require 'cl-lib)
(require 'page-break-lines nil t)

(defun baleen-render (data)
  (dolist (page data)
    (let* ((props (cdr page))
           (max (1- (length props))))
      (seq-do-indexed (lambda (match i)
                        (let ((o (make-overlay (point)
                                               (progn (progn (insert (nth 4 match))
                                                             (point))))))
                          (overlay-put o
                                       'before-string (propertize " "
                                                                  'display `((margin left-margin)
                                                                             ,(propertize (format " %3d" (car page))
                                                                                          'face 'bold))
                                                                  )))
                        ;; (unless (= i max) (insert "\n")))
                      (insert "\n"))
                      props))
    (insert "\f\n")))

(defun baleen-filter-page (data query)
  (seq-filter (lambda (c)
               (string-match-p query (nth 4 c)))
             (cdr data)))

;; (baleen-filter-page (car test) "eig")

(defun baleen-filter (data query)
  (nreverse
   (seq-reduce (lambda (v p)
                 (if-let (m (baleen-filter-page p query))
                     (cons (cons (car p) m)
                           v)
                   v))
               data
               nil)))

;; (baleen-filter test "q")

(defun baleen-update ()
  (let* ((query (minibuffer-contents))
         (query-length (length query))
         (parent-results (unless (< query-length 2)
                             (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
         (current-results (if parent-results
                              (baleen-filter parent-results query)
                            (unless (string-empty-p query) (baleen-filter test query)))))
    (when current-results
      (with-current-buffer (get-buffer-create "*baleen*")
        (erase-buffer)
        (baleen-render current-results))
      (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))))

(defun baleen ()
  (interactive)
  (pop-to-buffer "*baleen*")
  (set-window-margins nil 4)
  (when (featurep 'page-break-lines)
    (page-break-lines-mode))
  (minibuffer-with-setup-hook
      (lambda ()
        (add-hook 'post-command-hook #'baleen-update nil t))
    (dlet (baleen-results)
      (read-string "Baleen: ")
      (pp baleen-results)))
  (kill-buffer "*baleen*"))

;; NOTE alternatively use doc-pymupdf-text-blocks
(setq test '((1 (1 2 3 4 "hello")
                (2 3 4 5 "hoi"))
             (2 (3 4 2 4 "how do"))))

(defun baleen-update2 ()
  ;; (let ((query (minibuffer-contents)))
  ;;   (with-current-buffer (get-buffer-create "*baleen*")
  ;;     (erase-buffer)
  ;;     (baleen-render (baleen-filter test2 query)))))
  (let* ((query (minibuffer-contents))
         (query-length (length query)))
    (if (> (length previous-query) query-length)
        (with-current-buffer (get-buffer-create "*baleen*")
          (erase-buffer)
          (baleen-render (cdr (alist-get query baleen-results nil nil #'string=))))
      (let* ((parent-results (unless (< query-length 2)
                               (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
             (current-results (if parent-results
                                  (baleen-filter parent-results query)
                                (unless (string-empty-p query) (baleen-filter test2 query)))))
        (when current-results
          (with-current-buffer (get-buffer-create "*baleen*")
            (erase-buffer)
            (baleen-render current-results))
          (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))

        (setq previous-query query)))))

(defun baleen2 ()
  (interactive)
  (pop-to-buffer "*baleen*")
  (buffer-disable-undo)
  (set-window-margins nil 4)
  (when (featurep 'page-break-lines)
    (page-break-lines-mode))
  (minibuffer-with-setup-hook
      (lambda ()
        (add-hook 'post-command-hook #'baleen-update2 nil t))
    (dlet (previous-query
           baleen-results)
      (read-string "Baleen: ")
      (print (length baleen-results))))
  (kill-buffer "*baleen*"))

;; NOTE alternatively use doc-pymupdf-text-blocks
(setq test2
      '((1 (189.0 195.02845764160156 350.99603271484375 212.2610626220703 "An Introduction to
" 0 0) (149.28021240234375 237.02845764160156 390.6446228027344 254.2610626220703 "Programming in Emacs Lisp
" 1 0)) (3 (172.8000030517578 267.5661315917969 367.04559326171875 288.2452697753906 "An Introduction to
" 0 0) (125.160400390625 306.9261169433594 414.5801696777344 327.6052551269531 "Programming in Emacs Lisp
" 1 0) (233.8809051513672 347.60906982421875 305.9354553222656 360.9072570800781 "Second Edition
" 2 0) (218.40089416503906 407.48907470703125 321.4480895996094 420.7872619628906 "by Robert J. Chassell
" 3 0)) (4 (89.999755859375 389.84906005859375 449.3995666503906 415.38726806640625 "Copyright c⃝ 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002 Free
Software Foundation, Inc.
" 0 0) (89.99954223632812 440.00909423828125 321.0759582519531 477.1872863769531 "Published by the Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA
" 1 0) (89.99752807617188 489.8091125488281 449.4958190917969 628.6273803710938 "Edition 2.05, 2001 Jan 5
ISBN 1-882114-43-4
Permission is granted to copy, distribute and/or modify this document under
the terms of the GNU Free Documentation License, Version 1.1 or any later
version published by the Free Software Foundation; there being no Invariant
Section, with the Front-Cover Texts being “A GNU Manual”, and with the
Back-Cover Texts as in (a) below. A copy of the license is included in the
section entitled “GNU Free Documentation License”.
(a) The FSF’s Back-Cover Text is: “You have freedom to copy and modify
this GNU Manual, like GNU software. Copies published by the Free Software
Foundation raise funds for GNU development.”
" 2 0)) (5 (446.760009765625 49.213592529296875 450.0118103027344 61.180747985839844 "i
" 0 0) (90.0 75.14844512939453 219.12728881835938 92.38106536865234 "Short Contents
" 1 0) (89.99615478515625 106.16294860839844 449.7834167480469 510.0864562988281 "Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1
List Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2
Practicing Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3
How To Write Function Definitions . . . . . . . . . . . . . . . . . . 29
4
A Few Buffer–Related Functions . . . . . . . . . . . . . . . . . . . . 51
5
A Few More Complex Functions . . . . . . . . . . . . . . . . . . . . 63
6
Narrowing and Widening . . . . . . . . . . . . . . . . . . . . . . . . . 77
7
car, cdr, cons: Fundamental Functions . . . . . . . . . . . . . 81
8
Cutting and Storing Text. . . . . . . . . . . . . . . . . . . . . . . . . 89
9
How Lists are Implemented. . . . . . . . . . . . . . . . . . . . . . . 113
10
Yanking Text Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
11
Loops and Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
12
Regular Expression Searches . . . . . . . . . . . . . . . . . . . . . . 149
13
Counting: Repetition and Regexps. . . . . . . . . . . . . . . . . . 167
14
Counting Words in a defun. . . . . . . . . . . . . . . . . . . . . . 181
15
Readying a Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
16
Your ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
18
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Appendix A
The the-the Function . . . . . . . . . . . . . . . . . . 241
Appendix B
Handling the Kill Ring . . . . . . . . . . . . . . . . . . . 243
Appendix C
A Graph with Labelled Axes . . . . . . . . . . . . . . . 255
Appendix D
GNU Free Documentation License . . . . . . . . . . . 279
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
" 2 0)) (6 (90.0 49.213592529296875 96.4916763305664 61.180747985839844 "ii
" 0 0)) (7 (440.8800048828125 47.60907745361328 449.89093017578125 60.90726852416992 "iii
" 0 0) (90.0 75.14844512939453 240.67727661132812 92.38106536865234 "Table of Contents
" 1 0) (90.00009155273438 117.08299255371094 449.61639404296875 193.38731384277344 "Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
On Reading this Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
For Whom This is Written. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Lisp History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
A Note for Novices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Thank You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv
" 2 0) (90.000732421875 207.6830291748047 449.66815185546875 535.1473999023438 "1
List Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1
Lisp Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1
Lisp Atoms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2
Whitespace in Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3
GNU Emacs Helps You Type Lists . . . . . . . . . . . . . . . 3
1.2
Run a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3
Generate an Error Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4
Symbol Names and Function Definitions . . . . . . . . . . . . . . . . . . 6
1.5
The Lisp Interpreter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5.1
Byte Compiling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6
Evaluation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6.1
Evaluating Inner Lists . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7.1
Error Message for a Symbol Without a Function. . 11
1.7.2
Error Message for a Symbol Without a Value . . . . 11
1.8
Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8.1
Arguments’ Data Types . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8.2
An Argument as the Value of a Variable or List . . 13
1.8.3
Variable Number of Arguments . . . . . . . . . . . . . . . . . 14
1.8.4
Using the Wrong Type Object as an Argument . . 14
1.8.5
The message Function . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9
Setting the Value of a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9.1
Using set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9.2
Using setq. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.9.3
Counting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.10
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.11
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
" 3 0) (90.00164794921875 549.443115234375 449.662109375 625.7474365234375 "2
Practicing Evaluation . . . . . . . . . . . . . . . . . . . . . 23
2.1
Buffer Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2
Getting Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3
Switching Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4
Buffer Size and the Location of Point . . . . . . . . . . . . . . . . . . . . 27
2.5
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
" 4 0)) (8 (90.0 47.60907745361328 98.74909210205078 60.90726852416992 "iv
" 0 0) (90.0 71.24296569824219 449.7541198730469 314.9472961425781 "3
How To Write Function Definitions . . . . . . . . 29
3.1
The defun Special Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2
Install a Function Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1
Change a Function Definition. . . . . . . . . . . . . . . . . . . 32
3.3
Make a Function Interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.1
An Interactive multiply-by-seven .. . . . . . . . . . . . 34
3.4
Different Options for interactive . . . . . . . . . . . . . . . . . . . . . . 35
3.5
Install Code Permanently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6
let . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6.1
The Parts of a let Expression . . . . . . . . . . . . . . . . . . 37
3.6.2
Sample let Expression. . . . . . . . . . . . . . . . . . . . . . . . . 38
3.6.3
Uninitialized Variables in a let Statement. . . . . . . 39
3.7
The if Special Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7.1
The type-of-animal Function in Detail. . . . . . . . . 41
3.8
If–then–else Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.9
Truth and Falsehood in Emacs Lisp . . . . . . . . . . . . . . . . . . . . . 43
3.10
save-excursion .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.10.1
Template for a save-excursion Expression . . . . 45
3.11
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.12
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
" 1 0) (90.00115966796875 329.24298095703125 449.7353210449219 465.30731201171875 "4
A Few Buffer–Related Functions. . . . . . . . . . . 51
4.1
Finding More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.2
A Simplified beginning-of-buffer Definition. . . . . . . . . . . . 52
4.3
The Definition of mark-whole-buffer . . . . . . . . . . . . . . . . . . . 54
4.3.1
Body of mark-whole-buffer .. . . . . . . . . . . . . . . . . . 55
4.4
The Definition of append-to-buffer . . . . . . . . . . . . . . . . . . . . 56
4.4.1
The append-to-buffer Interactive Expression. . . 57
4.4.2
The Body of append-to-buffer .. . . . . . . . . . . . . . . 57
4.4.3
save-excursion in append-to-buffer.. . . . . . . . . 58
4.5
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.6
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
" 2 0)) (9 (444.239990234375 47.60907745361328 450.0 60.90726852416992 "v
" 0 0) (90.0 71.24296569824219 449.7479553222656 291.0672912597656 "5
A Few More Complex Functions . . . . . . . . . . . 63
5.1
The Definition of copy-to-buffer.. . . . . . . . . . . . . . . . . . . . . . 63
5.2
The Definition of insert-buffer.. . . . . . . . . . . . . . . . . . . . . . . 64
5.2.1
The Interactive Expression in insert-buffer.. . . 65
A Read-only Buffer. . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
‘b’ in an Interactive Expression. . . . . . . . . . . . . . . . . 65
5.2.2
The Body of the insert-buffer Function . . . . . . . 65
5.2.3
insert-buffer With an if Instead of an or. . . . . 66
5.2.4
The or in the Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.2.5
The let Expression in insert-buffer .. . . . . . . . . 68
5.3
Complete Definition of beginning-of-buffer .. . . . . . . . . . . 69
5.3.1
Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.3.2
beginning-of-buffer with an Argument . . . . . . . 71
What happens in a large buffer. . . . . . . . . . . . . . . . . 71
What happens in a small buffer . . . . . . . . . . . . . . . . 72
5.3.3
The Complete beginning-of-buffer .. . . . . . . . . . 73
5.4
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.5
optional Argument Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
" 1 0) (89.99783325195312 305.3630065917969 449.7347106933594 357.7873229980469 "6
Narrowing and Widening. . . . . . . . . . . . . . . . . . 77
6.1
The save-restriction Special Form . . . . . . . . . . . . . . . . . . . . 77
6.2
what-line.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.3
Exercise with Narrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
" 2 0) (89.9976806640625 372.0830078125 449.7032775878906 484.267333984375 "7
car, cdr, cons: Fundamental Functions . . . . . 81
7.1
car and cdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.2
cons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2.1
Find the Length of a List: length . . . . . . . . . . . . . . 84
7.3
nthcdr .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.4
nth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.5
setcar .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.6
setcdr .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.7
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
" 3 0)) (10 (90.0 47.60907745361328 98.78182220458984 60.90726852416992 "vi
" 0 0) (90.0 71.24296569824219 449.7066650390625 302.9472961425781 "8
Cutting and Storing Text . . . . . . . . . . . . . . . . . 89
8.1
zap-to-char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.1.1
The interactive Expression . . . . . . . . . . . . . . . . . . . 90
8.1.2
The Body of zap-to-char.. . . . . . . . . . . . . . . . . . . . . 91
8.1.3
The search-forward Function . . . . . . . . . . . . . . . . . 92
8.1.4
The progn Special Form . . . . . . . . . . . . . . . . . . . . . . . 93
8.1.5
Summing up zap-to-char . . . . . . . . . . . . . . . . . . . . . 93
8.2
kill-region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.2.1
condition-case.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.2.2
delete-and-extract-region . . . . . . . . . . . . . . . . . . 96
8.3
delete-and-extract-region: Digressing into C . . . . . . . . . 98
8.4
Initializing a Variable with defvar . . . . . . . . . . . . . . . . . . . . . 100
8.4.1
defvar and an asterisk. . . . . . . . . . . . . . . . . . . . . . . . 101
8.5
copy-region-as-kill.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.5.1
The Body of copy-region-as-kill.. . . . . . . . . . . 103
The kill-append function. . . . . . . . . . . . . . . . . . . . 104
The kill-new function . . . . . . . . . . . . . . . . . . . . . . . 105
8.6
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.7
Searching Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
" 1 0) (90.00201416015625 317.3630065917969 449.6243896484375 357.7873229980469 "9
How Lists are Implemented . . . . . . . . . . . . . . 113
9.1
Symbols as a Chest of Drawers . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.2
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
" 2 0) (90.00247192382812 372.0830078125 449.5589599609375 424.50732421875 "10
Yanking Text Back . . . . . . . . . . . . . . . . . . . . . 117
10.1
Kill Ring Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.2
The kill-ring-yank-pointer Variable . . . . . . . . . . . . . . . 117
10.3
Exercises with yank and nthcdr. . . . . . . . . . . . . . . . . . . . . . . 119
" 3 0) (90.00210571289062 438.9230041503906 449.5998229980469 622.7473754882812 "11
Loops and Recursion. . . . . . . . . . . . . . . . . . . . 121
11.1
while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
11.1.1
A while Loop and a List. . . . . . . . . . . . . . . . . . . . . 122
11.1.2
An Example: print-elements-of-list . . . . . . 123
11.1.3
A Loop with an Incrementing Counter . . . . . . . . 124
Example with incrementing counter . . . . . . . . . . . 125
The parts of the function definition. . . . . . . . . . . . 126
Putting the function definition together . . . . . . . . 127
11.1.4
Loop with a Decrementing Counter . . . . . . . . . . . 129
Example with decrementing counter . . . . . . . . . . . 129
The parts of the function definition. . . . . . . . . . . . 130
Putting the function definition together . . . . . . . . 130
11.2
Save your time: dolist and dotimes . . . . . . . . . . . . . . . . . . 131
The dolist Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
The dotimes Macro . . . . . . . . . . . . . . . . . . . . . . . . . . 133
" 4 0)) (11 (438.239990234375 47.60907745361328 450.0108947753906 60.90726852416992 "vii
" 0 0) (125.8800048828125 71.48908233642578 449.4754333496094 240.1873016357422 "11.3
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
11.3.1
Building Robots: Extending the Metaphor. . . . . 134
11.3.2
The Parts of a Recursive Definition . . . . . . . . . . . 135
11.3.3
Recursion with a List . . . . . . . . . . . . . . . . . . . . . . . . 136
11.3.4
Recursion in Place of a Counter . . . . . . . . . . . . . . 137
An argument of 3 or 4. . . . . . . . . . . . . . . . . . . . . . . . 138
11.3.5
Recursion Example Using cond . . . . . . . . . . . . . . . 139
11.3.6
Recursive Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Recursive Pattern: every . . . . . . . . . . . . . . . . . . . . . 141
Recursive Pattern: accumulate . . . . . . . . . . . . . . . . 142
Recursive Pattern: keep . . . . . . . . . . . . . . . . . . . . . . 143
11.3.7
Recursion without Deferments . . . . . . . . . . . . . . . . 143
11.3.8
No Deferment Solution. . . . . . . . . . . . . . . . . . . . . . . 145
11.4
Looping Exercise. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
" 1 0) (90.00149536132812 254.60301208496094 449.6435241699219 462.4273376464844 "12
Regular Expression Searches . . . . . . . . . . . . 149
12.1
The Regular Expression for sentence-end .. . . . . . . . . . . . 149
12.2
The re-search-forward Function. . . . . . . . . . . . . . . . . . . . . 150
12.3
forward-sentence .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
The while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
The regular expression search . . . . . . . . . . . . . . . . . . . . . . . . 154
12.4
forward-paragraph: a Goldmine of Functions . . . . . . . . . 155
The let* expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
The forward motion while loop . . . . . . . . . . . . . . . . . . . . . . 158
Between paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Within paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
No fill prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
With a fill prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Summary.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12.5
Create Your Own ‘TAGS’ File. . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.6
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.7
Exercises with re-search-forward.. . . . . . . . . . . . . . . . . . . 166
" 2 0) (90.00076293945312 476.7230224609375 449.64251708984375 541.02734375 "13
Counting: Repetition and Regexps . . . . . . 167
13.1
The count-words-region Function . . . . . . . . . . . . . . . . . . . 167
13.1.1
The Whitespace Bug in count-words-region.. 170
13.2
Count Words Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
13.3
Exercise: Counting Punctuation . . . . . . . . . . . . . . . . . . . . . . . 179
" 3 0)) (12 (90.0 47.60907745361328 104.76000213623047 60.90726852416992 "viii
" 0 0) (90.0 71.24296569824219 449.6117858886719 243.1873016357422 "14
Counting Words in a defun . . . . . . . . . . . . . . 181
14.1
What to Count? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.2
What Constitutes a Word or Symbol? . . . . . . . . . . . . . . . . . 182
14.3
The count-words-in-defun Function . . . . . . . . . . . . . . . . . 183
14.4
Count Several defuns Within a File . . . . . . . . . . . . . . . . . . . 186
14.5
Find a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
14.6
lengths-list-file in Detail . . . . . . . . . . . . . . . . . . . . . . . . . 188
14.7
Count Words in defuns in Different Files . . . . . . . . . . . . . . 190
14.7.1
The append Function . . . . . . . . . . . . . . . . . . . . . . . . 191
14.8
Recursively Count Words in Different Files. . . . . . . . . . . . . 192
14.9
Prepare the Data for Display in a Graph . . . . . . . . . . . . . . . 193
14.9.1
Sorting Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
14.9.2
Making a List of Files. . . . . . . . . . . . . . . . . . . . . . . . 194
14.9.3
Counting function definitions . . . . . . . . . . . . . . . . . 197
" 1 0) (89.99942016601562 257.6029968261719 449.582275390625 321.9073181152344 "15
Readying a Graph . . . . . . . . . . . . . . . . . . . . . . 203
15.1
The graph-body-print Function. . . . . . . . . . . . . . . . . . . . . . 208
15.2
The recursive-graph-body-print Function. . . . . . . . . . . 210
15.3
Need for Printed Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
15.4
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
" 2 0) (89.99984741210938 336.2030029296875 449.5562744140625 520.1473388671875 "16
Your ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . 213
16.1
Site-wide Initialization Files. . . . . . . . . . . . . . . . . . . . . . . . . . . 213
16.2
Specifying Variables using defcustom.. . . . . . . . . . . . . . . . . 214
16.3
Beginning a ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
16.4
Text and Auto Fill Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
16.5
Mail Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.6
Indent Tabs Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.7
Some Keybindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
16.8
Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
16.9
Loading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
16.10
Autoloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
16.11
A Simple Extension: line-to-top-of-window . . . . . . . . 224
16.12
X11 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
16.13
Miscellaneous Settings for a ‘.emacs’ File . . . . . . . . . . . . . 227
16.14
A Modified Mode Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
" 3 0) (90.00198364257812 534.5630493164062 449.5606689453125 610.8673706054688 "17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
17.1
debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
17.2
debug-on-entry .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
17.3
debug-on-quit and (debug).. . . . . . . . . . . . . . . . . . . . . . . . . 234
17.4
The edebug Source Level Debugger. . . . . . . . . . . . . . . . . . . . 235
17.5
Debugging Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
" 4 0)) (13 (441.239990234375 47.60907745361328 449.9891052246094 60.90726852416992 "ix
" 0 0) (90.0 71.24296569824219 449.5467834472656 85.66089630126953 "18
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
" 1 0) (90.0001220703125 102.08299255371094 449.6182556152344 116.51359558105469 "Appendix A
The the-the Function. . . . . . . . . . 241
" 2 0) (89.99960327148438 133.0430145263672 449.6458740234375 269.1073303222656 "Appendix B
Handling the Kill Ring . . . . . . . . 243
B.1
The rotate-yank-pointer Function . . . . . . . . . . . . . . . . . . . 243
B.1.1
The Body of rotate-yank-pointer .. . . . . . . . . . 244
The else-part of the if expression . . . . . . . . . . . . . 245
The % remainder function . . . . . . . . . . . . . . . . . . . . . 247
Using % in rotate-yank-pointer . . . . . . . . . . . . . 248
Pointing to the last element. . . . . . . . . . . . . . . . . . . 248
B.2
yank.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Passing the argument . . . . . . . . . . . . . . . . . . . . . . . . 250
Passing a negative argument . . . . . . . . . . . . . . . . . . 251
B.3
yank-pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
" 3 0) (90.0001220703125 283.4030456542969 449.68988037109375 479.3473815917969 "Appendix C
A Graph with Labelled Axes. . . 255
C.1
The print-graph Varlist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
C.2
The print-Y-axis Function. . . . . . . . . . . . . . . . . . . . . . . . . . . 256
C.2.1
Side Trip: Compute a Remainder. . . . . . . . . . . . . . 258
C.2.2
Construct a Y Axis Element . . . . . . . . . . . . . . . . . . 259
C.2.3
Create a Y Axis Column. . . . . . . . . . . . . . . . . . . . . . 261
C.2.4
The Not Quite Final Version of print-Y-axis.. 262
C.3
The print-X-axis Function. . . . . . . . . . . . . . . . . . . . . . . . . . . 263
C.3.1
X Axis Tic Marks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
C.4
Printing the Whole Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
C.4.1
Testing print-graph .. . . . . . . . . . . . . . . . . . . . . . . . 270
C.4.2
Graphing Numbers of Words and Symbols . . . . . 271
C.4.3
A lambda Expression: Useful Anonymity. . . . . . . 272
C.4.4
The mapcar Function. . . . . . . . . . . . . . . . . . . . . . . . . 274
C.4.5
Another Bug . . . Most Insidious . . . . . . . . . . . . . . 274
C.4.6
The Printed Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . 277
" 4 0) (89.99880981445312 493.7004699707031 449.52435302734375 524.02099609375 "Appendix D
GNU Free Documentation License
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
" 5 0) (89.99868774414062 540.443115234375 449.5042724609375 554.8610229492188 "Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
" 6 0)) (14 (90.0 47.60907745361328 95.76000213623047 60.90726852416992 "x
" 0 0)) (15 (90.0 47.60907745361328 449.83599853515625 60.90726852416992 "On Reading this Text
xi
" 0 0) (90.00021362304688 75.14844512939453 152.6470489501953 92.38106536865234 "Preface
" 1 0) (89.999267578125 102.08905792236328 449.4326477050781 360.4271545410156 "Most of the GNU Emacs integrated environment is written in the pro-
gramming language called Emacs Lisp. The code written in this program-
ming language is the software—the sets of instructions—that tell the com-
puter what to do when you give it commands. Emacs is designed so that
you can write new code in Emacs Lisp and easily install it as an extension
to the editor.
(GNU Emacs is sometimes called an “extensible editor”, but it does much
more than provide editing capabilities.
It is better to refer to Emacs as
an “extensible computing environment”. However, that phrase is quite a
mouthful.
It is easier to refer to Emacs simply as an editor.
Moreover,
everything you do in Emacs—find the Mayan date and phases of the moon,
simplify polynomials, debug code, manage files, read letters, write books—all
these activities are kinds of editing in the most general sense of the word.)
Although Emacs Lisp is usually thought of in association only with
Emacs, it is a full computer programming language. You can use Emacs
Lisp as you would any other programming language.
Perhaps you want to understand programming; perhaps you want to ex-
tend Emacs; or perhaps you want to become a programmer. This introduc-
tion to Emacs Lisp is designed to get you started: to guide you in learning
the fundamentals of programming, and more importantly, to show you how
you can teach yourself to go further.
" 2 0) (90.00047302246094 376.2202453613281 243.05418395996094 390.5807800292969 "On Reading this Text
" 3 0) (89.99932861328125 398.24896240234375 449.6614685058594 630.7872314453125 "All through this document, you will see little sample programs you can
run inside of Emacs.
If you read this document in Info inside of GNU
Emacs, you can run the programs as they appear. (This is easy to do and
is explained when the examples are presented.) Alternatively, you can read
this introduction as a printed book while sitting beside a computer running
Emacs. (This is what I like to do; I like printed books.) If you don’t have a
running Emacs beside you, you can still read this book, but in this case, it
is best to treat it as a novel or as a travel guide to a country not yet visited:
interesting, but not the same as being there.
Much of this introduction is dedicated to walk-throughs or guided tours
of code used in GNU Emacs. These tours are designed for two purposes:
first, to give you familiarity with real, working code (code you use every
day); and, second, to give you familiarity with the way Emacs works. It is
interesting to see how a working environment is implemented. Also, I hope
that you will pick up the habit of browsing through source code. You can
learn from it and mine it for ideas. Having GNU Emacs is like having a
dragon’s cave of treasures.
In addition to learning about Emacs as an editor and Emacs Lisp as
a programming language, the examples and guided tours will give you an
" 4 0)) (16 (90.0 47.60907745361328 449.8251953125 60.90726852416992 "xii
Preface
" 0 0) (89.99826049804688 77.48908233642578 449.3992919921875 201.1873016357422 "opportunity to get acquainted with Emacs as a Lisp programming environ-
ment. GNU Emacs supports programming and provides tools that you will
want to become comfortable using, such as M-. (the key which invokes the
find-tag command). You will also learn about buffers and other objects
that are part of the environment. Learning about these features of Emacs is
like learning new routes around your home town.
Finally, I hope to convey some of the skills for using Emacs to learn
aspects of programming that you don’t know. You can often use Emacs to
help you understand what puzzles you or to find out how to do something
new. This self-reliance is not only a pleasure, but an advantage.
" 1 0) (89.99856567382812 221.06036376953125 279.07073974609375 235.4208984375 "For Whom This is Written
" 2 0) (89.99630737304688 244.049072265625 449.50616455078125 630.7874755859375 "This text is written as an elementary introduction for people who are not
programmers. If you are a programmer, you may not be satisfied with this
primer. The reason is that you may have become expert at reading reference
manuals and be put off by the way this text is organized.
An expert programmer who reviewed this text said to me:
I prefer to learn from reference manuals. I “dive into” each para-
graph, and “come up for air” between paragraphs.
When I get to the end of a paragraph, I assume that that subject
is done, finished, that I know everything I need (with the possible
exception of the case when the next paragraph starts talking about
it in more detail). I expect that a well written reference manual
will not have a lot of redundancy, and that it will have excellent
pointers to the (one) place where the information I want is.
This introduction is not written for this person!
Firstly, I try to say everything at least three times: first, to introduce it;
second, to show it in context; and third, to show it in a different context, or
to review it.
Secondly, I hardly ever put all the information about a subject in one
place, much less in one paragraph. To my way of thinking, that imposes
too heavy a burden on the reader. Instead I try to explain only what you
need to know at the time. (Sometimes I include a little extra information
so you won’t be surprised later when the additional information is formally
introduced.)
When you read this text, you are not expected to learn everything the first
time. Frequently, you need only make, as it were, a ‘nodding acquaintance’
with some of the items mentioned. My hope is that I have structured the
text and given you enough hints that you will be alert to what is important,
and concentrate on it.
You will need to “dive into” some paragraphs; there is no other way to
read them. But I have tried to keep down the number of such paragraphs.
" 3 0)) (17 (90.0 47.60907745361328 449.7156982421875 60.90726852416992 "A Note for Novices
xiii
" 0 0) (89.99826049804688 77.48908233642578 449.42022705078125 188.34727478027344 "This book is intended as an approachable hill, rather than as a daunting
mountain.
This introduction to Programming in Emacs Lisp has a companion doc-
ument, The GNU Emacs Lisp Reference Manual. The reference manual has
more detail than this introduction. In the reference manual, all the infor-
mation about one topic is concentrated in one place. You should turn to it
if you are like the programmer quoted above. And, of course, after you have
read this Introduction, you will find the Reference Manual useful when you
are writing your own programs.
" 1 0) (89.99887084960938 204.8603515625 177.66000366210938 219.22088623046875 "Lisp History
" 2 0) (89.999267578125 226.88909912109375 449.4208068847656 337.8672790527344 "Lisp was first developed in the late 1950s at the Massachusetts Institute
of Technology for research in artificial intelligence. The great power of the
Lisp language makes it superior for other purposes as well, such as writing
editor commands and integrated environments.
GNU Emacs Lisp is largely inspired by Maclisp, which was written at
MIT in the 1960s. It is somewhat inspired by Common Lisp, which became
a standard in the 1980s. However, Emacs Lisp is much simpler than Common
Lisp. (The standard Emacs distribution contains an optional extensions file,
‘cl.el’, that adds many Common Lisp features to Emacs Lisp.)
" 3 0) (89.99957275390625 354.2603759765625 226.11309814453125 368.62091064453125 "A Note for Novices
" 4 0) (89.99993896484375 376.4090881347656 449.44329833984375 443.3298034667969 "If you don’t know GNU Emacs, you can still read this document prof-
itably. However, I recommend you learn Emacs, if only to learn to move
around your computer screen. You can teach yourself how to use Emacs
with the on-line tutorial. To use it, type C-h t. (This means you press and
release the ⟨
" 5 0) (145.54800415039062 427.552001953125 169.30799865722656 428.0320129394531 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (145.55999755859375 428.7624206542969 169.3109130859375 436.7325134277344 "CTRL
" 7 0) (145.54800415039062 436.1919860839844 169.30799865722656 436.6719970703125 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99853515625 423.80908203125 449.4320983886719 541.0098266601562 "⟩ key and the h at the same time, and then press and release
t.)
Also, I often refer to one of Emacs’ standard commands by listing the
keys which you press to invoke the command and then giving the name of
the command in parentheses, like this: M-C-\\ (indent-region). What this
means is that the indent-region command is customarily invoked by typing
M-C-\\. (You can, if you wish, change the keys that are typed to invoke the
command; this is called rebinding. See Section 16.8, “Keymaps”, page 221.)
The abbreviation M-C-\\ means that you type your ⟨
" 9 0) (344.26800537109375 525.2319946289062 369.5880126953125 525.7119750976562 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (344.2799987792969 526.4424438476562 369.5664978027344 534.41259765625 "META
" 11 0) (344.26800537109375 533.751953125 369.5880126953125 534.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (369.0 521.4890747070312 403.426513671875 541.0098266601562 "⟩ key, ⟨
" 13 0) (402.7080078125 525.2319946289062 426.468017578125 525.7119750976562 "<image: None, width: 1, height: 1, bpc: 1>" 14 1) (402.7200012207031 526.4424438476562 426.4709167480469 534.41259765625 "CTRL
" 15 0) (402.7080078125 533.751953125 426.468017578125 534.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 16 1) (90.00009155273438 521.4890747070312 449.8581848144531 552.8898315429688 "⟩ key
and ⟨
" 17 0) (114.58800506591797 536.751953125 120.34800720214844 537.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 18 1) (114.5999984741211 535.5726928710938 120.32727813720703 546.8636474609375 "\\
" 19 0) (114.58800506591797 545.751953125 120.34800720214844 546.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 20 1) (119.76000213623047 533.3690795898438 422.3863830566406 552.8897705078125 "⟩ key all at the same time. (On many modern keyboards the ⟨
" 21 0) (421.66802978515625 537.1119995117188 446.988037109375 537.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 22 1) (421.67999267578125 538.3223876953125 446.9664001464844 546.2925415039062 "META
" 23 0) (421.66802978515625 545.751953125 446.988037109375 546.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 24 1) (90.0 536.97314453125 449.9865417480469 564.8897705078125 "⟩
key is labelled ⟨
" 25 0) (161.26800537109375 549.1119995117188 178.42800903320312 549.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 26 1) (161.27999877929688 550.3223876953125 178.3014678955078 558.2925415039062 "ALT
" 27 0) (161.26800537109375 557.6319580078125 178.42800903320312 558.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 28 1) (89.99942016601562 545.7290649414062 449.3890380859375 588.769775390625 "⟩.) Sometimes a combination like this is called a keychord,
since it is similar to the way you play a chord on a piano. If your keyboard
does not have a ⟨
" 29 0) (174.58799743652344 572.991943359375 199.90798950195312 573.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 30 1) (174.60000610351562 574.202392578125 199.8865203857422 582.1725463867188 "META
" 31 0) (174.58799743652344 581.6319580078125 199.90798950195312 582.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 32 1) (199.32000732421875 569.2490844726562 253.54656982421875 588.7698364257812 "⟩ key, the ⟨
" 33 0) (252.8280029296875 572.991943359375 269.50799560546875 573.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 34 1) (252.83999633789062 574.202392578125 269.3859558105469 582.1725463867188 "ESC
" 35 0) (252.8280029296875 581.6319580078125 269.50799560546875 582.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 36 1) (90.00003051757812 569.2490844726562 449.7705993652344 600.7698364257812 "⟩ key prefix is used in place of it. In
this case, M-C-\\ means that you press and release your ⟨
" 37 0) (363.3479919433594 584.991943359375 380.0279846191406 585.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 38 1) (363.3599853515625 586.202392578125 379.90594482421875 594.1725463867188 "ESC
" 39 0) (363.3479919433594 593.5120239257812 380.0279846191406 593.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 40 1) (90.00039672851562 581.2490844726562 449.8471374511719 612.7698364257812 "⟩ key and then
type the ⟨
" 41 0) (137.7480010986328 596.9920043945312 161.50799560546875 597.4719848632812 "<image: None, width: 1, height: 1, bpc: 1>" 42 1) (137.75999450683594 598.202392578125 161.5109100341797 606.1725463867188 "CTRL
" 43 0) (137.7480010986328 605.5120239257812 161.50799560546875 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 44 1) (161.0399932861328 593.2490844726562 234.58642578125 612.7698364257812 "⟩ key and the ⟨
" 45 0) (233.9879913330078 596.5120239257812 239.74798583984375 596.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 46 1) (234.0 595.4526977539062 239.72727966308594 606.74365234375 "\\
" 47 0) (233.9879913330078 605.5120239257812 239.74798583984375 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 48 1) (90.00027465820312 593.2490844726562 449.7488708496094 624.6498413085938 "⟩ key at the same time. But usually M-C-\\
means press the ⟨
" 49 0) (172.42800903320312 608.8720092773438 196.18800354003906 609.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 50 1) (172.44000244140625 610.0823974609375 196.19091796875 618.0525512695312 "CTRL
" 51 0) (172.42800903320312 617.5120239257812 196.18800354003906 617.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 52 1) (195.60000610351562 605.1290893554688 393.1064147949219 624.6497802734375 "⟩ key along with the key that is labelled ⟨
" 53 0) (392.38800048828125 608.8720092773438 409.5480041503906 609.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 54 1) (392.3999938964844 610.0823974609375 409.42144775390625 618.0525512695312 "ALT
" 55 0) (392.38800048828125 617.5120239257812 409.5480041503906 617.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 56 1) (90.00039672851562 605.1290893554688 449.869140625 636.6497802734375 "⟩ and, at
the same time, press the ⟨
" 57 0) (213.10801696777344 620.3919677734375 218.86801147460938 620.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 58 1) (213.1199951171875 619.3327026367188 218.84727478027344 630.6236572265625 "\\
" 59 0) (213.10801696777344 629.3919677734375 218.86801147460938 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 60 1) (218.27999877929688 617.1290893554688 243.59999084472656 636.289794921875 "⟩ key.
" 61 0)) (18 (90.0 47.60907745361328 449.8251953125 60.90726852416992 "xiv
Preface
" 0 0) (89.9986572265625 77.48908233642578 449.4637756347656 194.2097930908203 "In addition to typing a lone keychord, you can prefix what you type with
C-u, which is called the ‘universal argument’. The C-u keychord passes an
argument to the subsequent command. Thus, to indent a region of plain
text by 6 spaces, mark the region, and then type C-u 6 M-C-\\. (If you do
not specify a number, Emacs either passes the number 4 to the command
or otherwise runs the command differently than it would otherwise.) See
section “Numeric Arguments” in The GNU Emacs Manual.
If you are reading this in Info using GNU Emacs, you can read through
this whole document just by pressing the space bar, ⟨
" 1 0) (346.3080139160156 178.43194580078125 362.9880065917969 178.9119415283203 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (346.32000732421875 179.6424102783203 362.865966796875 187.61251831054688 "SPC
" 3 0) (346.3080139160156 187.072021484375 362.9880065917969 187.55201721191406 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (89.9993896484375 175.049072265625 449.90179443359375 238.2672576904297 "⟩. (To learn about
Info, type C-h i and then select Info.)
A note on terminology: when I use the word Lisp alone, I often am
referring to the various dialects of Lisp in general, but when I speak of
Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
" 5 0) (89.99943542480469 254.66033935546875 168.7605743408203 269.0208740234375 "Thank You
" 6 0) (89.99978637695312 276.6890869140625 449.869384765625 352.26727294921875 "My thanks to all who helped me with this book. My especial thanks to
Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
Randy Smith, Richard M. Stallman, and Melissa Weisshaus.
My thanks
also go to both Philip Johnson and David Stampe for their patient encour-
agement. My mistakes are my own.
Robert J. Chassell
" 7 0)) (19 (90.0 47.60907745361328 449.9559631347656 60.90726852416992 "Lisp Atoms
1
" 0 0) (89.9993896484375 75.14844512939453 237.94793701171875 92.38106536865234 "1 List Processing
" 1 0) (89.9981689453125 104.12909698486328 449.4855041503906 189.1873016357422 "To the untutored eye, Lisp is a strange programming language. In Lisp
code there are parentheses everywhere. Some people even claim that the
name stands for ‘Lots of Isolated Silly Parentheses’. But the claim is un-
warranted. Lisp stands for LISt Processing, and the programming language
handles lists (and lists of lists) by putting them between parentheses. The
parentheses mark the boundaries of the list. Sometimes a list is preceded by
a single apostrophe or quotation mark, ‘’’. Lists are the basis of Lisp.
" 2 0) (89.99810791015625 206.18035888671875 186.65130615234375 220.5408935546875 "1.1 Lisp Lists
" 3 0) (89.997314453125 228.4490966796875 449.47412109375 277.6272888183594 "In Lisp, a list looks like this: ’(rose violet daisy buttercup). This
list is preceded by a single apostrophe. It could just as well be written as
follows, which looks more like the kind of list you are likely to be familiar
with:
" 4 0) (89.99658203125 282.6976623535156 449.4080810546875 481.8672790527344 "’(rose
violet
daisy
buttercup)
The elements of this list are the names of the four different flowers, separated
from each other by whitespace and surrounded by parentheses, like flowers
in a field with a stone wall around them.
Lists can also have numbers in them, as in this list: (+ 2 2). This list
has a plus-sign, ‘+’, followed by two ‘2’s, each separated by whitespace.
In Lisp, both data and programs are represented the same way; that is,
they are both lists of words, numbers, or other lists, separated by white-
space and surrounded by parentheses. (Since a program looks like data, one
program may easily serve as data for another; this is a very powerful feature
of Lisp.) (Incidentally, these two parenthetical remarks are not Lisp lists,
because they contain ‘;’ and ‘.’ as punctuation marks.)
Here is another list, this time with a list inside of it:
" 5 0) (89.99627685546875 487.0576477050781 449.39642333984375 534.54736328125 "’(this list has (a list inside of it))
The components of this list are the words ‘this’, ‘list’, ‘has’, and the
list ‘(a list inside of it)’. The interior list is made up of the words ‘a’,
‘list’, ‘inside’, ‘of’, ‘it’.
" 6 0) (89.99640655517578 548.2818603515625 201.3193817138672 561.3858642578125 "1.1.1 Lisp Atoms
" 7 0) (89.99514770507812 569.609130859375 449.3634948730469 630.787353515625 "In Lisp, what we have been calling words are called atoms. This term
comes from the historical meaning of the word atom, which means ‘indivis-
ible’. As far as Lisp is concerned, the words we have been using in the lists
cannot be divided into any smaller parts and still mean the same thing as
part of a program; likewise with numbers and single character symbols like
" 8 0)) (20 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "2
Chapter 1: List Processing
" 0 0) (90.00003051757812 77.48908233642578 449.2689514160156 102.66727447509766 "‘+’. On the other hand, unlike an atom, a list can be split into parts. (See
Chapter 7, “car cdr & cons Fundamental Functions”, page 81.)
" 1 0) (89.99966430664062 117.68909454345703 449.32330322265625 142.86729431152344 "In a list, atoms are separated from each other by whitespace. They can
be right next to a parenthesis.
" 2 0) (89.9991455078125 157.88909912109375 449.6281433105469 230.9473114013672 "Technically speaking, a list in Lisp consists of parentheses surrounding
atoms separated by whitespace or surrounding other lists or surrounding
both atoms and other lists.
A list can have just one atom in it or have
nothing in it at all. A list with nothing in it looks like this: (), and is called
the empty list. Unlike anything else, an empty list is considered both an
atom and a list at the same time.
" 3 0) (89.99899291992188 245.84912109375 449.39892578125 318.9073181152344 "The printed representation of both atoms and lists are called symbolic
expressions or, more concisely, s-expressions. The word expression by itself
can refer to either the printed representation, or to the atom or list as it
is held internally in the computer. Often, people use the term expression
indiscriminately. (Also, in many texts, the word form is used as a synonym
for expression.)
" 4 0) (89.99847412109375 333.80914306640625 449.4320373535156 430.8673400878906 "Incidentally, the atoms that make up our universe were named such when
they were thought to be indivisible; but it has been found that physical atoms
are not indivisible. Parts can split off an atom or it can fission into two parts
of roughly equal size. Physical atoms were named prematurely, before their
truer nature was found. In Lisp, certain kinds of atom, such as an array, can
be separated into parts; but the mechanism for doing this is different from
the mechanism for splitting a list. As far as list operations are concerned,
the atoms of a list are unsplittable.
" 5 0) (89.99725341796875 445.7691650390625 449.41961669921875 494.9473571777344 "As in English, the meanings of the component letters of a Lisp atom are
different from the meaning the letters make as a word. For example, the
word for the South American sloth, the ‘ai’, is completely different from the
two words, ‘a’, and ‘i’.
" 6 0) (89.99642944335938 509.84918212890625 449.41912841796875 630.7874145507812 "There are many kinds of atom in nature but only a few in Lisp: for
example, numbers, such as 37, 511, or 1729, and symbols, such as ‘+’, ‘foo’,
or ‘forward-line’. The words we have listed in the examples above are
all symbols. In everyday Lisp conversation, the word “atom” is not often
used, because programmers usually try to be more specific about what kind
of atom they are dealing with. Lisp programming is mostly about symbols
(and sometimes numbers) within lists.
(Incidentally, the preceding three
word parenthetical remark is a proper list in Lisp, since it consists of atoms,
which in this case are symbols, separated by whitespace and enclosed by
parentheses, without any non-Lisp punctuation.)
" 7 0)) (21 (90.0 47.60907745361328 449.78131103515625 60.90726852416992 "GNU Emacs Helps You Type Lists
3
" 0 0) (89.99951171875 79.64905548095703 449.333984375 104.9472427368164 "In addition, text between double quotation marks—even sentences or
paragraphs—is an atom. Here is an example:
" 1 0) (89.998046875 110.13748168945312 449.41973876953125 181.5071258544922 "’(this list includes \"text between quotation marks.\")
In Lisp, all of the quoted text including the punctuation mark and the blank
spaces is a single atom. This kind of atom is called a string (for ‘string
of characters’) and is the sort of thing that is used for messages that a
computer can print for a human to read. Strings are a different kind of atom
than numbers or symbols and are used differently.
" 2 0) (89.99826049804688 195.24169921875 254.18441772460938 208.34568786621094 "1.1.2 Whitespace in Lists
" 3 0) (89.99853515625 216.68896484375 449.3758239746094 241.86717224121094 "The amount of whitespace in a list does not matter. From the point of
view of the Lisp language,
" 4 0) (89.9984359741211 247.05752563476562 218.55104064941406 284.2271423339844 "’(this list
looks like this)
is exactly the same as this:
" 5 0) (89.99649047851562 289.4173889160156 449.4737854003906 460.7470397949219 "’(this list looks like this)
Both examples show what to Lisp is the same list, the list made up of
the symbols ‘this’, ‘list’, ‘looks’, ‘like’, and ‘this’ in that order.
Extra whitespace and newlines are designed to make a list more readable
by humans. When Lisp reads the expression, it gets rid of all the extra
whitespace (but it needs to have at least one space between atoms in order
to tell them apart.)
Odd as it seems, the examples we have seen cover almost all of what
Lisp lists look like! Every other list in Lisp looks more or less like one of
these examples, except that the list may be longer and more complex. In
brief, a list is between parentheses, a string is between quotation marks, a
symbol looks like a word, and a number looks like a number. (For certain
situations, square brackets, dots and a few other special characters may be
used; however, we will go quite far without them.)
" 6 0) (89.99827575683594 474.4815979003906 352.74591064453125 487.5856018066406 "1.1.3 GNU Emacs Helps You Type Lists
" 7 0) (89.99734497070312 495.808837890625 449.5176086425781 550.8495483398438 "When you type a Lisp expression in GNU Emacs using either Lisp Interac-
tion mode or Emacs Lisp mode, you have available to you several commands
to format the Lisp expression so it is easy to read. For example, pressing
the ⟨
" 8 0) (112.66800689697266 535.072021484375 130.42800903320312 535.552001953125 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (112.68000030517578 536.2824096679688 130.4187774658203 544.2525634765625 "TAB
" 10 0) (112.66800689697266 543.5919799804688 130.42800903320312 544.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (90.00009155273438 531.3291015625 449.35589599609375 630.787353515625 "⟩ key automatically indents the line the cursor is on by the right
amount. A command to properly indent the code in a region is customarily
bound to M-C-\\. Indentation is designed so that you can see which elements
of a list belongs to which list—elements of a sub-list are indented more than
the elements of the enclosing list.
In addition, when you type a closing parenthesis, Emacs momentarily
jumps the cursor back to the matching opening parenthesis, so you can see
which one it is. This is very useful, since every list you type in Lisp must have
" 12 0)) (22 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "4
Chapter 1: List Processing
" 0 0) (90.00039672851562 77.48908233642578 449.3244323730469 114.66727447509766 "its closing parenthesis match its opening parenthesis. (See section “Major
Modes” in The GNU Emacs Manual, for more information about Emacs’
modes.)
" 1 0) (90.001220703125 131.30035400390625 228.78074645996094 145.660888671875 "1.2 Run a Program
" 2 0) (90.00100708007812 153.4490966796875 449.4663391113281 350.236083984375 "A list in Lisp—any list—is a program ready to run. If you run it (for
which the Lisp jargon is evaluate), the computer will do one of three things:
do nothing except return to you the list itself; send you an error message; or,
treat the first symbol in the list as a command to do something. (Usually,
of course, it is the last of these three things that you really want!)
The single apostrophe, ’, that I put in front of some of the example lists
in preceding sections is called a quote; when it precedes a list, it tells Lisp
to do nothing with the list, other than take it as it is written. But if there is
no quote preceding a list, the first item of the list is special: it is a command
for the computer to obey. (In Lisp, these commands are called functions.)
The list (+ 2 2) shown above did not have a quote in front of it, so Lisp
understands that the + is an instruction to do something with the rest of the
list: add the numbers that follow.
If you are reading this inside of GNU Emacs in Info, here is how you
can evaluate such a list: place your cursor immediately after the right hand
parenthesis of the following list and then type C-x C-e:
" 3 0) (90.00213623046875 355.297607421875 449.45660400390625 414.67608642578125 "(+ 2 2)
You will see the number 4 appear in the echo area. (In the jargon, what you
have just done is “evaluate the list.” The echo area is the line at the bottom
of the screen that displays or “echoes” text.) Now try the same thing with a
quoted list: place the cursor right after the following list and type C-x C-e:
" 4 0) (89.99981689453125 419.61761474609375 449.44403076171875 566.7073364257812 "’(this is a quoted list)
You will see (this is a quoted list) appear in the echo area.
In both cases, what you are doing is giving a command to the program
inside of GNU Emacs called the Lisp interpreter—giving the interpreter a
command to evaluate the expression. The name of the Lisp interpreter comes
from the word for the task done by a human who comes up with the meaning
of an expression—who “interprets” it.
You can also evaluate an atom that is not part of a list—one that is not
surrounded by parentheses; again, the Lisp interpreter translates from the
humanly readable expression to the language of the computer. But before
discussing this (see Section 1.7, “Variables”, page 10), we will discuss what
the Lisp interpreter does when you make an error.
" 5 0) (90.00013732910156 583.3403930664062 312.9887390136719 597.700927734375 "1.3 Generate an Error Message
" 6 0) (90.00048828125 605.4891357421875 449.4440612792969 630.787353515625 "Partly so you won’t worry if you do it accidentally, we will now give a
command to the Lisp interpreter that generates an error message. This is a
" 7 0)) (23 (90.0 47.60907745361328 449.8147888183594 60.90726852416992 "Generate an Error Message
5
" 0 0) (89.99969482421875 77.48908233642578 449.3667907714844 138.5472869873047 "harmless activity; and indeed, we will often try to generate error messages
intentionally. Once you understand the jargon, error messages can be in-
formative. Instead of being called “error” messages, they should be called
“help” messages. They are like signposts to a traveller in a strange country;
deciphering them can be hard, but once understood, they can point the way.
" 1 0) (89.99981689453125 141.80908203125 449.3234558105469 167.10728454589844 "The error message is generated by a built-in GNU Emacs debugger. We
will ‘enter the debugger’. You get out of the debugger by typing q.
" 2 0) (89.99853515625 170.24908447265625 449.3768005371094 219.43609619140625 "What we will do is evaluate a list that is not quoted and does not have
a meaningful command as its first element. Here is a list almost exactly the
same as the one we just used, but without the single-quote in front of it.
Position the cursor right after it and type C-x C-e:
" 3 0) (111.59806823730469 227.01760864257812 233.72633361816406 235.98399353027344 "(this is an unquoted list)
" 4 0) (89.9980697631836 239.72906494140625 449.3874206542969 288.9072570800781 "What you see depends on which version of Emacs you are running. GNU
Emacs version 21 provides more information than version 20 and before.
First, the more recent result of generating an error; then the earlier, version
20 result.
" 5 0) (89.998046875 292.1690673828125 449.3435974121094 317.4672546386719 "In GNU Emacs version 21, a ‘*Backtrace*’ window will open up and you
will see the following in it:
" 6 0) (111.59724426269531 325.0576171875 346.4422912597656 421.1441345214844 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function this)
(this is an unquoted list)
eval((this is an unquoted list))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 7 0) (89.99765014648438 426.689208984375 449.3754577636719 463.9873962402344 "Your cursor will be in this window (you may have to wait a few seconds
before it becomes visible). To quit the debugger and make the debugger
window go away, type:
" 8 0) (111.5979995727539 471.5777587890625 116.30535125732422 480.54412841796875 "q
" 9 0) (89.99800109863281 484.1692199707031 449.3653259277344 509.4762268066406 "Please type q right now, so you become confident that you can get out of
the debugger. Then, type C-x C-e again to re-enter it.
" 10 0) (104.99765014648438 512.729248046875 449.299072265625 526.0274658203125 "Based on what we already know, we can almost read this error message.
" 11 0) (89.99639892578125 529.169189453125 449.42919921875 590.347412109375 "You read the ‘*Backtrace*’ buffer from the bottom up; it tells you what
Emacs did. When you typed C-x C-e, you made an interactive call to the
command eval-last-sexp. eval is an abbreviation for ‘evaluate’ and sexp
is an abbreviation for ‘symbolic expression’. The command means ‘evaluate
last symbolic expression’, which is the expression just before your cursor.
" 12 0) (89.99649047851562 593.6092529296875 449.75628662109375 630.7874755859375 "Each line above tells you what the Lisp interpreter evaluated next. The
most recent action is at the top. The buffer is called the ‘*Backtrace*’
buffer because it enables you to track Emacs backwards.
" 13 0)) (24 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "6
Chapter 1: List Processing
" 0 0) (105.00039672851562 79.88904571533203 373.5820617675781 93.1872329711914 "At the top of the ‘*Backtrace*’ buffer, you see the line:
" 1 0) (89.99893188476562 98.61758422851562 449.7381286621094 363.90740966796875 "Debugger entered--Lisp error: (void-function this)
The Lisp interpreter tried to evaluate the first atom of the list, the word
‘this’. It is this action that generated the error message ‘void-function
this’.
The message contains the words ‘void-function’ and ‘this’.
The word ‘function’ was mentioned once before. It is a very important
word. For our purposes, we can define it by saying that a function is a set
of instructions to the computer that tell the computer to do something.
Now we can begin to understand the error message: ‘void-function
this’. The function (that is, the word ‘this’) does not have a definition of
any set of instructions for the computer to carry out.
The slightly odd word, ‘void-function’, is designed to cover the way
Emacs Lisp is implemented, which is that when a symbol does not have a
function definition attached to it, the place that should contain the instruc-
tions is ‘void’.
On the other hand, since we were able to add 2 plus 2 successfully, by
evaluating (+ 2 2), we can infer that the symbol + must have a set of in-
structions for the computer to obey and those instructions must be to add
the numbers that follow the +.
In GNU Emacs version 20, and in earlier versions, you will see only one
line of error message; it will appear in the echo area and look like this:
" 2 0) (89.99703979492188 369.2177734375 449.7022399902344 517.2674560546875 "Symbol’s function definition is void: this
(Also, your terminal may beep at you—some do, some don’t; and others
blink. This is just a device to get your attention.) The message goes away
as soon as you type another key, even just to move the cursor.
We know the meaning of the word ‘Symbol’. It refers to the first atom of
the list, the word ‘this’. The word ‘function’ refers to the instructions that
tell the computer what to do. (Technically, the symbol tells the computer
where to find the instructions, but this is a complication we can ignore for
the moment.)
The error message can be understood: ‘Symbol’s function definition
is void: this’. The symbol (that is, the word ‘this’) lacks instructions for
the computer to carry out.
" 3 0) (89.99691772460938 535.2205200195312 403.7975158691406 549.5810546875 "1.4 Symbol Names and Function Definitions
" 4 0) (89.996826171875 557.729248046875 449.39691162109375 630.7874755859375 "We can articulate another characteristic of Lisp based on what we have
discussed so far—an important characteristic: a symbol, like +, is not itself
the set of instructions for the computer to carry out. Instead, the symbol
is used, perhaps temporarily, as a way of locating the definition or set of
instructions. What we see is the name through which the instructions can
be found. Names of people work the same way.
I can be referred to as
" 5 0)) (25 (90.0 47.60907745361328 449.8582458496094 60.90726852416992 "The Lisp Interpreter
7
" 0 0) (89.99691772460938 77.48908233642578 449.4644775390625 305.9473571777344 "‘Bob’; however, I am not the letters ‘B’, ‘o’, ‘b’ but am the consciousness
consistently associated with a particular life-form. The name is not me, but
it can be used to refer to me.
In Lisp, one set of instructions can be attached to several names. For
example, the computer instructions for adding numbers can be linked to the
symbol plus as well as to the symbol + (and are in some dialects of Lisp).
Among humans, I can be referred to as ‘Robert’ as well as ‘Bob’ and by
other words as well.
On the other hand, a symbol can have only one function definition at-
tached to it at a time. Otherwise, the computer would be confused as to
which definition to use. If this were the case among people, only one person
in the world could be named ‘Bob’. However, the function definition to which
the name refers can be changed readily. (See Section 3.2, “Install a Function
Definition”, page 31.)
Since Emacs Lisp is large, it is customary to name symbols in a way that
identifies the part of Emacs to which the function belongs. Thus, all the
names for functions that deal with Texinfo start with ‘texinfo-’ and those
for functions that deal with reading mail start with ‘rmail-’.
" 1 0) (89.99710083007812 330.38043212890625 264.1138916015625 344.740966796875 "1.5 The Lisp Interpreter
" 2 0) (89.99496459960938 354.44915771484375 449.4619140625 630.787353515625 "Based on what we have seen, we can now start to figure out what the Lisp
interpreter does when we command it to evaluate a list. First, it looks to see
whether there is a quote before the list; if there is, the interpreter just gives
us the list. On the other hand, if there is no quote, the interpreter looks at
the first element in the list and sees whether it has a function definition. If
it does, the interpreter carries out the instructions in the function definition.
Otherwise, the interpreter prints an error message.
This is how Lisp works. Simple. There are added complications which
we will get to in a minute, but these are the fundamentals. Of course, to
write Lisp programs, you need to know how to write function definitions and
attach them to names, and how to do this without confusing either yourself
or the computer.
Now, for the first complication. In addition to lists, the Lisp interpreter
can evaluate a symbol that is not quoted and does not have parentheses
around it.
The Lisp interpreter will attempt to determine the symbol’s
value as a variable. This situation is described in the section on variables.
(See Section 1.7, “Variables”, page 10.)
The second complication occurs because some functions are unusual and
do not work in the usual manner. Those that don’t are called special forms.
They are used for special jobs, like defining a function, and there are not
many of them. In the next few chapters, you will be introduced to several
of the more important special forms.
" 3 0)) (26 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "8
Chapter 1: List Processing
" 0 0) (89.99853515625 77.48908233642578 449.49615478515625 213.4272918701172 "The third and final complication is this: if the function that the Lisp
interpreter is looking at is not a special form, and if it is part of a list, the
Lisp interpreter looks to see whether the list has a list inside of it. If there
is an inner list, the Lisp interpreter first figures out what it should do with
the inside list, and then it works on the outside list. If there is yet another
list embedded inside the inner list, it works on that one first, and so on.
It always works on the innermost list first. The interpreter works on the
innermost list first, to evaluate the result of that list. The result may be
used by the enclosing expression.
Otherwise, the interpreter works left to right, from one expression to the
next.
" 1 0) (89.99853515625 229.9217529296875 229.24867248535156 243.02574157714844 "1.5.1 Byte Compiling
" 2 0) (89.99526977539062 252.208984375 449.4936218261719 427.0271911621094 "One other aspect of interpreting: the Lisp interpreter is able to interpret
two kinds of entity: humanly readable code, on which we will focus exclu-
sively, and specially processed code, called byte compiled code, which is not
humanly readable. Byte compiled code runs faster than humanly readable
code.
You can transform humanly readable code into byte compiled code by
running one of the compile commands such as byte-compile-file. Byte
compiled code is usually stored in a file that ends with a ‘.elc’ exten-
sion rather than a ‘.el’ extension. You will see both kinds of file in the
‘emacs/lisp’ directory; the files to read are those with ‘.el’ extensions.
As a practical matter, for most things you might do to customize or
extend Emacs, you do not need to byte compile; and I will not discuss
the topic here. See section “Byte Compilation” in The GNU Emacs Lisp
Reference Manual, for a full description of byte compilation.
" 3 0) (89.99472045898438 447.74029541015625 193.54904174804688 462.100830078125 "1.6 Evaluation
" 4 0) (89.99298095703125 470.9690246582031 449.40380859375 630.7872314453125 "When the Lisp interpreter works on an expression, the term for the ac-
tivity is called evaluation. We say that the interpreter ‘evaluates the expres-
sion’. I’ve used this term several times before. The word comes from its
use in everyday language, ‘to ascertain the value or amount of; to appraise’,
according to Webster’s New Collegiate Dictionary.
After evaluating an expression, the Lisp interpreter will most likely return
the value that the computer produces by carrying out the instructions it
found in the function definition, or perhaps it will give up on that function
and produce an error message. (The interpreter may also find itself tossed,
so to speak, to a different function or it may attempt to repeat continually
what it is doing for ever and ever in what is called an ‘infinite loop’. These
actions are less common; and we can ignore them.) Most frequently, the
interpreter returns a value.
" 5 0)) (27 (90.0 47.60907745361328 449.83587646484375 60.90726852416992 "Evaluating Inner Lists
9
" 0 0) (89.99923706054688 77.48908233642578 449.3990783691406 188.58726501464844 "At the same time the interpreter returns a value, it may do something
else as well, such as move a cursor or copy a file; this other kind of action
is called a side effect. Actions that we humans think are important, such as
printing results, are often “side effects” to the Lisp interpreter. The jargon
can sound peculiar, but it turns out that it is fairly easy to learn to use side
effects.
In summary, evaluating a symbolic expression most commonly causes the
Lisp interpreter to return a value and perhaps carry out a side effect; or else
produce an error.
" 1 0) (89.99913024902344 202.56182861328125 270.7168884277344 215.6658172607422 "1.6.1 Evaluating Inner Lists
" 2 0) (89.99765014648438 223.88909912109375 449.3211669921875 299.2362060546875 "If evaluation applies to a list that is inside another list, the outer list may
use the value returned by the first evaluation as information when the outer
list is evaluated. This explains why inner expressions are evaluated first: the
values they return are used by the outer expressions.
We can investigate this process by evaluating another addition example.
Place your cursor after the following expression and type C-x C-e:
" 3 0) (89.99594116210938 304.4176330566406 449.461181640625 492.1872863769531 "(+ 2 (+ 3 3))
The number 8 will appear in the echo area.
What happens is that the Lisp interpreter first evaluates the inner ex-
pression, (+ 3 3), for which the value 6 is returned; then it evaluates the
outer expression as if it were written (+ 2 6), which returns the value 8.
Since there are no more enclosing expressions to evaluate, the interpreter
prints that value in the echo area.
Now it is easy to understand the name of the command invoked by the
keystrokes C-x C-e: the name is eval-last-sexp.
The letters sexp are
an abbreviation for ‘symbolic expression’, and eval is an abbreviation for
‘evaluate’. The command means ‘evaluate last symbolic expression’.
As an experiment, you can try evaluating the expression by putting the
cursor at the beginning of the next line immediately following the expression,
or inside the expression.
Here is another copy of the expression:
" 4 0) (89.99530029296875 497.3776550292969 449.4059143066406 630.787353515625 "(+ 2 (+ 3 3))
If you place the cursor at the beginning of the blank line that immediately
follows the expression and type C-x C-e, you will still get the value 8 printed
in the echo area. Now try putting the cursor inside the expression. If you
put it right after the next to last parenthesis (so it appears to sit on top
of the last parenthesis), you will get a 6 printed in the echo area! This is
because the command evaluates the expression (+ 3 3).
Now put the cursor immediately after a number. Type C-x C-e and you
will get the number itself. In Lisp, if you evaluate a number, you get the
number itself—this is how numbers differ from symbols. If you evaluate a
list starting with a symbol like +, you will get a value returned that is the
" 5 0)) (28 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "10
Chapter 1: List Processing
" 0 0) (89.999267578125 77.48908233642578 449.2245178222656 114.66727447509766 "result of the computer carrying out the instructions in the function definition
attached to that name. If a symbol by itself is evaluated, something different
happens, as we will see in the next section.
" 1 0) (89.9996337890625 137.54034423828125 183.30419921875 151.90087890625 "1.7 Variables
" 2 0) (89.9949951171875 161.24908447265625 449.5032958984375 436.5160827636719 "In Emacs Lisp, a symbol can have a value attached to it just as it can
have a function definition attached to it. The two are different. The function
definition is a set of instructions that a computer will obey. A value, on the
other hand, is something, such as number or a name, that can vary (which
is why such a symbol is called a variable). The value of a symbol can be any
expression in Lisp, such as a symbol, number, list, or string. A symbol that
has a value is often called a variable.
A symbol can have both a function definition and a value attached to it
at the same time. Or it can have just one or the other. The two are separate.
This is somewhat similar to the way the name Cambridge can refer to the
city in Massachusetts and have some information attached to the name as
well, such as “great programming center”.
Another way to think about this is to imagine a symbol as being a chest of
drawers. The function definition is put in one drawer, the value in another,
and so on. What is put in the drawer holding the value can be changed
without affecting the contents of the drawer holding the function definition,
and vice-versa.
The variable fill-column illustrates a symbol with a value attached to
it: in every GNU Emacs buffer, this symbol is set to some value, usually 72
or 70, but sometimes to some other value. To find the value of this symbol,
evaluate it by itself. If you are reading this in Info inside of GNU Emacs,
you can do this by putting the cursor after the symbol and typing C-x C-e:
" 3 0) (89.9940185546875 443.1376037597656 449.47039794921875 630.787353515625 "fill-column
After I typed C-x C-e, Emacs printed the number 72 in my echo area. This
is the value for which fill-column is set for me as I write this. It may
be different for you in your Info buffer. Notice that the value returned as
a variable is printed in exactly the same way as the value returned by a
function carrying out its instructions. From the point of view of the Lisp
interpreter, a value returned is a value returned. What kind of expression it
came from ceases to matter once the value is known.
A symbol can have any value attached to it or, to use the jargon, we can
bind the variable to a value: to a number, such as 72; to a string, \"such as
this\"; to a list, such as (spruce pine oak); we can even bind a variable to
a function definition.
A symbol can be bound to a value in several ways.
See Section 1.9,
“Setting the Value of a Variable”, page 17, for information about one way
to do this.
" 4 0)) (29 (90.0 47.60907745361328 449.5411682128906 60.90726852416992 "Error Message for a Symbol Without a Value
11
" 0 0) (89.99951171875 78.2418212890625 441.228759765625 91.34580993652344 "1.7.1 Error Message for a Symbol Without a Function
" 1 0) (89.99884033203125 99.68909454345703 449.4649353027344 175.02732849121094 "When we evaluated fill-column to find its value as a variable, we did
not place parentheses around the word. This is because we did not intend
to use it as a function name.
If fill-column were the first or only element of a list, the Lisp interpreter
would attempt to find the function definition attached to it.
But fill-
column has no function definition. Try evaluating this:
" 2 0) (89.99842071533203 180.33767700195312 449.25616455078125 204.06736755371094 "(fill-column)
In GNU Emacs version 21, you will create a ‘*Backtrace*’ buffer that says:
" 3 0) (89.99859619140625 209.37771606445312 449.3437194824219 359.34735107421875 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function fill-column)
(fill-column)
eval((fill-column))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(Remember, to quit the debugger and make the debugger window go away,
type q in the ‘*Backtrace*’ buffer.)
In GNU Emacs 20 and before, you will produce an error message that
says:
" 4 0) (89.99845886230469 364.65771484375 449.4523620605469 400.2673645019531 "Symbol’s function definition is void: fill-column
(The message will go away away as soon as you move the cursor or type
another key.)
" 5 0) (89.99870300292969 414.6019287109375 421.0548095703125 427.7059326171875 "1.7.2 Error Message for a Symbol Without a Value
" 6 0) (89.99868774414062 436.0491943359375 449.5945739746094 485.2362060546875 "If you attempt to evaluate a symbol that does not have a value bound
to it, you will receive an error message. You can see this by experimenting
with our 2 plus 2 addition. In the following expression, put your cursor right
after the +, before the first number 2, type C-x C-e:
" 7 0) (89.99947357177734 490.4177551269531 416.4536437988281 514.2673950195312 "(+ 2 2)
In GNU Emacs 21, you will create a ‘*Backtrace*’ buffer that says:
" 8 0) (89.99969482421875 519.5778198242188 449.3229675292969 630.7874755859375 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-variable +)
eval(+)
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(As with the other times we entered the debugger, you can quit by typing q
in the ‘*Backtrace*’ buffer.)
" 9 0)) (30 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "12
Chapter 1: List Processing
" 0 0) (89.99711608886719 77.48908233642578 449.40985107421875 275.7072448730469 "This backtrace is different from the very first error message we saw,
which said, ‘Debugger entered--Lisp error: (void-function this)’. In
this case, the function does not have a value as a variable; while in the other
error message, the function (the word ‘this’) did not have a definition.
In this experiment with the +, what we did was cause the Lisp interpreter
to evaluate the + and look for the value of the variable instead of the function
definition. We did this by placing the cursor right after the symbol rather
than after the parenthesis of the enclosing list as we did before. As a conse-
quence, the Lisp interpreter evaluated the preceding s-expression, which in
this case was the + by itself.
Since + does not have a value bound to it, just the function definition,
the error message reported that the symbol’s value as a variable was void.
In GNU Emacs version 20 and before, your error message will say:
Symbol’s value as variable is void: +
The meaning is the same as in GNU Emacs 21.
" 1 0) (89.99661254882812 297.7403564453125 196.37869262695312 312.10089111328125 "1.8 Arguments
" 2 0) (89.9964599609375 321.2090759277344 449.287109375 346.50726318359375 "To see how information is passed to functions, let’s look again at our old
standby, the addition of two plus two. In Lisp, this is written as follows:
" 3 0) (89.99591064453125 352.8976135253906 449.4605712890625 503.9472351074219 "(+ 2 2)
If you evaluate this expression, the number 4 will appear in your echo
area. What the Lisp interpreter does is add the numbers that follow the +.
The numbers added by + are called the arguments of the function +.
These numbers are the information that is given to or passed to the function.
The word ‘argument’ comes from the way it is used in mathematics and
does not refer to a disputation between two people; instead it refers to the
information presented to the function, in this case, to the +. In Lisp, the
arguments to a function are the atoms or lists that follow the function. The
values returned by the evaluation of these atoms or lists are passed to the
function. Different functions require different numbers of arguments; some
functions require none at all.1
" 4 0) (89.98799896240234 517.9119873046875 233.98800659179688 518.3919677734375 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (95.87999725341797 518.8551635742188 449.8175354003906 630.3016357421875 "1 It is curious to track the path by which the word ‘argument’ came to have two differ-
ent meanings, one in mathematics and the other in everyday English. According to
the Oxford English Dictionary, the word derives from the Latin for ‘to make clear,
prove’; thus it came to mean, by one thread of derivation, ‘the evidence offered as
proof’, which is to say, ‘the information offered’, which led to its meaning in Lisp.
But in the other thread of derivation, it came to mean ‘to assert in a manner against
which others may make counter assertions’, which led to the meaning of the word as a
disputation. (Note here that the English word has two different definitions attached to
it at the same time. By contrast, in Emacs Lisp, a symbol cannot have two different
function definitions at the same time.)
" 6 0)) (31 (90.0 47.60907745361328 449.5195007324219 60.90726852416992 "An Argument as the Value of a Variable or List
13
" 0 0) (89.99984741210938 78.2418212890625 282.3642272949219 91.34580993652344 "1.8.1 Arguments’ Data Types
" 1 0) (89.99920654296875 99.56909942626953 449.4541320800781 198.6672821044922 "The type of data that should be passed to a function depends on what
kind of information it uses. The arguments to a function such as + must
have values that are numbers, since + adds numbers. Other functions use
different kinds of data for their arguments.
For example, the concat function links together or unites two or more
strings of text to produce a string. The arguments are strings. Concate-
nating the two character strings abc, def produces the single string abcdef.
This can be seen by evaluating the following:
" 2 0) (89.99880981445312 203.73764038085938 449.5189208984375 327.3072204589844 "(concat \"abc\" \"def\")
The value produced by evaluating this expression is \"abcdef\".
A function such as substring uses both a string and numbers as argu-
ments. The function returns a part of the string, a substring of the first
argument. This function takes three arguments. Its first argument is the
string of characters, the second and third arguments are numbers that in-
dicate the beginning and end of the substring. The numbers are a count
of the number of characters (including spaces and punctuations) from the
beginning of the string.
For example, if you evaluate the following:
" 3 0) (89.99746704101562 332.3775634765625 449.5065002441406 453.7873229980469 "(substring \"The quick brown fox jumped.\" 16 19)
you will see \"fox\" appear in the echo area. The arguments are the string
and the two numbers.
Note that the string passed to substring is a single atom even though
it is made up of several words separated by spaces. Lisp counts everything
between the two quotation marks as part of the string, including the spaces.
You can think of the substring function as a kind of ‘atom smasher’ since it
takes an otherwise indivisible atom and extracts a part. However, substring
is only able to extract a substring from an argument that is a string, not
from another type of atom such as a number or symbol.
" 4 0) (89.99795532226562 467.5218811035156 435.76593017578125 480.6258850097656 "1.8.2 An Argument as the Value of a Variable or List
" 5 0) (89.99832153320312 488.84912109375 449.4090576171875 540.1961669921875 "An argument can be a symbol that returns a value when it is evaluated.
For example, when the symbol fill-column by itself is evaluated, it returns
a number. This number can be used in an addition.
Position the cursor after the following expression and type C-x C-e:
" 6 0) (89.9979248046875 545.3777465820312 449.3211669921875 630.787353515625 "(+ 2 fill-column)
The value will be a number two more than what you get by evaluating
fill-column alone. For me, this is 74, because the value of fill-column is
72.
As we have just seen, an argument can be a symbol that returns a value
when evaluated. In addition, an argument can be a list that returns a value
when it is evaluated. For example, in the following expression, the arguments
" 7 0)) (32 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "14
Chapter 1: List Processing
" 0 0) (89.99893188476562 77.48908233642578 449.4317321777344 102.66727447509766 "to the function concat are the strings \"The \" and \" red foxes.\" and the
list (number-to-string (+ 2 fill-column)).
" 1 0) (89.9990234375 108.93759155273438 449.813720703125 193.3872528076172 "(concat \"The \" (number-to-string (+ 2 fill-column)) \" red foxes.\")
If you evaluate this expression—and if, as with my Emacs, fill-column
evaluates to 72—\"The 74 red foxes.\" will appear in the echo area. (Note
that you must put spaces after the word ‘The’ and before the word ‘red’
so they will appear in the final string.
The function number-to-string
converts the integer that the addition function returns to a string. number-
to-string is also known as int-to-string.)
" 2 0) (89.99903869628906 210.601806640625 331.18389892578125 223.70579528808594 "1.8.3 Variable Number of Arguments
" 3 0) (89.99853515625 233.009033203125 449.4313049316406 309.4272155761719 "Some functions, such as concat, + or *, take any number of arguments.
(The * is the symbol for multiplication.) This can be seen by evaluating
each of the following expressions in the usual way. What you will see in the
echo area is printed in this text after ‘⇒’, which you may read as ‘evaluates
to’.
In the first set, the functions have no arguments:
" 4 0) (111.59883117675781 314.8530578613281 177.5061798095703 330.40972900390625 "(+)
⇒ 0
" 5 0) (111.59883117675781 339.8130187988281 177.5061798095703 355.36968994140625 "(*)
⇒ 1
" 6 0) (104.99882507324219 353.2489929199219 343.0240783691406 366.54718017578125 "In this set, the functions have one argument each:
" 7 0) (111.59925842285156 371.9730224609375 177.50660705566406 387.5296936035156 "(+ 3)
⇒ 3
" 8 0) (111.59925842285156 396.8130187988281 177.50660705566406 412.36968994140625 "(* 3)
⇒ 3
" 9 0) (104.99925231933594 410.3689880371094 355.2318115234375 423.66717529296875 "In this set, the functions have three arguments each:
" 10 0) (111.5989990234375 429.093017578125 182.17779541015625 445.24969482421875 "(+ 3 4 5) ⇒ 12
" 11 0) (111.59896850585938 453.9330139160156 182.17776489257812 470.0896911621094 "(* 3 4 5) ⇒ 60
" 12 0) (89.99893188476562 480.4817199707031 431.9792785644531 493.5857238769531 "1.8.4 Using the Wrong Type Object as an Argument
" 13 0) (89.99838256835938 502.88897705078125 449.4961242675781 563.9559936523438 "When a function is passed an argument of the wrong type, the Lisp
interpreter produces an error message. For example, the + function expects
the values of its arguments to be numbers. As an experiment we can pass it
the quoted symbol hello instead of a number. Position the cursor after the
following expression and type C-x C-e:
" 14 0) (89.99658203125 570.2175903320312 449.3319091796875 630.7872314453125 "(+ 2 ’hello)
When you do this you will generate an error message. What has happened is
that + has tried to add the 2 to the value returned by ’hello, but the value
returned by ’hello is the symbol hello, not a number. Only numbers can
be added. So + could not carry out its addition.
" 15 0)) (33 (90.0 47.60907745361328 449.54150390625 60.90726852416992 "Using the Wrong Type Object as an Argument
15
" 0 0) (89.99951171875 85.52906036376953 449.80322265625 110.8272476196289 "In GNU Emacs version 21, you will create and enter a ‘*Backtrace*’
buffer that says:
" 1 0) (111.59939575195312 121.77761840820312 369.980712890625 230.46385192871094 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error:
(wrong-type-argument number-or-marker-p hello)
+(2 hello)
eval((+ 2 (quote hello)))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 2 0) (90.00003051757812 238.7689208984375 449.30157470703125 264.0671081542969 "As usual, the error message tries to be helpful and makes sense after you
learn how to read it.
" 3 0) (89.99972534179688 270.68890380859375 449.4212341308594 307.8670959472656 "The first part of the error message is straightforward; it says ‘wrong type
argument’. Next comes the mysterious jargon word ‘number-or-marker-p’.
This word is trying to tell you what kind of argument the + expected.
" 4 0) (89.99972534179688 314.60888671875 449.43310546875 405.0495910644531 "The symbol number-or-marker-p says that the Lisp interpreter is try-
ing to determine whether the information presented it (the value of the
argument) is a number or a marker (a special object representing a buffer
position). What it does is test to see whether the + is being given numbers to
add. It also tests to see whether the argument is something called a marker,
which is a specific feature of Emacs Lisp. (In Emacs, locations in a buffer
are recorded as markers.
When the mark is set with the C-@ or C-⟨
" 5 0) (430.3080139160156 389.6319885253906 446.9880065917969 390.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (430.32000732421875 390.8424377441406 446.865966796875 398.8125305175781 "SPC
" 7 0) (430.3080139160156 398.2720031738281 446.9880065917969 398.75201416015625 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99850463867188 389.49310302734375 449.9865417480469 447.42724609375 "⟩
command, its position is kept as a marker. The mark can be considered a
number—the number of characters the location is from the beginning of the
buffer.) In Emacs Lisp, + can be used to add the numeric value of marker
positions as numbers.
" 9 0) (89.99911499023438 454.049072265625 449.3556213378906 562.9873046875 "The ‘p’ of number-or-marker-p is the embodiment of a practice started
in the early days of Lisp programming. The ‘p’ stands for ‘predicate’. In the
jargon used by the early Lisp researchers, a predicate refers to a function
to determine whether some property is true or false. So the ‘p’ tells us that
number-or-marker-p is the name of a function that determines whether it
is true or false that the argument supplied is a number or a marker. Other
Lisp symbols that end in ‘p’ include zerop, a function that tests whether its
argument has the value of zero, and listp, a function that tests whether its
argument is a list.
" 10 0) (89.99859619140625 569.609130859375 449.3768005371094 630.787353515625 "Finally, the last part of the error message is the symbol hello. This is the
value of the argument that was passed to +. If the addition had been passed
the correct type of object, the value passed would have been a number, such
as 37, rather than a symbol like hello. But then you would not have got
the error message.
" 11 0)) (34 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "16
Chapter 1: List Processing
" 0 0) (89.99951171875 79.52906036376953 449.3662414550781 104.8272476196289 "In GNU Emacs version 20 and before, the echo area displays an error
message that says:
" 1 0) (89.99954223632812 109.77761840820312 449.72625732421875 145.1472625732422 "Wrong type argument: number-or-marker-p, hello
This says, in different words, the same as the top line of the ‘*Backtrace*’
buffer.
" 2 0) (89.99954223632812 157.92181396484375 265.9501037597656 171.03736877441406 "1.8.5 The message Function
" 3 0) (89.99853515625 179.00909423828125 449.47509765625 242.22727966308594 "Like +, the message function takes a variable number of arguments. It is
used to send messages to the user and is so useful that we will describe it
here.
A message is printed in the echo area.
For example, you can print a
message in your echo area by evaluating the following list:
" 4 0) (89.99856567382812 247.29763793945312 449.5411376953125 418.2760009765625 "(message \"This message appears in the echo area!\")
The whole string between double quotation marks is a single argument
and is printed in toto. (Note that in this example, the message itself will ap-
pear in the echo area within double quotes; that is because you see the value
returned by the message function. In most uses of message in programs that
you write, the text will be printed in the echo area as a side-effect, without
the quotes. See Section 3.3.1, “multiply-by-seven in detail”, page 34, for
an example of this.)
However, if there is a ‘%s’ in the quoted string of characters, the message
function does not print the ‘%s’ as such, but looks to the argument that
follows the string. It evaluates the second argument and prints the value at
the location in the string where the ‘%s’ is.
You can see this by positioning the cursor after the following expression
and typing C-x C-e:
" 5 0) (89.9979248046875 423.217529296875 449.4093017578125 508.38720703125 "(message \"The name of this buffer is: %s.\" (buffer-name))
In Info, \"The name of this buffer is: *info*.\" will appear in the echo
area. The function buffer-name returns the name of the buffer as a string,
which the message function inserts in place of %s.
To print a value as an integer, use ‘%d’ in the same way as ‘%s’. For
example, to print a message in the echo area that states the value of the
fill-column, evaluate the following:
" 6 0) (89.9979248046875 513.3375854492188 449.5290832519531 598.5072631835938 "(message \"The value of fill-column is %d.\" fill-column)
On my system, when I evaluate this list, \"The value of fill-column is
72.\" appears in my echo area2.
If there is more than one ‘%s’ in the quoted string, the value of the first
argument following the quoted string is printed at the location of the first
‘%s’ and the value of the second argument is printed at the location of the
second ‘%s’, and so on.
" 7 0) (89.98799896240234 605.5120239257812 233.98800659179688 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (95.87999725341797 606.5751953125 449.7224426269531 630.3015747070312 "2 Actually, you can use %s to print a number. It is non-specific. %d prints only the part
of a number left of a decimal point, and not anything that is not a number.
" 9 0)) (35 (90.0 47.60907745361328 449.8360595703125 60.90726852416992 "Using set
17
" 0 0) (104.9993896484375 80.60907745361328 307.3194274902344 93.90726470947266 "For example, if you evaluate the following,
" 1 0) (89.99725341796875 100.05758666992188 449.41925048828125 250.9872283935547 "(message \"There are %d %s in the office!\"
(- fill-column 14) \"pink elephants\")
a rather whimsical message will appear in your echo area. On my system it
says, \"There are 58 pink elephants in the office!\".
The expression (- fill-column 14) is evaluated and the resulting num-
ber is inserted in place of the ‘%d’; and the string in double quotes, \"pink
elephants\", is treated as a single argument and inserted in place of the
‘%s’. (That is to say, a string between double quotes evaluates to itself, like
a number.)
Finally, here is a somewhat complex example that not only illustrates
the computation of a number, but also shows how you can use an expression
within an expression to generate the text that is substituted for ‘%s’:
" 2 0) (89.99569702148438 257.1375427246094 449.5152893066406 418.9872131347656 "(message \"He saw %d %s\"
(- fill-column 34)
(concat \"red \"
(substring
\"The quick brown foxes jumped.\" 16 21)
\" leaping.\"))
In this example, message has three arguments: the string, \"He saw %d
%s\", the expression, (- fill-column 32), and the expression beginning with
the function concat. The value resulting from the evaluation of (- fill-
column 32) is inserted in place of the ‘%d’; and the value returned by the
expression beginning with concat is inserted in place of the ‘%s’.
When I evaluate the expression, the message \"He saw 38 red foxes
leaping.\" appears in my echo area.
" 3 0) (89.99574279785156 439.7003173828125 337.15985107421875 454.06085205078125 "1.9 Setting the Value of a Variable
" 4 0) (89.99496459960938 462.9290466308594 449.36309814453125 539.1072998046875 "There are several ways by which a variable can be given a value. One of
the ways is to use either the function set or the function setq. Another way
is to use let (see Section 3.6, “let”, page 36). (The jargon for this process
is to bind a variable to a value.)
The following sections not only describe how set and setq work but also
illustrate how arguments are passed.
" 5 0) (89.99526977539062 555.7218017578125 189.42724609375 568.8373413085938 "1.9.1 Using set
" 6 0) (89.99478149414062 578.009033203125 449.4709777832031 615.196044921875 "To set the value of the symbol flowers to the list ’(rose violet daisy
buttercup), evaluate the following expression by positioning the cursor after
the expression and typing C-x C-e.
" 7 0) (111.59518432617188 621.337646484375 322.8502197265625 630.3040161132812 "(set ’flowers ’(rose violet daisy buttercup))
" 8 0)) (36 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "18
Chapter 1: List Processing
" 0 0) (89.99588012695312 77.48908233642578 449.5401611328125 214.6361083984375 "The list (rose violet daisy buttercup) will appear in the echo area. This
is what is returned by the set function. As a side effect, the symbol flowers
is bound to the list ; that is, the symbol flowers, which can be viewed as a
variable, is given the list as its value. (This process, by the way, illustrates
how a side effect to the Lisp interpreter, setting the value, can be the primary
effect that we humans are interested in. This is because every Lisp function
must return a value if it does not get an error, but it will only have a side
effect if it is designed to have one.)
After evaluating the set expression, you can evaluate the symbol flowers
and it will return the value you just set. Here is the symbol. Place your
cursor after it and type C-x C-e.
" 1 0) (89.99557495117188 221.97763061523438 449.3955078125 299.8273010253906 "flowers
When you evaluate flowers, the list (rose violet daisy buttercup) ap-
pears in the echo area.
Incidentally, if you evaluate ’flowers, the variable with a quote in front
of it, what you will see in the echo area is the symbol itself, flowers. Here
is the quoted symbol, so you can try this:
" 2 0) (89.99444580078125 307.1776428222656 449.5155334472656 440.5873107910156 "’flowers
Note also, that when you use set, you need to quote both arguments to
set, unless you want them evaluated. Since we do not want either argument
evaluated, neither the variable flowers nor the list (rose violet daisy
buttercup), both are quoted. (When you use set without quoting its first
argument, the first argument is evaluated before anything else is done. If
you did this and flowers did not have a value already, you would get an
error message that the ‘Symbol’s value as variable is void’; on the other
hand, if flowers did return a value after it was evaluated, the set would
attempt to set the value that was returned. There are situations where this
is the right thing for the function to do; but such situations are rare.)
" 3 0) (89.99407958984375 460.921875 196.14169311523438 474.0374450683594 "1.9.2 Using setq
" 4 0) (89.99331665039062 484.40911865234375 449.50286865234375 585.787353515625 "As a practical matter, you almost always quote the first argument to set.
The combination of set and a quoted first argument is so common that it
has its own name: the special form setq. This special form is just like set
except that the first argument is quoted automatically, so you don’t need to
type the quote mark yourself. Also, as an added convenience, setq permits
you to set several different variables to different values, all in one expression.
To set the value of the variable carnivores to the list ’(lion tiger
leopard) using setq, the following expression is used:
" 5 0) (89.99374389648438 593.0177001953125 449.1311950683594 630.787353515625 "(setq carnivores ’(lion tiger leopard))
This is exactly the same as using set except the first argument is automat-
ically quoted by setq. (The ‘q’ in setq means quote.)
" 6 0)) (37 (90.0 47.60907745361328 449.8360595703125 60.90726852416992 "Counting
19
" 0 0) (104.9993896484375 79.52906036376953 324.09747314453125 92.8272476196289 "With set, the expression would look like this:
" 1 0) (89.99957275390625 97.89761352539062 449.4219665527344 169.1472625732422 "(set ’carnivores ’(lion tiger leopard))
Also, setq can be used to assign different values to different variables.
The first argument is bound to the value of the second argument, the third
argument is bound to the value of the fourth argument, and so on.
For
example, you could use the following to assign a list of trees to the symbol
trees and a list of herbivores to the symbol herbivores:
" 2 0) (89.99673461914062 174.09762573242188 449.462646484375 308.4672546386719 "(setq trees ’(pine fir oak maple)
herbivores ’(gazelle antelope zebra))
(The expression could just as well have been on one line, but it might not
have fit on a page; and humans find it easier to read nicely formatted lists.)
Although I have been using the term ‘assign’, there is another way of
thinking about the workings of set and setq; and that is to say that set
and setq make the symbol point to the list. This latter way of thinking is
very common and in forthcoming chapters we shall come upon at least one
symbol that has ‘pointer’ as part of its name. The name is chosen because the
symbol has a value, specifically a list, attached to it; or, expressed another
way, the symbol is set to “point” to the list.
" 3 0) (89.99659729003906 321.9618225097656 186.9347686767578 335.0658264160156 "1.9.3 Counting
" 4 0) (89.99603271484375 343.049072265625 449.38531494140625 428.1072692871094 "Here is an example that shows how to use setq in a counter. You might
use this to count how many times a part of your program repeats itself. First
set a variable to zero; then add one to the number each time the program
repeats itself. To do this, you need a variable that serves as a counter, and
two expressions: an initial setq expression that sets the counter variable to
zero; and a second setq expression that increments the counter each time it
is evaluated.
" 5 0) (111.59613800048828 433.1752014160156 385.1600646972656 442.14398193359375 "(setq counter 0)
; Let’s call this the initializer.
" 6 0) (111.59576416015625 458.01519775390625 367.5655212402344 466.9839782714844 "(setq counter (+ counter 1))
; This is the incrementer.
" 7 0) (89.99337768554688 482.9751892089844 449.4482727050781 630.7872924804688 "counter
; This is the counter.
(The text following the ‘;’ are comments.
See Section 3.2.1, “Change a
Function Definition”, page 32.)
If you evaluate the first of these expressions, the initializer, (setq
counter 0), and then evaluate the third expression, counter, the number 0
will appear in the echo area. If you then evaluate the second expression, the
incrementer, (setq counter (+ counter 1)), the counter will get the value
1. So if you again evaluate counter, the number 1 will appear in the echo
area. Each time you evaluate the second expression, the value of the counter
will be incremented.
When you evaluate the incrementer, (setq counter (+ counter 1)), the
Lisp interpreter first evaluates the innermost list; this is the addition. In
" 8 0)) (38 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "20
Chapter 1: List Processing
" 0 0) (89.99929809570312 77.48908233642578 449.4102478027344 150.5472869873047 "order to evaluate this list, it must evaluate the variable counter and the
number 1. When it evaluates the variable counter, it receives its current
value.
It passes this value and the number 1 to the + which adds them
together. The sum is then returned as the value of the inner list and passed
to the setq which sets the variable counter to this new value. Thus, the
value of the variable, counter, is changed.
" 1 0) (89.99888610839844 168.2603759765625 194.45069885253906 182.62091064453125 "1.10 Summary
" 2 0) (89.99853515625 190.64910888671875 449.4289855957031 550.1472778320312 "Learning Lisp is like climbing a hill in which the first part is the steepest.
You have now climbed the most difficult part; what remains becomes easier
as you progress onwards.
In summary,
• Lisp programs are made up of expressions, which are lists or single
atoms.
• Lists are made up of zero or more atoms or inner lists, separated by
whitespace and surrounded by parentheses. A list can be empty.
• Atoms are multi-character symbols, like forward-paragraph, single
character symbols like +, strings of characters between double quota-
tion marks, or numbers.
• A number evaluates to itself.
• A string between double quotes also evaluates to itself.
• When you evaluate a symbol by itself, its value is returned.
• When you evaluate a list, the Lisp interpreter looks at the first symbol
in the list and then at the function definition bound to that symbol.
Then the instructions in the function definition are carried out.
• A single-quote, ’, tells the Lisp interpreter that it should return the
following expression as written, and not evaluate it as it would if the
quote were not there.
• Arguments are the information passed to a function. The arguments to
a function are computed by evaluating the rest of the elements of the
list of which the function is the first element.
• A function always returns a value when it is evaluated (unless it gets
an error); in addition, it may also carry out some action called a “side
effect”. In many cases, a function’s primary purpose is to create a side
effect.
" 3 0) (89.99552154541016 567.8603515625 191.33419799804688 582.2208862304688 "1.11 Exercises
" 4 0) (98.99540710449219 590.2490844726562 449.3295593261719 630.7872924804688 "A few simple exercises:
• Generate an error message by evaluating an appropriate symbol that is
not within parentheses.
" 5 0)) (39 (90.0 47.60907745361328 449.8256530761719 60.90726852416992 "Exercises
21
" 0 0) (98.99981689453125 77.48908233642578 449.3341979980469 144.5472869873047 "• Generate an error message by evaluating an appropriate symbol that is
between parentheses.
• Create a counter that increments by two rather than one.
• Write an expression that prints a message in the echo area when evalu-
ated.
" 1 0)) (40 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "22
Chapter 1: List Processing
" 0 0)) (41 (90.0 47.60907745361328 449.8140563964844 60.90726852416992 "Buffer Names
23
" 0 0) (89.9993896484375 75.14844512939453 292.32098388671875 92.38106536865234 "2 Practicing Evaluation
" 1 0) (89.997802734375 102.08905792236328 449.6385498046875 434.1072692871094 "Before learning how to write a function definition in Emacs Lisp, it is
useful to spend a little time evaluating various expressions that have already
been written. These expressions will be lists with the functions as their first
(and often only) element. Since some of the functions associated with buffers
are both simple and interesting, we will start with those. In this section, we
will evaluate a few of these. In another section, we will study the code of
several other buffer-related functions, to see how they were written.
Whenever you give an editing command to Emacs Lisp, such as the com-
mand to move the cursor or to scroll the screen, you are evaluating an ex-
pression, the first element of which is a function. This is how Emacs works.
When you type keys, you cause the Lisp interpreter to evaluate an expres-
sion and that is how you get your results. Even typing plain text involves
evaluating an Emacs Lisp function, in this case, one that uses self-insert-
command, which simply inserts the character you typed. The functions you
evaluate by typing keystrokes are called interactive functions, or commands;
how you make a function interactive will be illustrated in the chapter on
how to write function definitions. See Section 3.3, “Making a Function In-
teractive”, page 33.
In addition to typing keyboard commands, we have seen a second way
to evaluate an expression: by positioning the cursor after a list and typing
C-x C-e. This is what we will do in the rest of this section. There are other
ways to evaluate an expression as well; these will be described as we come
to them.
Besides being used for practicing evaluation, the functions shown in the
next few sections are important in their own right. A study of these functions
makes clear the distinction between buffers and files, how to switch to a
buffer, and how to determine a location within it.
" 2 0) (89.9981689453125 449.9003601074219 215.32943725585938 464.2608947753906 "2.1 Buffer Names
" 3 0) (89.99673461914062 472.049072265625 449.4408264160156 630.787353515625 "The two functions, buffer-name and buffer-file-name, show the differ-
ence between a file and a buffer. When you evaluate the following expression,
(buffer-name), the name of the buffer appears in the echo area. When you
evaluate (buffer-file-name), the name of the file to which the buffer refers
appears in the echo area. Usually, the name returned by (buffer-name) is
the same as the name of the file to which it refers, and the name returned
by (buffer-file-name) is the full path-name of the file.
A file and a buffer are two different entities. A file is information recorded
permanently in the computer (unless you delete it). A buffer, on the other
hand, is information inside of Emacs that will vanish at the end of the editing
session (or when you kill the buffer). Usually, a buffer contains information
that you have copied from a file; we say the buffer is visiting that file. This
copy is what you work on and modify. Changes to the buffer do not change
" 4 0)) (42 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "24
Chapter 2: Practicing Evaluation
" 0 0) (89.99951171875 77.48908233642578 449.3558044433594 142.15606689453125 "the file, until you save the buffer. When you save the buffer, the buffer is
copied to the file and is thus saved permanently.
If you are reading this in Info inside of GNU Emacs, you can evaluate
each of the following expressions by positioning the cursor after it and typing
C-x C-e.
" 1 0) (111.60028076171875 148.53750610351562 172.3654022216797 157.50389099121094 "(buffer-name)
" 2 0) (89.99502563476562 173.49752807617188 450.076171875 630.7871704101562 "(buffer-file-name)
When I do this, ‘\"introduction.texinfo\"’ is the value returned by eval-
uating (buffer-name), and ‘\"/gnu/work/intro/introduction.texinfo\"’
is the value returned by evaluating (buffer-file-name). The former is the
name of the buffer and the latter is the name of the file. (In the expres-
sions, the parentheses tell the Lisp interpreter to treat buffer-name and
buffer-file-name as functions; without the parentheses, the interpreter
would attempt to evaluate the symbols as variables. See Section 1.7, “Vari-
ables”, page 10.)
In spite of the distinction between files and buffers, you will often find
that people refer to a file when they mean a buffer and vice-versa. Indeed,
most people say, “I am editing a file,” rather than saying, “I am editing a
buffer which I will soon save to a file.” It is almost always clear from context
what people mean. When dealing with computer programs, however, it is
important to keep the distinction in mind, since the computer is not as smart
as a person.
The word ‘buffer’, by the way, comes from the meaning of the word as
a cushion that deadens the force of a collision. In early computers, a buffer
cushioned the interaction between files and the computer’s central processing
unit. The drums or tapes that held a file and the central processing unit
were pieces of equipment that were very different from each other, working
at their own speeds, in spurts. The buffer made it possible for them to work
together effectively. Eventually, the buffer grew from being an intermediary,
a temporary holding place, to being the place where work is done. This
transformation is rather like that of a small seaport that grew into a great
city: once it was merely the place where cargo was warehoused temporarily
before being loaded onto ships; then it became a business and cultural center
in its own right.
Not all buffers are associated with files. For example, when you start
an Emacs session by typing the command emacs alone, without naming any
files, Emacs will start with the ‘*scratch*’ buffer on the screen. This buffer
is not visiting any file. Similarly, a ‘*Help*’ buffer is not associated with
any file.
If you switch to the ‘*scratch*’ buffer, type (buffer-name), position
the cursor after it, and type C-x C-e to evaluate the expression, the name
\"*scratch*\" is returned and will appear in the echo area. \"*scratch*\"
is the name of the buffer. However, if you type (buffer-file-name) in
" 3 0)) (43 (90.0 47.60907745361328 449.78125 60.90726852416992 "Getting Buffers
25
" 0 0) (89.99859619140625 77.48908233642578 449.4100036621094 176.46726989746094 "the ‘*scratch*’ buffer and evaluate that, nil will appear in the echo area.
nil is from the Latin word for ‘nothing’; in this case, it means that the
‘*scratch*’ buffer is not associated with any file. (In Lisp, nil is also used
to mean ‘false’ and is a synonym for the empty list, ().)
Incidentally, if you are in the ‘*scratch*’ buffer and want the value
returned by an expression to appear in the ‘*scratch*’ buffer itself rather
than in the echo area, type C-u C-x C-e instead of C-x C-e. This causes the
value returned to appear after the expression. The buffer will look like this:
" 1 0) (89.99822998046875 181.53762817382812 449.3982238769531 240.9072723388672 "(buffer-name)\"*scratch*\"
You cannot do this in Info since Info is read-only and it will not allow you
to change the contents of the buffer. But you can do this in any buffer you
can edit; and when you write code or documentation (such as this book),
this feature is very useful.
" 2 0) (89.99812316894531 257.54034423828125 228.2606201171875 271.90087890625 "2.2 Getting Buffers
" 3 0) (89.99639892578125 279.6890869140625 449.77862548828125 514.50732421875 "The buffer-name function returns the name of the buffer; to get the
buffer itself, a different function is needed: the current-buffer function. If
you use this function in code, what you get is the buffer itself.
A name and the object or entity to which the name refers are different
from each other. You are not your name. You are a person to whom others
refer by name. If you ask to speak to George and someone hands you a
card with the letters ‘G’, ‘e’, ‘o’, ‘r’, ‘g’, and ‘e’ written on it, you might be
amused, but you would not be satisfied. You do not want to speak to the
name, but to the person to whom the name refers. A buffer is similar: the
name of the scratch buffer is ‘*scratch*’, but the name is not the buffer.
To get a buffer itself, you need to use a function such as current-buffer.
However, there is a slight complication: if you evaluate current-buffer
in an expression on its own, as we will do here, what you see is a printed
representation of the name of the buffer without the contents of the buffer.
Emacs works this way for two reasons: the buffer may be thousands of lines
long—too long to be conveniently displayed; and, another buffer may have
the same contents but a different name, and it is important to distinguish
between them.
Here is an expression containing the function:
" 4 0) (89.99655151367188 519.4577026367188 449.4071044921875 630.787353515625 "(current-buffer)
If you evaluate the expression in the usual way, ‘#<buffer *info*>’ appears
in the echo area. The special format indicates that the buffer itself is being
returned, rather than just its name.
Incidentally, while you can type a number or symbol into a program, you
cannot do that with the printed representation of a buffer: the only way to
get a buffer itself is with a function such as current-buffer.
A related function is other-buffer. This returns the most recently se-
lected buffer other than the one you are in currently. If you have recently
" 5 0)) (44 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "26
Chapter 2: Practicing Evaluation
" 0 0) (89.99960327148438 77.48908233642578 449.38861083984375 117.30728912353516 "switched back and forth from the ‘*scratch*’ buffer, other-buffer will
return that buffer.
You can see this by evaluating the expression:
" 1 0) (89.99948120117188 122.85763549804688 449.3883972167969 158.7073211669922 "(other-buffer)
You should see ‘#<buffer *scratch*>’ appear in the echo area, or the name
of whatever other buffer you switched back from most recently1.
" 2 0) (89.99954223632812 177.2603759765625 242.77392578125 191.62091064453125 "2.3 Switching Buffers
" 3 0) (89.9981689453125 199.88909912109375 449.7664794921875 376.2673645019531 "The other-buffer function actually provides a buffer when it is used
as an argument to a function that requires one. We can see this by using
other-buffer and switch-to-buffer to switch to a different buffer.
But first, a brief introduction to the switch-to-buffer function. When
you switched back and forth from Info to the ‘*scratch*’ buffer to evaluate
(buffer-name), you most likely typed C-x b and then typed ‘*scratch*’2
when prompted in the minibuffer for the name of the buffer to which you
wanted to switch. The keystrokes, C-x b, cause the Lisp interpreter to eval-
uate the interactive function switch-to-buffer. As we said before, this is
how Emacs works: different keystrokes call or run different functions. For
example, C-f calls forward-char, M-e calls forward-sentence, and so on.
By writing switch-to-buffer in an expression, and giving it a buffer to
switch to, we can switch buffers just the way C-x b does.
Here is the Lisp expression:
" 4 0) (89.99703979492188 381.8177185058594 449.5504150390625 507.2898864746094 "(switch-to-buffer (other-buffer))
The symbol switch-to-buffer is the first element of the list, so the Lisp
interpreter will treat it as a function and carry out the instructions that
are attached to it.
But before doing that, the interpreter will note that
other-buffer is inside parentheses and work on that symbol first. other-
buffer is the first (and in this case, the only) element of this list, so the Lisp
interpreter calls or runs the function. It returns another buffer. Next, the
interpreter runs switch-to-buffer, passing to it, as an argument, the other
buffer, which is what Emacs will switch to. If you are reading this in Info,
try this now. Evaluate the expression. (To get back, type C-x b ⟨
" 5 0) (401.6280212402344 491.5119934082031 419.7480163574219 491.99200439453125 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (401.6400146484375 492.7224426269531 419.7401428222656 500.6925354003906 "RET
" 7 0) (401.6280212402344 500.0320129394531 419.7480163574219 500.51202392578125 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (419.2799987792969 488.1290588378906 434.0481262207031 506.9297790527344 "⟩.)3
" 9 0) (89.98799896240234 512.3919677734375 233.98800659179688 512.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (95.87995910644531 513.4552001953125 449.8567810058594 615.3016357421875 "1 Actually, by default, if the buffer from which you just switched is visible to you in
another window, other-buffer will choose the most recent buffer that you cannot see;
this is a subtlety that I often forget.
2 Or rather, to save typing, you probably typed just part of the name, such as *sc, and
then pressed your TAB key to cause it to expand to the full name; and then typed your
RET key.
3 Remember, this expression will move you to your most recent other buffer that you
cannot see. If you really want to go to your most recently selected buffer, even if you
can still see it, you need to evaluate the following more complex expression:
" 11 0) (111.60035705566406 621.3377075195312 355.89874267578125 630.3040771484375 "(switch-to-buffer (other-buffer (current-buffer) t))
" 12 0)) (45 (90.0 47.60907745361328 449.5959167480469 60.90726852416992 "Buffer Size and the Location of Point
27
" 0 0) (89.99728393554688 77.48908233642578 449.47625732421875 300.0672912597656 "In the programming examples in later sections of this document, you will
see the function set-buffer more often than switch-to-buffer. This is
because of a difference between computer programs and humans: humans
have eyes and expect to see the buffer on which they are working on their
computer terminals. This is so obvious, it almost goes without saying. How-
ever, programs do not have eyes. When a computer program works on a
buffer, that buffer does not need to be visible on the screen.
switch-to-buffer is designed for humans and does two different things:
it switches the buffer to which Emacs’ attention is directed; and it switches
the buffer displayed in the window to the new buffer. set-buffer, on the
other hand, does only one thing: it switches the attention of the computer
program to a different buffer. The buffer on the screen remains unchanged (of
course, normally nothing happens there until the command finishes running).
Also, we have just introduced another jargon term, the word call. When
you evaluate a list in which the first symbol is a function, you are calling
that function. The use of the term comes from the notion of the function as
an entity that can do something for you if you ‘call’ it—just as a plumber is
an entity who can fix a leak if you call him or her.
" 1 0) (89.99729919433594 320.7803955078125 382.8487243652344 335.14093017578125 "2.4 Buffer Size and the Location of Point
" 2 0) (89.99652099609375 344.0091247558594 449.4404602050781 408.18731689453125 "Finally, let’s look at several rather simple functions, buffer-size, point,
point-min, and point-max. These give information about the size of a buffer
and the location of point within it.
The function buffer-size tells you the size of the current buffer; that
is, the function returns a count of the number of characters in the buffer.
" 3 0) (89.99505615234375 414.2176818847656 449.3948669433594 528.54736328125 "(buffer-size)
You can evaluate this in the usual way, by positioning the cursor after the
expression and typing C-x C-e.
In Emacs, the current position of the cursor is called point. The expres-
sion (point) returns a number that tells you where the cursor is located as
a count of the number of characters from the beginning of the buffer up to
point.
You can see the character count for point in this buffer by evaluating the
following expression in the usual way:
" 4 0) (89.99472045898438 534.6976928710938 449.3069152832031 571.02734375 "(point)
As I write this, the value of point is 65724. The point function is frequently
used in some of the examples later in this book.
" 5 0) (89.98799896240234 583.6719970703125 233.98800659179688 584.1519775390625 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (105.0 588.4552001953125 449.8509216308594 630.308837890625 "In this case, the first argument to other-buffer tells it which buffer to skip—the
current one—and the second argument tells other-buffer it is OK to switch to a
visible buffer.
In regular use, switch-to-buffer takes you to an invisible window
since you would most likely use C-x o (other-window) to go to another visible buffer.
" 7 0)) (46 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "28
Chapter 2: Practicing Evaluation
" 0 0) (90.0001220703125 79.52906036376953 449.50830078125 104.8272476196289 "The value of point depends, of course, on its location within the buffer.
If you evaluate point in this spot, the number will be larger:
" 1 0) (89.99801635742188 109.77761840820312 449.4309997558594 230.82725524902344 "(point)
For me, the value of point in this location is 66043, which means that there
are 319 characters (including spaces) between the two expressions.
The function point-min is somewhat similar to point, but it returns the
value of the minimum permissible value of point in the current buffer. This
is the number 1 unless narrowing is in effect. (Narrowing is a mechanism
whereby you can restrict yourself, or a program, to operations on just a part
of a buffer. See Chapter 6, “Narrowing and Widening”, page 77.) Likewise,
the function point-max returns the value of the maximum permissible value
of point in the current buffer.
" 2 0) (89.99761199951172 247.2203369140625 176.9756317138672 261.58087158203125 "2.5 Exercise
" 3 0) (89.9976806640625 269.36907958984375 449.4519958496094 294.5472717285156 "Find a file with which you are working and move towards its middle.
Find its buffer name, file name, length, and your position in the file.
" 4 0)) (47 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "The defun Special Form
29
" 0 0) (89.99920654296875 75.14844512939453 408.7035217285156 92.38106536865234 "3 How To Write Function Definitions
" 1 0) (89.99887084960938 100.40906524658203 449.50750732421875 356.8272399902344 "When the Lisp interpreter evaluates a list, it looks to see whether the first
symbol on the list has a function definition attached to it; or, put another
way, whether the symbol points to a function definition.
If it does, the
computer carries out the instructions in the definition. A symbol that has a
function definition is called, simply, a function (although, properly speaking,
the definition is the function and the symbol refers to it.)
All functions are defined in terms of other functions, except for a few
primitive functions that are written in the C programming language. When
you write functions’ definitions, you will write them in Emacs Lisp and use
other functions as your building blocks. Some of the functions you will use
will themselves be written in Emacs Lisp (perhaps by you) and some will be
primitives written in C. The primitive functions are used exactly like those
written in Emacs Lisp and behave like them. They are written in C so we
can easily run GNU Emacs on any computer that has sufficient power and
can run C.
Let me re-emphasize this: when you write code in Emacs Lisp, you do
not distinguish between the use of functions written in C and the use of
functions written in Emacs Lisp. The difference is irrelevant.
I mention
the distinction only because it is interesting to know. Indeed, unless you
investigate, you won’t know whether an already-written function is written
in Emacs Lisp or C.
" 2 0) (89.99930572509766 371.66033935546875 285.83026123046875 386.0335693359375 "3.1 The defun Special Form
" 3 0) (89.99844360351562 393.8090515136719 449.5723876953125 630.787353515625 "In Lisp, a symbol such as mark-whole-buffer has code attached to it that
tells the computer what to do when the function is called. This code is called
the function definition and is created by evaluating a Lisp expression that
starts with the symbol defun (which is an abbreviation for define function).
Because defun does not evaluate its arguments in the usual way, it is called
a special form.
In subsequent sections, we will look at function definitions from the Emacs
source code, such as mark-whole-buffer. In this section, we will describe
a simple function definition so you can see how it looks.
This function
definition uses arithmetic because it makes for a simple example.
Some
people dislike examples using arithmetic; however, if you are such a person,
do not despair. Hardly any of the code we will study in the remainder of
this introduction involves arithmetic or mathematics. The examples mostly
involve text in one way or another.
A function definition has up to five parts following the word defun:
1. The name of the symbol to which the function definition should be
attached.
2. A list of the arguments that will be passed to the function. If no argu-
ments will be passed to the function, this is an empty list, ().
" 4 0)) (48 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "30
Chapter 3: How To Write Function Definitions
" 0 0) (95.8790512084961 77.48908233642578 449.5083923339844 170.10728454589844 "3. Documentation describing the function.
(Technically optional, but
strongly recommended.)
4. Optionally, an expression to make the function interactive so you can
use it by typing M-x and then the name of the function; or by typing an
appropriate key or keychord.
5. The code that instructs the computer what to do: the body of the
function definition.
" 1 0) (89.9984130859375 175.4090576171875 449.4312744140625 200.58726501464844 "It is helpful to think of the five parts of a function definition as being
organized in a template, with slots for each part:
" 2 0) (89.99749755859375 206.49517822265625 449.25555419921875 292.1471862792969 "(defun function-name (arguments...)
\"optional-documentation...\"
(interactive argument-passing-info)
; optional
body...)
As an example, here is the code for a function that multiplies its argument
by 7. (This example is not interactive. See Section 3.3, “Making a Function
Interactive”, page 33, for that information.)
" 3 0) (89.99642944335938 298.0575256347656 449.4833984375 630.7872314453125 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
This definition begins with a parenthesis and the symbol defun, followed
by the name of the function.
The name of the function is followed by a list that contains the arguments
that will be passed to the function. This list is called the argument list. In
this example, the list has only one element, the symbol, number. When the
function is used, the symbol will be bound to the value that is used as the
argument to the function.
Instead of choosing the word number for the name of the argument, I
could have picked any other name. For example, I could have chosen the
word multiplicand. I picked the word ‘number’ because it tells what kind
of value is intended for this slot; but I could just as well have chosen the
word ‘multiplicand’ to indicate the role that the value placed in this slot
will play in the workings of the function. I could have called it foogle, but
that would have been a bad choice because it would not tell humans what it
means. The choice of name is up to the programmer and should be chosen
to make the meaning of the function clear.
Indeed, you can choose any name you wish for a symbol in an argument
list, even the name of a symbol used in some other function: the name
you use in an argument list is private to that particular definition. In that
definition, the name refers to a different entity than any use of the same name
outside the function definition. Suppose you have a nick-name ‘Shorty’ in
your family; when your family members refer to ‘Shorty’, they mean you.
But outside your family, in a movie, for example, the name ‘Shorty’ refers to
someone else. Because a name in an argument list is private to the function
" 4 0)) (49 (90.0 47.60907745361328 449.6510314941406 60.90726852416992 "Install a Function Definition
31
" 0 0) (89.9986572265625 77.48908233642578 449.6072692871094 329.7073669433594 "definition, you can change the value of such a symbol inside the body of a
function without changing its value outside the function. The effect is similar
to that produced by a let expression. (See Section 3.6, “let”, page 36.)
The argument list is followed by the documentation string that describes
the function. This is what you see when you type C-h f and the name of a
function. Incidentally, when you write a documentation string like this, you
should make the first line a complete sentence since some commands, such as
apropos, print only the first line of a multi-line documentation string. Also,
you should not indent the second line of a documentation string, if you have
one, because that looks odd when you use C-h f (describe-function). The
documentation string is optional, but it is so useful, it should be included in
almost every function you write.
The third line of the example consists of the body of the function defini-
tion. (Most functions’ definitions, of course, are longer than this.) In this
function, the body is the list, (* 7 number), which says to multiply the value
of number by 7. (In Emacs Lisp, * is the function for multiplication, just as
+ is the function for addition.)
When you use the multiply-by-seven function, the argument number
evaluates to the actual number you want used. Here is an example that
shows how multiply-by-seven is used; but don’t try to evaluate this yet!
" 1 0) (89.99813842773438 336.6977233886719 449.4861755371094 509.4673767089844 "(multiply-by-seven 3)
The symbol number, specified in the function definition in the next section,
is given or “bound to” the value 3 in the actual use of the function. Note
that although number was inside parentheses in the function definition, the
argument passed to the multiply-by-seven function is not in parentheses.
The parentheses are written in the function definition so the computer can
figure out where the argument list ends and the rest of the function definition
begins.
If you evaluate this example, you are likely to get an error message. (Go
ahead, try it!) This is because we have written the function definition, but
not yet told the computer about the definition—we have not yet installed (or
‘loaded’) the function definition in Emacs. Installing a function is the process
that tells the Lisp interpreter the definition of the function. Installation is
described in the next section.
" 2 0) (89.99852752685547 533.6604614257812 318.361572265625 548.02099609375 "3.2 Install a Function Definition
" 3 0) (89.99853515625 557.7291870117188 449.4633483886719 630.7874145507812 "If you are reading this inside of Info in Emacs, you can try out the
multiply-by-seven function by first evaluating the function definition and
then evaluating (multiply-by-seven 3). A copy of the function definition
follows. Place the cursor after the last parenthesis of the function definition
and type C-x C-e. When you do this, multiply-by-seven will appear in the
echo area. (What this means is that when a function definition is evaluated,
" 4 0)) (50 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "32
Chapter 3: How To Write Function Definitions
" 0 0) (89.99884033203125 77.48908233642578 449.2569274902344 102.66727447509766 "the value it returns is the name of the defined function.) At the same time,
this action installs the function definition.
" 1 0) (89.99839782714844 108.33761596679688 449.6280212402344 244.03607177734375 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
By evaluating this defun, you have just installed multiply-by-seven in
Emacs. The function is now just as much a part of Emacs as forward-
word or any other editing function you use. (multiply-by-seven will stay
installed until you quit Emacs. To reload code automatically whenever you
start Emacs, see Section 3.5, “Installing Code Permanently”, page 36.)
You can see the effect of installing multiply-by-seven by evaluating the
following sample. Place the cursor after the following expression and type
C-x C-e. The number 21 will appear in the echo area.
" 2 0) (90.00173950195312 249.69760131835938 449.5650634765625 309.5472717285156 "(multiply-by-seven 3)
If you wish, you can read the documentation for the function by typing
C-h f (describe-function) and then the name of the function, multiply-
by-seven. When you do this, a ‘*Help*’ window will appear on your screen
that says:
" 3 0) (90.00132751464844 315.2176208496094 369.9828186035156 352.6361083984375 "multiply-by-seven:
Multiply NUMBER by seven.
(To return to a single window on your screen, type C-x 1.)
" 4 0) (90.00106811523438 368.0418395996094 317.6019287109375 381.1458435058594 "3.2.1 Change a Function Definition
" 5 0) (90.00045776367188 389.8490905761719 449.45574951171875 501.42730712890625 "If you want to change the code in multiply-by-seven, just rewrite it.
To install the new version in place of the old one, evaluate the function
definition again. This is how you modify code in Emacs. It is very simple.
As an example, you can change the multiply-by-seven function to add
the number to itself seven times instead of multiplying the number by seven.
It produces the same answer, but by a different path. At the same time, we
will add a comment to the code; a comment is text that the Lisp interpreter
ignores, but that a human reader may find useful or enlightening.
The
comment is that this is the “second version”.
" 6 0) (90.00033569335938 507.09527587890625 449.4554138183594 630.787353515625 "(defun multiply-by-seven (number)
; Second version.
\"Multiply NUMBER by seven.\"
(+ number number number number number number number))
The comment follows a semicolon, ‘;’. In Lisp, everything on a line that
follows a semicolon is a comment. The end of the line is the end of the
comment. To stretch a comment over two or more lines, begin each line
with a semicolon.
See Section 16.3, “Beginning a ‘.emacs’ File”, page 216, and section
“Comments” in The GNU Emacs Lisp Reference Manual, for more about
comments.
" 7 0)) (51 (90.0 47.60907745361328 449.6617126464844 60.90726852416992 "Make a Function Interactive
33
" 0 0) (90.00015258789062 77.48908233642578 449.4977111816406 152.9473114013672 "You can install this version of the multiply-by-seven function by eval-
uating it in the same way you evaluated the first function: place the cursor
after the last parenthesis and type C-x C-e.
In summary, this is how you write code in Emacs Lisp: you write a
function; install it; test it; and then make fixes or enhancements and install
it again.
" 1 0) (90.00015258789062 171.0203857421875 318.5445251464844 185.38092041015625 "3.3 Make a Function Interactive
" 2 0) (89.99545288085938 193.52911376953125 449.4504089355469 381.5473327636719 "You make a function interactive by placing a list that begins with the
special form interactive immediately after the documentation.
A user
can invoke an interactive function by typing M-x and then the name of the
function; or by typing the keys to which it is bound, for example, by typing
C-n for next-line or C-x h for mark-whole-buffer.
Interestingly, when you call an interactive function interactively, the value
returned is not automatically displayed in the echo area. This is because you
often call an interactive function for its side effects, such as moving forward
by a word or line, and not for the value returned. If the returned value
were displayed in the echo area each time you typed a key, it would be very
distracting.
Both the use of the special form interactive and one way to display a
value in the echo area can be illustrated by creating an interactive version
of multiply-by-seven.
Here is the code:
" 3 0) (89.9947509765625 386.97528076171875 449.7109375 490.1298828125 "(defun multiply-by-seven (number)
; Interactive version.
\"Multiply NUMBER by seven.\"
(interactive \"p\")
(message \"The result is %d\" (* 7 number)))
You can install this code by placing your cursor after it and typing C-x C-e.
The name of the function will appear in your echo area. Then, you can use
this code by typing C-u and a number and then typing M-x multiply-by-
seven and pressing ⟨
" 4 0) (188.98800659179688 474.35198974609375 207.10800170898438 474.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (189.0 475.56243896484375 207.10011291503906 483.53253173828125 "RET
" 6 0) (188.98800659179688 482.8719787597656 207.10800170898438 483.35198974609375 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (89.9998779296875 470.9690856933594 449.6286926269531 589.1560668945312 "⟩. The phrase ‘The result is ...’ followed by the
product will appear in the echo area.
Speaking more generally, you invoke a function like this in either of two
ways:
1. By typing a prefix argument that contains the number to be passed,
and then typing M-x and the name of the function, as with C-u 3 M-x
forward-sentence; or,
2. By typing whatever key or keychord the function is bound to, as with
C-u 3 M-e.
" 8 0) (89.99884796142578 593.6090698242188 449.2897033691406 630.7872924804688 "Both the examples just mentioned work identically to move point forward
three sentences. (Since multiply-by-seven is not bound to a key, it could
not be used as an example of key binding.)
" 9 0)) (52 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "34
Chapter 3: How To Write Function Definitions
" 0 0) (89.99887084960938 77.48908233642578 449.442626953125 134.2097930908203 "(See Section 16.7, “Some Keybindings”, page 220, to learn how to bind
a command to a key.)
A prefix argument is passed to an interactive function by typing the
⟨
" 1 0) (92.86800384521484 118.7919921875 118.18800354003906 119.2719955444336 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (92.87999725341797 120.00239562988281 118.16650390625 127.9725112915039 "META
" 3 0) (92.86800384521484 127.31201171875 118.18800354003906 127.7920150756836 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00018310546875 115.04907989501953 449.5415344238281 152.58726501464844 "⟩ key followed by a number, for example, M-3 M-e, or by typing C-
u and then a number, for example, C-u 3 M-e (if you type C-u without a
number, it defaults to 4).
" 5 0) (90.00042724609375 166.081787109375 340.1502380371094 179.1973419189453 "3.3.1 An Interactive multiply-by-seven
" 6 0) (90.00039672851562 187.2890625 449.4432067871094 224.46726989746094 "Let’s look at the use of the special form interactive and then at the
function message in the interactive version of multiply-by-seven. You will
recall that the function definition looks like this:
" 7 0) (90.00021362304688 229.53521728515625 449.639892578125 340.5072326660156 "(defun multiply-by-seven (number)
; Interactive version.
\"Multiply NUMBER by seven.\"
(interactive \"p\")
(message \"The result is %d\" (* 7 number)))
In this function, the expression, (interactive \"p\"), is a list of two ele-
ments. The \"p\" tells Emacs to pass the prefix argument to the function and
use its value for the argument of the function.
The argument will be a number. This means that the symbol number
will be bound to a number in the line:
" 8 0) (90.00032043457031 345.57757568359375 449.1166076660156 381.0671081542969 "(message \"The result is %d\" (* 7 number))
For example, if your prefix argument is 5, the Lisp interpreter will evaluate
the line as if it were:
" 9 0) (89.99880981445312 386.0174560546875 449.5517883300781 630.7871704101562 "(message \"The result is %d\" (* 7 5))
(If you are reading this in GNU Emacs, you can evaluate this expression
yourself.) First, the interpreter will evaluate the inner list, which is (* 7
5). This returns a value of 35. Next, it will evaluate the outer list, passing
the values of the second and subsequent elements of the list to the function
message.
As we have seen, message is an Emacs Lisp function especially designed
for sending a one line message to a user. (See Section 1.8.5, “The message
function”, page 16.) In summary, the message function prints its first argu-
ment in the echo area as is, except for occurrences of ‘%d’, ‘%s’, or ‘%c’. When
it sees one of these control sequences, the function looks to the second and
subsequent arguments and prints the value of the argument in the location
in the string where the control sequence is located.
In the interactive multiply-by-seven function, the control string is ‘%d’,
which requires a number, and the value returned by evaluating (* 7 5) is
the number 35. Consequently, the number 35 is printed in place of the ‘%d’
and the message is ‘The result is 35’.
(Note that when you call the function multiply-by-seven, the message
is printed without quotes, but when you call message, the text is printed
in double quotes. This is because the value returned by message is what
" 10 0)) (53 (90.0 47.60907745361328 449.60723876953125 60.90726852416992 "Different Options for interactive
35
" 0 0) (89.99957275390625 77.48908233642578 449.4103088378906 114.66727447509766 "appears in the echo area when you evaluate an expression whose first element
is message; but when embedded in a function, message prints the text as a
side effect without quotes.)
" 1 0) (89.99964904785156 140.54034423828125 353.6011047363281 154.91355895996094 "3.4 Different Options for interactive
" 2 0) (90.0 165.08905029296875 449.3779296875 208.12977600097656 "In the example, multiply-by-seven used \"p\" as the argument to
interactive. This argument told Emacs to interpret your typing either
C-u followed by a number or ⟨
" 3 0) (237.8280029296875 192.35198974609375 263.14801025390625 192.8319854736328 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (237.83999633789062 193.56239318847656 263.1264953613281 201.53250122070312 "META
" 5 0) (237.8280029296875 200.87200927734375 263.14801025390625 201.3520050048828 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99932861328125 188.60906982421875 449.7263488769531 262.0272521972656 "⟩ followed by a number as a command
to pass that number to the function as its argument. Emacs has more than
twenty characters predefined for use with interactive. In almost every
case, one of these options will enable you to pass the right information in-
teractively to a function. (See section “Code Characters for interactive”
in The GNU Emacs Lisp Reference Manual.)
" 7 0) (89.99850463867188 265.1689453125 449.4425048828125 302.3471374511719 "For example, the character ‘r’ causes Emacs to pass the beginning and
end of the region (the current values of point and mark) to the function as
two separate arguments. It is used as follows:
" 8 0) (89.99786376953125 309.6974792480469 449.4625549316406 400.7296447753906 "(interactive \"r\")
On the other hand, a ‘B’ tells Emacs to ask for the name of a buffer that
will be passed to the function. When it sees a ‘B’, Emacs will ask for the
name by prompting the user in the minibuffer, using a string that follows
the ‘B’, as in \"BAppend to buffer: \". Not only will Emacs prompt for the
name, but Emacs will complete the name if you type enough of it and press
⟨
" 9 0) (92.86800384521484 385.31201171875 110.62800598144531 385.7920227050781 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (92.87999725341797 386.5224304199219 110.6187744140625 394.4925231933594 "TAB
" 11 0) (92.86800384521484 393.9519958496094 110.62800598144531 394.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (89.9998779296875 381.92913818359375 449.7382507324219 535.5073852539062 "⟩.
A function with two or more arguments can have information passed
to each argument by adding parts to the string that follows interactive.
When you do this, the information is passed to each argument in the same
order it is specified in the interactive list.
In the string, each part is
separated from the next part by a ‘\\n’, which is a newline. For example,
you could follow \"BAppend to buffer: \" with a ‘\\n’) and an ‘r’. This would
cause Emacs to pass the values of point and mark to the function as well as
prompt you for the buffer—three arguments in all.
In this case, the function definition would look like the following, where
buffer, start, and end are the symbols to which interactive binds the
buffer and the current values of the beginning and ending of the region:
" 13 0) (111.60009765625 542.8552856445312 301.69366455078125 589.1441040039062 "(defun name-of-function (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
body-of-function...)
" 14 0) (89.99908447265625 593.6091918945312 449.36614990234375 630.7874145507812 "(The space after the colon in the prompt makes it look better when you
are prompted. The append-to-buffer function looks exactly like this. See
Section 4.4, “The Definition of append-to-buffer”, page 56.)
" 15 0)) (54 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "36
Chapter 3: How To Write Function Definitions
" 0 0) (89.9991455078125 77.48908233642578 449.42108154296875 164.46726989746094 "If a function does not have arguments, then interactive does not require
any. Such a function contains the simple expression (interactive). The
mark-whole-buffer function is like this.
Alternatively, if the special letter-codes are not right for your application,
you can pass your own arguments to interactive as a list.
See section
“Using Interactive” in The GNU Emacs Lisp Reference Manual, for more
information about this advanced technique.
" 1 0) (89.99888610839844 180.8603515625 299.9631652832031 195.22088623046875 "3.5 Install Code Permanently
" 2 0) (89.99822998046875 203.00909423828125 449.5183410644531 454.3872985839844 "When you install a function definition by evaluating it, it will stay in-
stalled until you quit Emacs.
The next time you start a new session of
Emacs, the function will not be installed unless you evaluate the function
definition again.
At some point, you may want to have code installed automatically when-
ever you start a new session of Emacs.
There are several ways of doing
this:
• If you have code that is just for yourself, you can put the code for the
function definition in your ‘.emacs’ initialization file. When you start
Emacs, your ‘.emacs’ file is automatically evaluated and all the function
definitions within it are installed. See Chapter 16, “Your ‘.emacs’ File”,
page 213.
• Alternatively, you can put the function definitions that you want in-
stalled in one or more files of their own and use the load function to
cause Emacs to evaluate and thereby install each of the functions in the
files. See Section 16.9, “Loading Files”, page 222.
• On the other hand, if you have code that your whole site will use,
it is usual to put it in a file called ‘site-init.el’ that is loaded when
Emacs is built. This makes the code available to everyone who uses your
machine. (See the ‘INSTALL’ file that is part of the Emacs distribution.)
" 3 0) (89.994384765625 458.0091247558594 449.3945007324219 566.9473876953125 "Finally, if you have code that everyone who uses Emacs may want, you
can post it on a computer network or send a copy to the Free Software Foun-
dation. (When you do this, please license the code and its documentation
under a license that permits other people to run, copy, study, modify, and
redistribute the code and which protects you from having your work taken
from you.) If you send a copy of your code to the Free Software Foundation,
and properly protect yourself and others, it may be included in the next
release of Emacs. In large part, this is how Emacs has grown over the past
years, by donations.
" 4 0) (89.99435424804688 583.46044921875 140.906005859375 597.8336791992188 "3.6 let
" 5 0) (89.99359130859375 605.4891357421875 449.3171691894531 630.787353515625 "The let expression is a special form in Lisp that you will need to use in
most function definitions.
" 6 0)) (55 (90.0 47.60907745361328 449.6617126464844 60.90726852416992 "The Parts of a let Expression
37
" 0 0) (89.99655151367188 77.48908233642578 449.54119873046875 534.3071899414062 "let is used to attach or bind a symbol to a value in such a way that
the Lisp interpreter will not confuse the variable with a variable of the same
name that is not part of the function.
To understand why the let special form is necessary, consider the situa-
tion in which you own a home that you generally refer to as ‘the house’, as
in the sentence, “The house needs painting.” If you are visiting a friend and
your host refers to ‘the house’, he is likely to be referring to his house, not
yours, that is, to a different house.
If your friend is referring to his house and you think he is referring to
your house, you may be in for some confusion. The same thing could happen
in Lisp if a variable that is used inside of one function has the same name
as a variable that is used inside of another function, and the two are not
intended to refer to the same value. The let special form prevents this kind
of confusion.
The let special form prevents confusion. let creates a name for a local
variable that overshadows any use of the same name outside the let ex-
pression. This is like understanding that whenever your host refers to ‘the
house’, he means his house, not yours. (Symbols used in argument lists work
the same way. See Section 3.1, “The defun Special Form”, page 29.)
Local variables created by a let expression retain their value only within
the let expression itself (and within expressions called within the let ex-
pression); the local variables have no effect outside the let expression.
Another way to think about let is that it is like a setq that is temporary
and local. The values set by let are automatically undone when the let is
finished. The setting only effects expressions that are inside the bounds of
the let expression. In computer science jargon, we would say “the binding
of a symbol is visible only in functions called in the let form; in Emacs Lisp,
scoping is dynamic, not lexical.”
let can create more than one variable at once.
Also, let gives each
variable it creates an initial value, either a value specified by you, or nil.
(In the jargon, this is called ‘binding the variable to the value’.) After let
has created and bound the variables, it executes the code in the body of the
let, and returns the value of the last expression in the body, as the value of
the whole let expression. (‘Execute’ is a jargon term that means to evaluate
a list; it comes from the use of the word meaning ‘to give practical effect to’
(Oxford English Dictionary). Since you evaluate an expression to perform
an action, ‘execute’ has evolved as a synonym to ‘evaluate’.)
" 1 0) (89.99635314941406 548.2816772460938 320.2282409667969 561.397216796875 "3.6.1 The Parts of a let Expression
" 2 0) (89.99591064453125 569.6089477539062 449.42822265625 630.7871704101562 "A let expression is a list of three parts. The first part is the symbol
let. The second part is a list, called a varlist, each element of which is
either a symbol by itself or a two-element list, the first element of which is
a symbol. The third part of the let expression is the body of the let. The
body usually consists of one or more lists.
" 3 0)) (56 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "38
Chapter 3: How To Write Function Definitions
" 0 0) (104.99932861328125 85.64905548095703 329.6063537597656 98.9472427368164 "A template for a let expression looks like this:
" 1 0) (111.59925842285156 110.13507843017578 204.64085388183594 119.10386657714844 "(let varlist body...)
" 2 0) (89.99923706054688 126.32892608642578 449.5193786621094 187.5071258544922 "The symbols in the varlist are the variables that are given initial values by
the let special form. Symbols by themselves are given the initial value of
nil; and each symbol that is the first element of a two-element list is bound
to the value that is returned when the Lisp interpreter evaluates the second
element.
" 3 0) (89.9986572265625 194.2489013671875 449.33294677734375 231.42710876464844 "Thus, a varlist might look like this: (thread (needles 3)). In this case,
in a let expression, Emacs binds the symbol thread to an initial value of
nil, and binds the symbol needles to an initial value of 3.
" 4 0) (89.99810791015625 238.28887939453125 449.45269775390625 263.4670715332031 "When you write a let expression, what you do is put the appropriate
expressions in the slots of the let expression template.
" 5 0) (89.99835205078125 270.3289794921875 449.3871765136719 295.5071716308594 "If the varlist is composed of two-element lists, as is often the case, the
template for the let expression looks like this:
" 6 0) (111.59841918945312 306.69512939453125 207.2140350341797 352.9839172363281 "(let ((variable value)
(variable value)
...)
body...)
" 7 0) (89.99833679199219 384.24176025390625 273.5873718261719 397.3573303222656 "3.6.2 Sample let Expression
" 8 0) (89.99783325195312 411.5690002441406 449.2343444824219 448.7471923828125 "The following expression creates and gives initial values to the two vari-
ables zebra and tiger. The body of the let expression is a list which calls
the message function.
" 9 0) (111.59782409667969 459.8175354003906 379.4499206542969 506.22393798828125 "(let ((zebra ’stripes)
(tiger ’fierce))
(message \"One kind of animal has %s and another is %s.\"
zebra tiger))
" 10 0) (104.99815368652344 513.6890258789062 387.94696044921875 526.9872436523438 "Here, the varlist is ((zebra ’stripes) (tiger ’fierce)).
" 11 0) (89.99758911132812 533.72900390625 449.4306640625 630.7872314453125 "The two variables are zebra and tiger. Each variable is the first element
of a two-element list and each value is the second element of its two-element
list. In the varlist, Emacs binds the variable zebra to the value stripes, and
binds the variable tiger to the value fierce. In this example, both values
are symbols preceded by a quote. The values could just as well have been
another list or a string. The body of the let follows after the list holding the
variables. In this example, the body is a list that uses the message function
to print a string in the echo area.
" 12 0)) (57 (90.0 47.60907745361328 449.7485656738281 60.90726852416992 "The if Special Form
39
" 0 0) (89.9990234375 80.12909698486328 449.4104309082031 117.42728424072266 "You may evaluate the example in the usual fashion, by placing the cur-
sor after the last parenthesis and typing C-x C-e. When you do this, the
following will appear in the echo area:
" 1 0) (89.99917602539062 122.97763061523438 449.27899169921875 182.8273162841797 "\"One kind of animal has stripes and another is fierce.\"
As we have seen before, the message function prints its first argument,
except for ‘%s’. In this example, the value of the variable zebra is printed
at the location of the first ‘%s’ and the value of the variable tiger is printed
at the location of the second ‘%s’.
" 2 0) (89.99952697753906 198.12188720703125 399.14581298828125 211.23744201660156 "3.6.3 Uninitialized Variables in a let Statement
" 3 0) (90.00033569335938 219.80914306640625 449.35638427734375 257.1073303222656 "If you do not bind the variables in a let statement to specific initial
values, they will automatically be bound to an initial value of nil, as in the
following expression:
" 4 0) (90.00006103515625 262.6576843261719 449.3996276855469 388.26739501953125 "(let ((birch 3)
pine
fir
(oak ’some))
(message
\"Here are %d variables with %s, %s, and %s value.\"
birch pine fir oak))
Here, the varlist is ((birch 3) pine fir (oak ’some)).
If you evaluate this expression in the usual way, the following will appear
in your echo area:
" 5 0) (89.99850463867188 393.8177490234375 449.52935791015625 528.0675048828125 "\"Here are 3 variables with nil, nil, and some value.\"
In this example, Emacs binds the symbol birch to the number 3, binds the
symbols pine and fir to nil, and binds the symbol oak to the value some.
Note that in the first part of the let, the variables pine and fir stand
alone as atoms that are not surrounded by parentheses; this is because they
are being bound to nil, the empty list. But oak is bound to some and so
is a part of the list (oak ’some). Similarly, birch is bound to the number
3 and so is in a list with that number. (Since a number evaluates to itself,
the number does not need to be quoted. Also, the number is printed in the
message using a ‘%d’ rather than a ‘%s’.) The four variables as a group are
put into a list to delimit them from the body of the let.
" 6 0) (89.99874877929688 546.9805297851562 263.7757263183594 561.353759765625 "3.7 The if Special Form
" 7 0) (89.9986572265625 569.6092529296875 449.37689208984375 630.7874755859375 "A third special form, in addition to defun and let, is the conditional if.
This form is used to instruct the computer to make decisions. You can write
function definitions without using if, but it is used often enough, and is
important enough, to be included here. It is used, for example, in the code
for the function beginning-of-buffer.
" 8 0)) (58 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "40
Chapter 3: How To Write Function Definitions
" 0 0) (89.9993896484375 77.48908233642578 449.3011169433594 126.66727447509766 "The basic idea behind an if, is that “if a test is true, then an expression
is evaluated.” If the test is not true, the expression is not evaluated. For
example, you might make a decision such as, “if it is warm and sunny, then
go to the beach!”
" 1 0) (90.00003051757812 133.2890625 449.541015625 182.46726989746094 "An if expression written in Lisp does not use the word ‘then’; the test
and the action are the second and third elements of the list whose first
element is if. Nonetheless, the test part of an if expression is often called
the if-part and the second argument is often called the then-part.
" 2 0) (89.99954223632812 189.08905029296875 449.38836669921875 238.2672576904297 "Also, when an if expression is written, the true-or-false-test is usually
written on the same line as the symbol if, but the action to carry out if the
test is true, the “then-part”, is written on the second and subsequent lines.
This makes the if expression easier to read.
" 3 0) (111.59953308105469 249.2152099609375 266.74188232421875 270.6639709472656 "(if true-or-false-test
action-to-carry-out-if-test-is-true)
" 4 0) (89.99954223632812 278.12908935546875 449.3883056640625 303.3072814941406 "The true-or-false-test will be an expression that is evaluated by the Lisp
interpreter.
" 5 0) (89.99847412109375 309.9290771484375 449.3443908691406 347.2272644042969 "Here is an example that you can evaluate in the usual manner. The test is
whether the number 5 is greater than the number 4. Since it is, the message
‘5 is greater than 4!’ will be printed.
" 6 0) (111.59870910644531 358.1752014160156 347.1021728515625 379.6239929199219 "(if (> 5 4)
; if-part
(message \"5 is greater than 4!\"))
; then-part
" 7 0) (89.99832153320312 387.569091796875 449.27825927734375 412.8672790527344 "(The function > tests whether its first argument is greater than its second
argument and returns true if it is.)
" 8 0) (89.99765014648438 419.4891052246094 449.45269775390625 480.66729736328125 "Of course, in actual use, the test in an if expression will not be fixed
for all time as it is by the expression (> 5 4). Instead, at least one of the
variables used in the test will be bound to a value that is not known ahead
of time. (If the value were known ahead of time, we would not need to run
the test!)
" 9 0) (89.99691772460938 487.28912353515625 449.77838134765625 548.3473510742188 "For example, the value may be bound to an argument of a function defi-
nition. In the following function definition, the character of the animal is a
value that is passed to the function. If the value bound to characteristic
is fierce, then the message, ‘It’s a tiger!’ will be printed; otherwise, nil
will be returned.
" 10 0) (111.59686279296875 559.4176635742188 383.8551025390625 630.6640625 "(defun type-of-animal (characteristic)
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger.\"
(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")))
" 11 0)) (59 (90.0 47.60907745361328 449.5629577636719 60.90726852416992 "The type-of-animal Function in Detail
41
" 0 0) (89.99929809570312 79.76905059814453 449.2897033691406 117.0672378540039 "If you are reading this inside of GNU Emacs, you can evaluate the function
definition in the usual way to install it in Emacs, and then you can evaluate
the following two expressions to see the results:
" 1 0) (111.59971618652344 122.25759887695312 224.23960876464844 131.22398376464844 "(type-of-animal ’fierce)
" 2 0) (111.5997085571289 147.21762084960938 219.56813049316406 156.1840057373047 "(type-of-animal ’zebra)
" 3 0) (89.99862670898438 170.24908447265625 449.1593322753906 207.4272918701172 "When you evaluate (type-of-animal ’fierce), you will see the following
message printed in the echo area: \"It’s a tiger!\"; and when you evaluate
(type-of-animal ’zebra) you will see nil printed in the echo area.
" 4 0) (89.9989013671875 221.5218505859375 374.209228515625 234.6374053955078 "3.7.1 The type-of-animal Function in Detail
" 5 0) (89.998779296875 242.9691162109375 449.4207763671875 308.5874328613281 "Let’s look at the type-of-animal function in detail.
The function definition for type-of-animal was written by filling the
slots of two templates, one for a function definition as a whole, and a second
for an if expression.
The template for every function that is not interactive is:
" 6 0) (104.99870300292969 313.8953857421875 416.442138671875 363.6674499511719 "(defun name-of-function (argument-list)
\"documentation...\"
body...)
The parts of the function that match this template look like this:
" 7 0) (89.99978637695312 368.9779052734375 449.4326477050781 504.7875671386719 "(defun type-of-animal (characteristic)
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger.\"
body: the if expression)
The name of function is type-of-animal; it is passed the value of one
argument.
The argument list is followed by a multi-line documentation
string. The documentation string is included in the example because it is a
good habit to write documentation string for every function definition. The
body of the function definition consists of the if expression.
The template for an if expression looks like this:
" 8 0) (105.00108337402344 509.97552490234375 429.5027160644531 547.3876342773438 "(if true-or-false-test
action-to-carry-out-if-the-test-returns-true)
In the type-of-animal function, the code for the if looks like this:
" 9 0) (105.00122833251953 552.5780029296875 316.1464538574219 589.86767578125 "(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")))
Here, the true-or-false-test is the expression:
" 10 0) (90.00041961669922 595.1780395507812 449.400390625 630.7876586914062 "(equal characteristic ’fierce)
In Lisp, equal is a function that determines whether its first argument is
equal to its second argument. The second argument is the quoted symbol
" 11 0)) (60 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "42
Chapter 3: How To Write Function Definitions
" 0 0) (89.99932861328125 77.48908233642578 449.8138427734375 102.66727447509766 "’fierce and the first argument is the value of the symbol characteristic—
in other words, the argument passed to this function.
" 1 0) (89.999267578125 110.00910186767578 449.5413513183594 171.0673065185547 "In the first exercise of type-of-animal, the argument fierce is passed to
type-of-animal. Since fierce is equal to fierce, the expression, (equal
characteristic ’fierce), returns a value of true. When this happens, the
if evaluates the second argument or then-part of the if: (message \"It’s
tiger!\").
" 2 0) (89.99838256835938 178.40911865234375 449.4090270996094 215.5873260498047 "On the other hand, in the second exercise of type-of-animal, the argu-
ment zebra is passed to type-of-animal. zebra is not equal to fierce, so
the then-part is not evaluated and nil is returned by the if expression.
" 3 0) (89.99838256835938 258.50042724609375 290.74395751953125 272.8609619140625 "3.8 If–then–else Expressions
" 4 0) (89.9981689453125 287.2491455078125 449.3325500488281 360.3073425292969 "An if expression may have an optional third argument, called the else-
part, for the case when the true-or-false-test returns false. When this hap-
pens, the second argument or then-part of the overall if expression is not
evaluated, but the third or else-part is evaluated. You might think of this
as the cloudy day alternative for the decision ‘if it is warm and sunny, then
go to the beach, else read a book!”.
" 5 0) (89.99774169921875 367.649169921875 449.4740905761719 416.8273620605469 "The word “else” is not written in the Lisp code; the else-part of an if
expression comes after the then-part. In the written Lisp, the else-part is
usually written to start on a line of its own and is indented less than the
then-part:
" 6 0) (111.59774017333984 428.37530517578125 300.1712341308594 462.3041076660156 "(if true-or-false-test
action-to-carry-out-if-the-test-returns-true
action-to-carry-out-if-the-test-returns-false)
" 7 0) (89.99734497070312 470.24920654296875 449.4627685546875 495.5473937988281 "For example, the following if expression prints the message ‘4 is not
greater than 5!’ when you evaluate it in the usual way:
" 8 0) (111.59687805175781 507.21533203125 347.1088562011719 541.024169921875 "(if (> 4 5)
; if-part
(message \"5 is greater than 4!\")
; then-part
(message \"4 is not greater than 5!\")) ; else-part
" 9 0) (89.99740600585938 549.0892333984375 449.3863220214844 598.2674560546875 "Note that the different levels of indentation make it easy to distinguish the
then-part from the else-part. (GNU Emacs has several commands that au-
tomatically indent if expressions correctly. See Section 1.1.3, “GNU Emacs
Helps You Type Lists”, page 3.)
" 10 0) (89.997314453125 605.4891967773438 449.3753356933594 630.7874145507812 "We can extend the type-of-animal function to include an else-part by
simply incorporating an additional part to the if expression.
" 11 0)) (61 (90.0 47.60907745361328 449.6175231933594 60.90726852416992 "Truth and Falsehood in Emacs Lisp
43
" 0 0) (89.99917602539062 79.52906036376953 449.3661804199219 128.70726013183594 "You can see the consequences of doing this if you evaluate the following
version of the type-of-animal function definition to install it and then
evaluate the two subsequent expressions to pass different arguments to the
function.
" 1 0) (111.59921264648438 133.77520751953125 383.85723876953125 229.86387634277344 "(defun type-of-animal (characteristic)
; Second version.
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger;
else say it’s not fierce.\"
(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")
(message \"It’s not fierce!\")))
" 2 0) (111.5989761352539 246.33749389648438 224.23887634277344 255.3038787841797 "(type-of-animal ’fierce)
" 3 0) (111.5989761352539 271.2975158691406 219.56739807128906 280.2638854980469 "(type-of-animal ’zebra)
" 4 0) (89.9976806640625 294.0889892578125 449.4304504394531 381.06719970703125 "When you evaluate (type-of-animal ’fierce), you will see the following
message printed in the echo area: \"It’s a tiger!\"; but when you evaluate
(type-of-animal ’zebra), you will see \"It’s not fierce!\".
(Of course, if the characteristic were ferocious, the message \"It’s not
fierce!\" would be printed; and it would be misleading! When you write
code, you need to take into account the possibility that some such argument
will be tested by the if and write your program accordingly.)
" 5 0) (89.99810791015625 396.140380859375 370.0843200683594 410.50091552734375 "3.9 Truth and Falsehood in Emacs Lisp
" 6 0) (89.99664306640625 418.16900634765625 449.47314453125 630.7872924804688 "There is an important aspect to the truth test in an if expression. So
far, we have spoken of ‘true’ and ‘false’ as values of predicates as if they were
new kinds of Emacs Lisp objects. In fact, ‘false’ is just our old friend nil.
Anything else—anything at all—is ‘true’.
The expression that tests for truth is interpreted as true if the result of
evaluating it is a value that is not nil. In other words, the result of the test
is considered true if the value returned is a number such as 47, a string such
as \"hello\", or a symbol (other than nil) such as flowers, or a list, or even
a buffer!
Before illustrating a test for truth, we need an explanation of nil.
In Emacs Lisp, the symbol nil has two meanings. First, it means the
empty list. Second, it means false and is the value returned when a true-or-
false-test tests false. nil can be written as an empty list, (), or as nil. As
far as the Lisp interpreter is concerned, () and nil are the same. Humans,
however, tend to use nil for false and () for the empty list.
In Emacs Lisp, any value that is not nil—is not the empty list—is con-
sidered true. This means that if an evaluation returns something that is not
" 7 0)) (62 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "44
Chapter 3: How To Write Function Definitions
" 0 0) (89.99884033203125 77.48908233642578 449.50787353515625 227.1073455810547 "an empty list, an if expression will test true. For example, if a number is
put in the slot for the test, it will be evaluated and will return itself, since
that is what numbers do when evaluated. In this conditional, the if expres-
sion will test true. The expression tests false only when nil, an empty list,
is returned by evaluating the expression.
You can see this by evaluating the two expressions in the following ex-
amples.
In the first example, the number 4 is evaluated as the test in the if
expression and returns itself; consequently, the then-part of the expression
is evaluated and returned: ‘true’ appears in the echo area. In the second
example, the nil indicates false; consequently, the else-part of the expression
is evaluated and returned: ‘false’ appears in the echo area.
" 1 0) (111.59869384765625 232.53768920898438 153.8319549560547 266.4640197753906 "(if 4
’true
’false)
" 2 0) (89.99874877929688 274.5376281738281 449.2897033691406 360.4272155761719 "(if nil
’true
’false)
Incidentally, if some other useful value is not available for a test that
returns true, then the Lisp interpreter will return the symbol t for true. For
example, the expression (> 5 4) returns t when evaluated, as you can see
by evaluating it in the usual way:
" 3 0) (89.99907684326172 365.8575744628906 392.6931457519531 389.70721435546875 "(> 5 4)
On the other hand, this function returns nil if the test is false.
" 4 0) (111.59896850585938 395.1375732421875 144.47213745117188 404.10394287109375 "(> 4 5)
" 5 0) (89.99890899658203 422.7803039550781 230.6892547607422 437.1535339355469 "3.10 save-excursion
" 6 0) (89.99594116210938 445.2890319824219 449.5833740234375 630.7872314453125 "The save-excursion function is the fourth and final special form that
we will discuss in this chapter.
In Emacs Lisp programs used for editing, the save-excursion function
is very common. It saves the location of point and mark, executes the body
of the function, and then restores point and mark to their previous positions
if their locations were changed. Its primary purpose is to keep the user from
being surprised and disturbed by unexpected movement of point or mark.
Before discussing save-excursion, however, it may be useful first to
review what point and mark are in GNU Emacs. Point is the current location
of the cursor.
Wherever the cursor is, that is point.
More precisely, on
terminals where the cursor appears to be on top of a character, point is
immediately before the character. In Emacs Lisp, point is an integer. The
first character in a buffer is number one, the second is number two, and
so on. The function point returns the current position of the cursor as a
number. Each buffer has its own value for point.
" 7 0)) (63 (90.0 47.60907745361328 449.5309143066406 60.90726852416992 "Template for a save-excursion Expression
45
" 0 0) (89.999755859375 77.48908233642578 449.4543151855469 108.16980743408203 "The mark is another position in the buffer; its value can be set with a
command such as C-⟨
" 1 0) (190.9080047607422 92.75201416015625 207.5880126953125 93.23201751708984 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (190.9199981689453 93.96241760253906 207.4659423828125 101.93253326416016 "SPC
" 3 0) (190.9080047607422 101.3919677734375 207.5880126953125 101.8719711303711 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (89.99887084960938 89.00910186767578 449.5196533203125 168.04981994628906 "⟩ (set-mark-command). If a mark has been set, you
can use the command C-x C-x (exchange-point-and-mark) to cause the
cursor to jump to the mark and set the mark to be the previous position
of point. In addition, if you set another mark, the position of the previous
mark is saved in the mark ring. Many mark positions can be saved this way.
You can jump the cursor to a saved mark by typing C-u C-⟨
" 5 0) (371.14801025390625 152.6319580078125 387.8280029296875 153.11195373535156 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (371.1600036621094 153.84242248535156 387.7059631347656 161.81253051757812 "SPC
" 7 0) (371.14801025390625 161.1519775390625 387.8280029296875 161.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.994873046875 148.88909912109375 449.956298828125 483.3072814941406 "⟩ one or more
times.
The part of the buffer between point and mark is called the region. Nu-
merous commands work on the region, including center-region, count-
lines-region, kill-region, and print-region.
The save-excursion special form saves the locations of point and mark
and restores those positions after the code within the body of the special form
is evaluated by the Lisp interpreter. Thus, if point were in the beginning
of a piece of text and some code moved point to the end of the buffer, the
save-excursion would put point back to where it was before, after the
expressions in the body of the function were evaluated.
In Emacs, a function frequently moves point as part of its internal work-
ings even though a user would not expect this. For example, count-lines-
region moves point. To prevent the user from being bothered by jumps that
are both unexpected and (from the user’s point of view) unnecessary, save-
excursion is often used to keep point and mark in the location expected by
the user. The use of save-excursion is good housekeeping.
To make sure the house stays clean, save-excursion restores the values
of point and mark even if something goes wrong in the code inside of it (or,
to be more precise and to use the proper jargon, “in case of abnormal exit”).
This feature is very helpful.
In addition to recording the values of point and mark, save-excursion
keeps track of the current buffer, and restores it, too. This means you can
write code that will change the buffer and have save-excursion switch you
back to the original buffer. This is how save-excursion is used in append-
to-buffer.
(See Section 4.4, “The Definition of append-to-buffer”,
page 56.)
" 9 0) (89.994873046875 495.3618469238281 403.0967712402344 508.4774169921875 "3.10.1 Template for a save-excursion Expression
" 10 0) (104.99459838867188 516.569091796875 370.936279296875 529.8673095703125 "The template for code using save-excursion is simple:
" 11 0) (89.99346923828125 534.9376831054688 449.4045715332031 630.7872924804688 "(save-excursion
body...)
The body of the function is one or more expressions that will be evaluated
in sequence by the Lisp interpreter. If there is more than one expression
in the body, the value of the last one will be returned as the value of the
save-excursion function. The other expressions in the body are evaluated
only for their side effects; and save-excursion itself is used only for its side
effect (which is restoring the positions of point and mark).
" 12 0)) (64 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "46
Chapter 3: How To Write Function Definitions
" 0 0) (89.99957275390625 79.52906036376953 449.2681884765625 104.8272476196289 "In more detail, the template for a save-excursion expression looks like
this:
" 1 0) (89.99939727783203 109.77761840820312 449.3226013183594 221.5872039794922 "(save-excursion
first-expression-in-body
second-expression-in-body
third-expression-in-body
...
last-expression-in-body)
An expression, of course, may be a symbol on its own or a list.
In Emacs Lisp code, a save-excursion expression often occurs within
the body of a let expression. It looks like this:
" 2 0) (111.59974670410156 226.6551513671875 191.0677947998047 260.4638977050781 "(let varlist
(save-excursion
body...))
" 3 0) (89.99969482421875 275.18023681640625 177.9246826171875 289.540771484375 "3.11 Review
" 4 0) (89.99923706054688 297.32904052734375 449.355712890625 334.5072326660156 "In the last few chapters we have introduced a fair number of functions
and special forms. Here they are described in brief, along with a few similar
functions that have not been mentioned yet.
" 5 0) (89.99917602539062 339.8526611328125 449.5627746582031 411.0760498046875 "eval-last-sexp
Evaluate the last symbolic expression before the current location
of point. The value is printed in the echo area unless the function
is invoked with an argument; in that case, the output is printed
in the current buffer. This command is normally bound to C-x
C-e.
" 6 0) (89.99933624267578 414.56903076171875 449.5079650878906 478.2672119140625 "defun
Define function.
This special form has up to five parts: the
name, a template for the arguments that will be passed to the
function, documentation, an optional interactive declaration,
and the body of the definition.
For example:
" 7 0) (89.99830627441406 483.69757080078125 449.49609375 630.7872314453125 "(defun back-to-indentation ()
\"Move point to first visible character on line.\"
(interactive)
(beginning-of-line 1)
(skip-chars-forward \" \\t\"))
interactive
Declare to the interpreter that the function can be used interac-
tively. This special form may be followed by a string with one
or more parts that pass the information to the arguments of the
function, in sequence. These parts may also tell the interpreter
to prompt for information. Parts of the string are separated by
newlines, ‘\\n’.
" 8 0)) (65 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "Review
47
" 0 0) (147.60000610351562 77.48908233642578 288.6217346191406 90.78726959228516 "Common code characters are:
" 1 0) (147.59974670410156 98.36908721923828 355.07952880859375 111.66727447509766 "b
The name of an existing buffer.
" 2 0) (147.59934997558594 119.12909698486328 341.30096435546875 132.4272918701172 "f
The name of an existing file.
" 3 0) (147.5989532470703 140.00909423828125 449.51861572265625 165.3072967529297 "p
The numeric prefix argument. (Note that this ‘p’ is
lower case.)
" 4 0) (147.59942626953125 172.76910400390625 449.55194091796875 210.0673065185547 "r
Point and the mark, as two numeric arguments,
smallest first. This is the only code letter that spec-
ifies two successive arguments rather than one.
" 5 0) (147.59896850585938 217.52911376953125 449.36614990234375 254.8273162841797 "See section “Code Characters for ‘interactive’” in The GNU
Emacs Lisp Reference Manual, for a complete list of code char-
acters.
" 6 0) (89.99897003173828 262.28912353515625 449.7151184082031 335.4673156738281 "let
Declare that a list of variables is for use within the body of the
let and give them an initial value, either nil or a specified
value; then evaluate the rest of the expressions in the body of
the let and return the value of the last one. Inside the body
of the let, the Lisp interpreter does not see the values of the
variables of the same names that are bound outside of the let.
" 7 0) (147.59890747070312 338.609130859375 209.08262634277344 351.9073181152344 "For example,
" 8 0) (169.19894409179688 359.377685546875 380.4963684082031 418.1440734863281 "(let ((foo (buffer-name))
(bar (buffer-size)))
(message
\"This buffer is %s and has %d characters.\"
foo bar))
" 9 0) (89.99915313720703 427.33282470703125 449.5732727050781 474.6673583984375 "save-excursion
Record the values of point and mark and the current buffer
before evaluating the body of this special form.
Restore the
values of point and mark and buffer afterward.
" 10 0) (147.59910583496094 477.9291687011719 209.08282470703125 491.22735595703125 "For example,
" 11 0) (169.1991424560547 498.6977233886719 399.27691650390625 544.984130859375 "(message \"We are %d characters into this buffer.\"
(- (point)
(save-excursion
(goto-char (point-min)) (point))))
" 12 0) (89.99880981445312 553.2891845703125 449.4642333984375 590.4674072265625 "if
Evaluate the first argument to the function; if it is true, evaluate
the second argument; else evaluate the third argument, if there
is one.
" 13 0) (147.59886169433594 593.6091918945312 449.3445739746094 630.7874145507812 "The if special form is called a conditional. There are other con-
ditionals in Emacs Lisp, but if is perhaps the most commonly
used.
" 14 0)) (66 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "48
Chapter 3: How To Write Function Definitions
" 0 0) (147.59933471679688 80.72907257080078 209.0830535888672 94.02725982666016 "For example,
" 1 0) (169.19937133789062 100.05758666992188 371.13720703125 158.8238983154297 "(if (string-equal
(number-to-string 21)
(substring (emacs-version) 10 12))
(message \"This is version 21 Emacs\")
(message \"This is not version 21 Emacs\"))
" 2 0) (89.99952697753906 165.3726348876953 449.58465576171875 357.9071960449219 "equal
eq
Test whether two objects are the same. equal uses one meaning
of the word ‘same’ and eq uses another: equal returns true if
the two objects have a similar structure and contents, such as
two copies of the same book. On the other hand, eq, returns
true if both arguments are actually the same object.
<
>
<=
>=
The < function tests whether its first argument is smaller than
its second argument. A corresponding function, >, tests whether
the first argument is greater than the second. Likewise, <= tests
whether the first argument is less than or equal to the second
and >= tests whether the first argument is greater than or equal
to the second. In all cases, both arguments must be numbers or
markers (markers indicate positions in buffers).
" 3 0) (90.000732421875 364.692626953125 449.51043701171875 552.7872314453125 "string<
string-lessp
string=
string-equal
The string-lessp function tests whether its first argument is
smaller than the second argument. A shorter, alternative name
for the same function (a defalias) is string<.
The arguments to string-lessp must be strings or symbols;
the ordering is lexicographic, so case is significant. The print
names of symbols are used instead of the symbols themselves.
An empty string, ‘\"\"’, a string with no characters in it, is smaller
than any string of characters.
string-equal provides the corresponding test for equality. Its
shorter, alternative name is string=. There are no string test
functions that correspond to >, >=, or <=.
" 4 0) (90.00051879882812 557.72900390625 449.6075134277344 630.7872314453125 "message
Print a message in the echo area. The first argument is a string
that can contain ‘%s’, ‘%d’, or ‘%c’ to print the value of arguments
that follow the string. The argument used by ‘%s’ must be a
string or a symbol; the argument used by ‘%d’ must be a number.
The argument used by ‘%c’ must be an ascii code number; it will
be printed as the character with that ascii code.
" 5 0)) (67 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "Review
49
" 0 0) (90.0 79.33271789550781 449.48699951171875 162.5472869873047 "setq
set
The setq function sets the value of its first argument to the
value of the second argument. The first argument is automati-
cally quoted by setq. It does the same for succeeding pairs of
arguments. Another function, set, takes only two arguments
and evaluates both of them before setting the value returned by
its first argument to the value returned by its second argument.
" 1 0) (90.00051879882812 174.4927520751953 449.47625732421875 197.9473114013672 "buffer-name
Without an argument, return the name of the buffer, as a string.
" 2 0) (90.0 204.2527618408203 449.4541320800781 239.5873260498047 "buffer-file-name
Without an argument, return the name of the file the buffer is
visiting.
" 3 0) (89.9998550415039 251.6527862548828 449.5303955078125 286.9873352050781 "current-buffer
Return the buffer in which Emacs is active; it may not be the
buffer that is visible on the screen.
" 4 0) (89.9993896484375 299.05279541015625 449.5411376953125 346.3873596191406 "other-buffer
Return the most recently selected buffer (other than the buffer
passed to other-buffer as an argument and other than the
current buffer).
" 5 0) (89.99929809570312 358.33282470703125 449.51898193359375 393.7961730957031 "switch-to-buffer
Select a buffer for Emacs to be active in and display it in the
current window so users can look at it. Usually bound to C-x b.
" 6 0) (89.99923706054688 405.7327880859375 449.5954284667969 441.1873474121094 "set-buffer
Switch Emacs’ attention to a buffer on which programs will run.
Don’t alter what the window is showing.
" 7 0) (89.99992370605469 453.1328125 407.3122253417969 476.58734130859375 "buffer-size
Return the number of characters in the current buffer.
" 8 0) (90.00003051757812 486.80914306640625 449.39996337890625 523.9873657226562 "point
Return the value of the current position of the cursor, as an
integer counting the number of characters from the beginning of
the buffer.
" 9 0) (90.00067138671875 536.052734375 449.4986267089844 571.3873291015625 "point-min
Return the minimum permissible value of point in the current
buffer. This is 1, unless narrowing is in effect.
" 10 0) (90.00077819824219 583.4527587890625 449.47662353515625 630.787353515625 "point-max
Return the value of the maximum permissible value of point in
the current buffer. This is the end of the buffer, unless narrowing
is in effect.
" 11 0)) (68 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "50
Chapter 3: How To Write Function Definitions
" 0 0) (89.99932861328125 94.10033416748047 191.3380126953125 108.46088409423828 "3.12 Exercises
" 1 0) (98.99920654296875 114.20905303955078 449.69317626953125 178.2672576904297 "• Write a non-interactive function that doubles the value of its argument,
a number. Make that function interactive.
• Write a function that tests whether the current value of fill-column
is greater than the argument passed to the function, and if so, prints an
appropriate message.
" 2 0)) (69 (90.0 47.60907745361328 449.6835632324219 60.90726852416992 "Finding More Information
51
" 0 0) (89.99990844726562 75.14844512939453 385.9106140136719 92.38106536865234 "4 A Few Buffer–Related Functions
" 1 0) (89.99786376953125 106.64917755126953 449.40869140625 191.70738220214844 "In this chapter we study in detail several of the functions used in GNU
Emacs. This is called a “walk-through”. These functions are used as ex-
amples of Lisp code, but are not imaginary examples; with the exception of
the first, simplified function definition, these functions show the actual code
used in GNU Emacs. You can learn a great deal from these definitions. The
functions described here are all related to buffers. Later, we will study other
functions.
" 2 0) (89.9979248046875 210.740478515625 304.238525390625 225.10101318359375 "4.1 Finding More Information
" 3 0) (89.99746704101562 233.60919189453125 449.29949951171875 288.64990234375 "In this walk-through, I will describe each new function as we come to it,
sometimes in detail and sometimes briefly. If you are interested, you can get
the full documentation of any Emacs Lisp function at any time by typing
C-h f and then the name of the function (and then ⟨
" 4 0) (348.2279968261719 272.75201416015625 366.3479919433594 273.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (348.239990234375 274.0824279785156 366.3401184082031 282.0525207519531 "RET
" 6 0) (348.2279968261719 281.3919677734375 366.3479919433594 281.8719787597656 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (89.999755859375 269.48907470703125 449.7926940917969 312.52978515625 "⟩). Similarly, you
can get the full documentation for a variable by typing C-h v and then the
name of the variable (and then ⟨
" 8 0) (244.42800903320312 296.75201416015625 262.5480041503906 297.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (244.44000244140625 297.9624328613281 262.54010009765625 305.9325256347656 "RET
" 10 0) (244.42800903320312 305.27203369140625 262.5480041503906 305.7520446777344 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (90.00039672851562 293.36907958984375 449.4324951171875 351.0498046875 "⟩).
In versions 20 and higher, when a function is written in Emacs Lisp,
describe-function will also tell you the location of the function definition.
If you move point over the file name and press the ⟨
" 12 0) (341.7480163574219 335.2720031738281 359.8680114746094 335.75201416015625 "<image: None, width: 1, height: 1, bpc: 1>" 13 1) (341.760009765625 336.482421875 359.8601379394531 344.4525146484375 "RET
" 14 0) (341.7480163574219 343.7919921875 359.8680114746094 344.2720031738281 "<image: None, width: 1, height: 1, bpc: 1>" 15 1) (89.99880981445312 331.5290832519531 449.82550048828125 478.60980224609375 "⟩ key, which is this
case means help-follow rather than ‘return’ or ‘enter’, Emacs will take you
directly to the function definition.
More generally, if you want to see a function in its original source file,
you can use the find-tags function to jump to it. find-tags works with
a wide variety of languages, not just Lisp, and C, and it works with non-
programming text as well. For example, find-tags will jump to the various
nodes in the Texinfo source file of this document.
The find-tags function depends on ‘tags tables’ that record the locations
of the functions, variables, and other items to which find-tags jumps.
To use the find-tags command, type M-. (i.e., type the ⟨
" 16 0) (381.1080017089844 462.7120056152344 406.4280090332031 463.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 17 1) (381.1199951171875 464.04241943359375 406.406494140625 472.01251220703125 "META
" 18 0) (381.1080017089844 471.35198974609375 406.4280090332031 471.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 19 1) (90.00018310546875 459.0890808105469 450.0108337402344 490.48980712890625 "⟩ key and
the period key at the same time, or else type the ⟨
" 20 0) (337.4280090332031 474.7120056152344 354.1080017089844 475.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 21 1) (337.44000244140625 475.92242431640625 353.9859619140625 483.89251708984375 "ESC
" 22 0) (337.4280090332031 483.35198974609375 354.1080017089844 483.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 23 1) (90.00003051757812 470.9690856933594 449.90167236328125 526.3698120117188 "⟩ key and then type
the period key), and then, at the prompt, type in the name of the function
whose source code you want to see, such as mark-whole-buffer, and then
type ⟨
" 24 0) (118.30799865722656 510.59197998046875 136.42799377441406 511.0719909667969 "<image: None, width: 1, height: 1, bpc: 1>" 25 1) (118.31999969482422 511.8024597167969 136.4201202392578 519.7725830078125 "RET
" 26 0) (118.30799865722656 519.1119995117188 136.42799377441406 519.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 27 1) (90.00003051757812 507.2091064453125 449.4978332519531 549.8897705078125 "⟩. Emacs will switch buffers and display the source code for the
function on your screen. To switch back to your current buffer, type C-x b
⟨
" 28 0) (92.86800384521484 534.4719848632812 110.98800659179688 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 29 1) (92.87999725341797 535.6824340820312 110.98011779785156 543.652587890625 "RET
" 30 0) (92.86800384521484 543.1119995117188 110.98800659179688 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 31 1) (110.5199966430664 531.089111328125 248.74658203125 550.2498168945312 "⟩. (On some keyboards, the ⟨
" 32 0) (248.0279998779297 534.4719848632812 273.3479919433594 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 33 1) (248.0399932861328 535.6824340820312 273.3265075683594 543.652587890625 "META
" 34 0) (248.0279998779297 543.1119995117188 273.3479919433594 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 35 1) (272.760009765625 530.7290649414062 354.5865783691406 550.2498168945312 "⟩ key is labelled ⟨
" 36 0) (353.8680114746094 534.4719848632812 371.02801513671875 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 37 1) (353.8800048828125 535.6824340820312 370.9014587402344 543.652587890625 "ALT
" 38 0) (353.8680114746094 543.1119995117188 371.02801513671875 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 39 1) (89.99786376953125 531.089111328125 450.0957946777344 630.787353515625 "⟩.)
Depending on how the initial default values of your copy of Emacs are
set, you may also need to specify the location of your ‘tags table’, which
is a file called ‘TAGS’. For example, if you are interested in Emacs sources,
the tags table you will most likely want, if it has already been created for
you, will be in a subdirectory of the ‘/usr/local/share/emacs/’ direc-
tory; thus you would use the M-x visit-tags-table command and spec-
ify a pathname such as ‘/usr/local/share/emacs/21.0.100/lisp/TAGS’
" 40 0)) (70 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "52
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.99884033203125 77.48908233642578 449.21343994140625 102.66727447509766 "or ‘/usr/local/src/emacs/lisp/TAGS’. If the tags table has not already
been created, you will have to create it yourself.
" 1 0) (89.9990234375 107.12909698486328 449.3988342285156 156.1873016357422 "To create a ‘TAGS’ file in a specific directory, switch to that directory
in Emacs using M-x cd command, or list the directory with C-x d (dired).
Then run the compile command, with etags *.el as the command to exe-
cute
" 2 0) (111.59941864013672 164.85763549804688 252.54220581054688 173.8240203857422 "M-x compile RET etags *.el RET
" 3 0) (89.99945068359375 178.52911376953125 449.1486511230469 203.8273162841797 "For more information, see Section 12.5, “Create Your Own ‘TAGS’ File”,
page 163.
" 4 0) (89.99884033203125 208.04913330078125 449.3875732421875 245.2273406982422 "After you become more familiar with Emacs Lisp, you will find that you
will frequently use find-tags to navigate your way around source code; and
you will create your own ‘TAGS’ tables.
" 5 0) (89.99884033203125 249.56903076171875 449.3661193847656 370.3872375488281 "Incidentally, the files that contain Lisp code are conventionally called
libraries. The metaphor is derived from that of a specialized library, such as
a law library or an engineering library, rather than a general library. Each
library, or file, contains functions that relate to a particular topic or activity,
such as ‘abbrev.el’ for handling abbreviations and other typing shortcuts,
and ‘help.el’ for on-line help. (Sometimes several libraries provide code
for a single activity, as the various ‘rmail...’ files provide code for reading
electronic mail.) In The GNU Emacs Manual, you will see sentences such as
“The C-h p command lets you search the standard Emacs Lisp libraries by
topic keywords.”
" 6 0) (89.99909973144531 401.1803283691406 426.8679504394531 415.5535583496094 "4.2 A Simplified beginning-of-buffer Definition
" 7 0) (89.99945068359375 426.9290466308594 449.3887634277344 488.1160583496094 "The beginning-of-buffer command is a good function to start with
since you are likely to be familiar with it and it is easy to understand. Used
as an interactive command, beginning-of-buffer moves the cursor to the
beginning of the buffer, leaving the mark at the previous position.
It is
generally bound to M-<.
" 8 0) (89.99887084960938 492.32904052734375 449.34490966796875 553.3872680664062 "In this section, we will discuss a shortened version of the function that
shows how it is most frequently used.
This shortened function works as
written, but it does not contain the code for a complex option. In another
section, we will describe the entire function. (See Section 5.3, “Complete
Definition of beginning-of-buffer”, page 69.)
" 9 0) (89.99856567382812 557.7290649414062 449.453125 630.7872924804688 "Before looking at the code, let’s consider what the function definition has
to contain: it must include an expression that makes the function interactive
so it can be called by typing M-x beginning-of-buffer or by typing a
keychord such as C-<; it must include code to leave a mark at the original
position in the buffer; and it must include code to move the cursor to the
beginning of the buffer.
" 10 0)) (71 (90.0 47.60907745361328 449.5094299316406 60.90726852416992 "A Simplified beginning-of-buffer Definition
53
" 0 0) (105.00076293945312 80.36908721923828 420.15325927734375 93.66727447509766 "Here is the complete text of the shortened version of the function:
" 1 0) (90.00039672851562 99.57760620117188 449.3782043457031 277.2670593261719 "(defun simplified-beginning-of-buffer ()
\"Move point to the beginning of the buffer;
leave mark at previous position.\"
(interactive)
(push-mark)
(goto-char (point-min)))
Like all function definitions, this definition has five parts following the
special form defun:
1. The name: in this example, simplified-beginning-of-buffer.
2. A list of the arguments: in this example, an empty list, (),
3. The documentation string.
4. The interactive expression.
5. The body.
" 2 0) (89.99948120117188 282.56884765625 449.48712158203125 385.3870544433594 "In this function definition, the argument list is empty; this means that this
function does not require any arguments. (When we look at the definition
for the complete function, we will see that it may be passed an optional
argument.)
The interactive expression tells Emacs that the function is intended to be
used interactively. In this example, interactive does not have an argument
because simplified-beginning-of-buffer does not require one.
The body of the function consists of the two lines:
" 3 0) (89.99844360351562 391.1773986816406 449.5838317871094 636.6495971679688 "(push-mark)
(goto-char (point-min))
The first of these lines is the expression, (push-mark). When this ex-
pression is evaluated by the Lisp interpreter, it sets a mark at the current
position of the cursor, wherever that may be. The position of this mark is
saved in the mark ring.
The next line is (goto-char (point-min)). This expression jumps the
cursor to the minimum point in the buffer, that is, to the beginning of the
buffer (or to the beginning of the accessible portion of the buffer if it is
narrowed. See Chapter 6, “Narrowing and Widening”, page 77.)
The push-mark command sets a mark at the place where the cursor was
located before it was moved to the beginning of the buffer by the (goto-
char (point-min)) expression. Consequently, you can, if you wish, go back
to where you were originally by typing C-x C-x.
That is all there is to the function definition!
When you are reading code such as this and come upon an unfamiliar
function, such as goto-char, you can find out what it does by using the
describe-function command. To use this command, type C-h f and then
type in the name of the function and press ⟨
" 4 0) (300.947998046875 620.8720092773438 319.0679931640625 621.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (300.9599914550781 622.0823974609375 319.06011962890625 630.0525512695312 "RET
" 6 0) (300.947998046875 629.3919677734375 319.0679931640625 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (318.6000061035156 617.4890747070312 450.3489074707031 636.289794921875 "⟩. The describe-function
" 8 0)) (72 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "54
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.9993896484375 77.48908233642578 449.35546875 102.66727447509766 "command will print the function’s documentation string in a ‘*Help*’ win-
dow. For example, the documentation for goto-char is:
" 1 0) (89.99880981445312 108.81759643554688 449.3445739746094 188.9297637939453 "One arg, a number.
Set point to that number.
Beginning of buffer is position (point-min),
end is (point-max).
(The prompt for describe-function will offer you the symbol under or
preceding the cursor, so you can save typing by positioning the cursor right
over or after the function and then typing C-h f ⟨
" 2 0) (327.1080017089844 173.1519775390625 345.2279968261719 173.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 3 1) (327.1199951171875 174.36244201660156 345.2201232910156 182.33255004882812 "RET
" 4 0) (327.1080017089844 181.6719970703125 345.2279968261719 182.15199279785156 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (89.99908447265625 169.76904296875 449.6611022949219 233.94725036621094 "⟩.)
The end-of-buffer function definition is written in the same way as
the beginning-of-buffer definition except that the body of the function
contains the expression (goto-char (point-max)) in place of (goto-char
(point-min)).
" 6 0) (89.99909210205078 254.90032958984375 371.3376159667969 269.2735595703125 "4.3 The Definition of mark-whole-buffer
" 7 0) (89.999267578125 278.1290283203125 449.4877014160156 381.5472106933594 "The mark-whole-buffer function is no harder to understand than the
simplified-beginning-of-buffer function. In this case, however, we will
look at the complete function, not a shortened version.
The mark-whole-buffer function is not as commonly used as the
beginning-of-buffer function, but is useful nonetheless: it marks a whole
buffer as a region by putting point at the beginning and a mark at the end
of the buffer. It is generally bound to C-x h.
In GNU Emacs 20, the code for the complete function looks like this:
" 8 0) (90.00177001953125 387.69757080078125 449.4015808105469 487.6272277832031 "(defun mark-whole-buffer ()
\"Put point at beginning and mark at end of buffer.\"
(interactive)
(push-mark (point))
(push-mark (point-max))
(goto-char (point-min)))
Like all other functions, the mark-whole-buffer function fits into the
template for a function definition. The template looks like this:
" 9 0) (90.00222778320312 493.7751770019531 449.6968078613281 630.7872314453125 "(defun name-of-function (argument-list)
\"documentation...\"
(interactive-expression...)
body...)
Here is how the function works: the name of the function is mark-whole-
buffer; it is followed by an empty argument list, ‘()’, which means that the
function does not require arguments. The documentation comes next.
The next line is an (interactive) expression that tells Emacs that
the function will be used interactively.
These details are similar to the
simplified-beginning-of-buffer function described in the previous sec-
tion.
" 10 0)) (73 (90.0 47.60907745361328 449.6732482910156 60.90726852416992 "Body of mark-whole-buffer
55
" 0 0) (90.00057983398438 78.2418212890625 297.62017822265625 91.35738372802734 "4.3.1 Body of mark-whole-buffer
" 1 0) (90.00100708007812 100.16907501220703 449.3463134765625 125.4672622680664 "The body of the mark-whole-buffer function consists of three lines of
code:
" 2 0) (89.99725341796875 131.13760375976562 449.5634460449219 445.369873046875 "(push-mark (point))
(push-mark (point-max))
(goto-char (point-min))
The first of these lines is the expression, (push-mark (point)).
This line does exactly the same job as the first line of the body of
the simplified-beginning-of-buffer function, which is written (push-
mark). In both cases, the Lisp interpreter sets a mark at the current position
of the cursor.
I don’t know why the expression in mark-whole-buffer is written (push-
mark (point)) and the expression in beginning-of-buffer is written
(push-mark). Perhaps whoever wrote the code did not know that the ar-
guments for push-mark are optional and that if push-mark is not passed an
argument, the function automatically sets mark at the location of point by
default. Or perhaps the expression was written so as to parallel the struc-
ture of the next line. In any case, the line causes Emacs to determine the
position of point and set a mark there.
The next line of mark-whole-buffer is (push-mark (point-max). This
expression sets a mark at the point in the buffer that has the highest number.
This will be the end of the buffer (or, if the buffer is narrowed, the end of the
accessible portion of the buffer. See Chapter 6, “Narrowing and Widening”,
page 77, for more about narrowing.)
After this mark has been set, the
previous mark, the one set at point, is no longer set, but Emacs remembers
its position, just as all other recent marks are always remembered. This
means that you can, if you wish, go back to that position by typing C-u
C-⟨
" 3 0) (104.38800048828125 429.9519958496094 121.06800079345703 430.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (104.4000015258789 431.1624450683594 120.9459457397461 439.1325378417969 "SPC
" 5 0) (104.38800048828125 438.47198486328125 121.06800079345703 438.9519958496094 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99981689453125 426.2090759277344 449.3128356933594 466.5072937011719 "⟩ twice.
(In GNU Emacs 21, the (push-mark (point-max) is slightly more com-
plicated than shown here. The line reads
" 7 0) (89.99786376953125 472.2976379394531 449.976318359375 630.787353515625 "(push-mark (point-max) nil t)
(The expression works nearly the same as before.
It sets a mark at the
highest numbered place in the buffer that it can. However, in this version,
push-mark has two additional arguments. The second argument to push-
mark is nil. This tells the function it should display a message that says
‘Mark set’ when it pushes the mark. The third argument is t. This tells
push-mark to activate the mark when Transient Mark mode is turned on.
Transient Mark mode highlights the currently active region. It is usually
turned off.)
Finally, the last line of the function is (goto-char (point-min))). This
is written exactly the same way as it is written in beginning-of-buffer.
The expression moves the cursor to the minimum point in the buffer, that is,
to the beginning of the buffer (or to the beginning of the accessible portion
" 8 0)) (74 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "56
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.99887084960938 77.48908233642578 449.39886474609375 114.66727447509766 "of the buffer). As a result of this, point is placed at the beginning of the
buffer and mark is set at the end of the buffer. The whole buffer is, therefore,
the region.
" 1 0) (89.99887084960938 141.5003662109375 363.90606689453125 155.8735809326172 "4.4 The Definition of append-to-buffer
" 2 0) (89.99874877929688 166.1690673828125 449.48590087890625 215.34727478027344 "The append-to-buffer command is very nearly as simple as the mark-
whole-buffer command. What it does is copy the region (that is, the part
of the buffer between point and mark) from the current buffer to a specified
buffer.
" 3 0) (89.99859619140625 218.60906982421875 450.0857238769531 303.6672668457031 "The append-to-buffer command uses the insert-buffer-substring
function to copy the region. insert-buffer-substring is described by its
name: it takes a string of characters from part of a buffer, a “substring”, and
inserts them into another buffer. Most of append-to-buffer is concerned
with setting up the conditions for insert-buffer-substring to work: the
code must specify both the buffer to which the text will go and the region
that will be copied. Here is the complete text of the function:
" 4 0) (111.59902954101562 311.2575988769531 360.5087585449219 345.06396484375 "(defun append-to-buffer (buffer start end)
\"Append to specified buffer the text of the region.
It is inserted into that buffer before its point.
" 5 0) (111.59835815429688 353.2575988769531 388.7680358886719 449.4641418457031 "When calling from a program, give three arguments:
a buffer or the name of one, and two character numbers
specifying the portion of the current buffer to be copied.\"
(interactive \"BAppend to buffer: \\nr\")
(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
" 6 0) (89.99880981445312 453.3292236328125 449.32196044921875 478.6274108886719 "The function can be understood by looking at it as a series of filled-in
templates.
" 7 0) (89.99908447265625 481.88922119140625 449.3765869140625 507.1874084472656 "The outermost template is for the function definition. In this function,
it looks like this (with several slots filled in):
" 8 0) (111.59933471679688 514.7777709960938 308.9515075683594 561.064208984375 "(defun append-to-buffer (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
body...)
" 9 0) (89.99948120117188 565.0491943359375 449.4534912109375 602.2274169921875 "The first line of the function includes its name and three arguments. The
arguments are the buffer to which the text will be copied, and the start
and end of the region in the current buffer that will be copied.
" 10 0) (89.99887084960938 605.4892578125 449.4425354003906 630.7874755859375 "The next part of the function is the documentation, which is clear and
complete.
" 11 0)) (75 (90.0 47.60907745361328 449.6504821777344 60.90726852416992 "The Body of append-to-buffer
57
" 0 0) (89.99981689453125 78.2418212890625 413.8818054199219 91.35738372802734 "4.4.1 The append-to-buffer Interactive Expression
" 1 0) (89.99908447265625 101.60907745361328 449.7373962402344 150.7872772216797 "Since the append-to-buffer function will be used interactively, the func-
tion must have an interactive expression. (For a review of interactive,
see Section 3.3, “Making a Function Interactive”, page 33.) The expression
reads as follows:
" 2 0) (89.99609375 158.01760864257812 449.4083251953125 323.5873107910156 "(interactive \"BAppend to buffer: \\nr\")
This expression has an argument inside of quotation marks and that argu-
ment has two parts, separated by ‘\\n’.
The first part is ‘BAppend to buffer: ’. Here, the ‘B’ tells Emacs to ask
for the name of the buffer that will be passed to the function. Emacs will
ask for the name by prompting the user in the minibuffer, using the string
following the ‘B’, which is the string ‘Append to buffer: ’.
Emacs then
binds the variable buffer in the function’s argument list to the specified
buffer.
The newline, ‘\\n’, separates the first part of the argument from the second
part. It is followed by an ‘r’ that tells Emacs to bind the two arguments
that follow the symbol buffer in the function’s argument list (that is, start
and end) to the values of point and mark.
" 3 0) (89.99641418457031 343.5618591308594 321.0094909667969 356.67742919921875 "4.4.2 The Body of append-to-buffer
" 4 0) (89.99420166015625 367.0491027832031 449.4703063964844 484.3872985839844 "The body of the append-to-buffer function begins with let.
As we have seen before (see Section 3.6, “let”, page 36), the purpose of
a let expression is to create and give initial values to one or more variables
that will only be used within the body of the let. This means that such
a variable will not be confused with any variable of the same name outside
the let expression.
We can see how the let expression fits into the function as a whole
by showing a template for append-to-buffer with the let expression in
outline:
" 5 0) (111.59420013427734 491.6176452636719 308.94635009765625 550.384033203125 "(defun append-to-buffer (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
(let ((variable value))
body...)
" 6 0) (104.99437713623047 554.0091552734375 291.63775634765625 567.307373046875 "The let expression has three elements:
" 7 0) (95.87387084960938 571.1691284179688 191.51376342773438 584.4673461914062 "1. The symbol let;
" 8 0) (95.87383270263672 588.3291015625 449.2298278808594 613.6273193359375 "2. A varlist containing, in this case, a single two-element list, (variable
value);
" 9 0) (95.87357330322266 617.4891357421875 265.2915954589844 630.787353515625 "3. The body of the let expression.
" 10 0)) (76 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "58
Chapter 4: A Few Buffer–Related Functions
" 0 0) (104.9993896484375 86.24909210205078 398.3338623046875 99.54727935791016 "In the append-to-buffer function, the varlist looks like this:
" 1 0) (111.59976196289062 111.21762084960938 228.67115783691406 120.18400573730469 "(oldbuf (current-buffer))
" 2 0) (89.99960327148438 128.00909423828125 449.46478271484375 177.1873016357422 "In this part of the let expression, the one variable, oldbuf, is bound to the
value returned by the (current-buffer) expression. The variable, oldbuf,
is used to keep track of the buffer in which you are working and from which
you will copy.
" 3 0) (89.99981689453125 184.52911376953125 449.464599609375 233.7073211669922 "The element or elements of a varlist are surrounded by a set of parentheses
so the Lisp interpreter can distinguish the varlist from the body of the let.
As a consequence, the two-element list within the varlist is surrounded by a
circumscribing set of parentheses. The line looks like this:
" 4 0) (111.60049438476562 245.37765502929688 261.50067138671875 266.8240051269531 "(let ((oldbuf (current-buffer)))
... )
" 5 0) (89.99920654296875 274.88909912109375 449.2578125 324.0672912597656 "The two parentheses before oldbuf might surprise you if you did not realize
that the first parenthesis before oldbuf marks the boundary of the varlist
and the second parenthesis marks the beginning of the two-element list,
(oldbuf (current-buffer)).
" 6 0) (89.99931335449219 357.60186767578125 351.45758056640625 370.7174377441406 "4.4.3 save-excursion in append-to-buffer
" 7 0) (89.99945068359375 385.40911865234375 449.45306396484375 410.7073059082031 "The body of the let expression in append-to-buffer consists of a save-
excursion expression.
" 8 0) (89.99969482421875 418.04913330078125 449.4207763671875 479.1073303222656 "The save-excursion function saves the locations of point and mark,
and restores them to those positions after the expressions in the body of the
save-excursion complete execution. In addition, save-excursion keeps
track of the original buffer, and restores it. This is how save-excursion is
used in append-to-buffer.
" 9 0) (90.00015258789062 486.56915283203125 449.4225158691406 547.7473754882812 "Incidentally, it is worth noting here that a Lisp function is normally for-
matted so that everything that is enclosed in a multi-line spread is indented
more to the right than the first symbol. In this function definition, the let
is indented more than the defun, and the save-excursion is indented more
than the let, like this:
" 10 0) (111.60150146484375 559.417724609375 200.54954528808594 630.6640625 "(defun ...
...
...
(let...
(save-excursion
...
" 11 0)) (77 (90.0 47.60907745361328 449.57415771484375 60.90726852416992 "save-excursion in append-to-buffer
59
" 0 0) (89.99896240234375 81.68909454345703 449.3990783691406 130.74729919433594 "This formatting convention makes it easy to see that the two lines in the
body of the save-excursion are enclosed by the parentheses associated
with save-excursion, just as the save-excursion itself is enclosed by the
parentheses associated with the let:
" 1 0) (111.59886169433594 137.85763549804688 341.7973327636719 184.1439666748047 "(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
" 2 0) (89.99932861328125 188.60906982421875 449.3766174316406 213.9072723388672 "The use of the save-excursion function can be viewed as a process of
filling in the slots of a template:
" 3 0) (111.59921264648438 221.01760864257812 226.0409698486328 279.7839050292969 "(save-excursion
first-expression-in-body
second-expression-in-body
...
last-expression-in-body)
" 4 0) (89.99874877929688 284.2490234375 449.3550109863281 309.4272155761719 "In this function, the body of the save-excursion contains only two expres-
sions. The body looks like this:
" 5 0) (89.99810791015625 316.5375671386719 449.7251281738281 498.5472412109375 "(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end)
When the append-to-buffer function is evaluated, the two expressions
in the body of the save-excursion are evaluated in sequence. The value of
the last expression is returned as the value of the save-excursion function;
the other expression is evaluated only for its side effects.
The first line in the body of the save-excursion uses the set-buffer
function to change the current buffer to the one specified in the first argument
to append-to-buffer. (Changing the buffer is the side effect; as we have
said before, in Lisp, a side effect is often the primary thing we want.) The
second line does the primary work of the function.
The set-buffer function changes Emacs’ attention to the buffer to which
the text will be copied and from which save-excursion will return.
The line looks like this:
" 6 0) (89.99884033203125 505.5376281738281 449.6275634765625 630.7872924804688 "(set-buffer (get-buffer-create buffer))
The innermost expression of this list is (get-buffer-create buffer).
This expression uses the get-buffer-create function, which either gets the
named buffer, or if it does not exist, creates one with the given name. This
means you can use append-to-buffer to put text into a buffer that did not
previously exist.
get-buffer-create also keeps set-buffer from getting an unnecessary
error: set-buffer needs a buffer to go to; if you were to specify a buffer that
does not exist, Emacs would baulk. Since get-buffer-create will create a
buffer if none exists, set-buffer is always provided with a buffer.
" 7 0)) (78 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "60
Chapter 4: A Few Buffer–Related Functions
" 0 0) (104.9993896484375 81.68909454345703 449.27874755859375 94.9872817993164 "The last line of append-to-buffer does the work of appending the text:
" 1 0) (89.99887084960938 102.21762084960938 449.83551025390625 231.90733337402344 "(insert-buffer-substring oldbuf start end)
The insert-buffer-substring function copies a string from the buffer
specified as its first argument and inserts the string into the present buffer.
In this case, the argument to insert-buffer-substring is the value of the
variable created and bound by the let, namely the value of oldbuf, which
was the current buffer when you gave the append-to-buffer command.
After insert-buffer-substring has done its work, save-excursion
will restore the action to the original buffer and append-to-buffer will
have done its job.
Written in skeletal form, the workings of the body look like this:
" 2 0) (111.5992431640625 239.0152587890625 392.71527099609375 285.3039855957031 "(let (bind-oldbuf-to-value-of-current-buffer)
(save-excursion
; Keep track of buffer.
change-buffer
insert-substring-from-oldbuf-into-buffer)
" 3 0) (111.59930419921875 301.29522705078125 337.39544677734375 322.7439880371094 "change-back-to-original-buffer-when-finished
let-the-local-meaning-of-oldbuf-disappear-when-finished
" 4 0) (89.99819946289062 338.72906494140625 449.51812744140625 451.8672790527344 "In summary, append-to-buffer works as follows: it saves the value of the
current buffer in the variable called oldbuf. It gets the new buffer, creating
one if need be, and switches Emacs to it. Using the value of oldbuf, it
inserts the region of text from the old buffer into the new buffer; and then
using save-excursion, it brings you back to your original buffer.
In looking at append-to-buffer, you have explored a fairly complex
function. It shows how to use let and save-excursion, and how to change
to and come back from another buffer. Many function definitions use let,
save-excursion, and set-buffer this way.
" 5 0) (89.99848937988281 476.9003601074219 169.8894805908203 491.2608947753906 "4.5 Review
" 6 0) (104.99848937988281 501.2090759277344 449.2343444824219 514.5072631835938 "Here is a brief summary of the various functions discussed in this chapter.
" 7 0) (89.99807739257812 525.252685546875 449.2018127441406 572.5960693359375 "describe-function
describe-variable
Print the documentation for a function or variable. Convention-
ally bound to C-h f and C-h v.
" 8 0) (89.9984130859375 581.609130859375 449.4854736328125 636.6498413085938 "find-tag
Find the file containing the source for a function or variable and
switch buffers to it, positioning point at the beginning of the
item. Conventionally bound to M-. (that’s a period following
the ⟨
" 9 0) (169.30799865722656 620.8720092773438 194.62799072265625 621.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (169.32000732421875 622.0823974609375 194.6065216064453 630.0525512695312 "META
" 11 0) (169.30799865722656 629.3919677734375 194.62799072265625 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (194.0399932861328 617.1290893554688 224.3890838623047 636.289794921875 "⟩ key).
" 13 0)) (79 (90.0 47.60907745361328 449.8256530761719 60.90726852416992 "Exercises
61
" 0 0) (90.0 79.33271789550781 449.3671569824219 126.66727447509766 "save-excursion
Save the location of point and mark and restore their values after
the arguments to save-excursion have been evaluated. Also,
remember the current buffer and return to it.
" 1 0) (89.99972534179688 133.0927276611328 449.4967346191406 192.4272918701172 "push-mark
Set mark at a location and record the value of the previous mark
on the mark ring. The mark is a location in the buffer that will
keep its relative position even if text is added to or removed
from the buffer.
" 2 0) (89.9984359741211 198.8527374267578 449.5509033203125 246.1873016357422 "goto-char
Set point to the location specified by the value of the argument,
which can be a number, a marker, or an expression that returns
the number of a position, such as (point-min).
" 3 0) (89.99832153320312 252.6127471923828 449.38671875 288.0672912597656 "insert-buffer-substring
Copy a region of text from a buffer that is passed to the function
as an argument and insert the region into the current buffer.
" 4 0) (89.99722290039062 294.49273681640625 441.1276550292969 317.95611572265625 "mark-whole-buffer
Mark the whole buffer as a region. Normally bound to C-x h.
" 5 0) (89.9969482421875 324.37274169921875 449.5276184082031 371.7073059082031 "set-buffer
Switch the attention of Emacs to another buffer, but do not
change the window being displayed. Used when the program
rather than a human is to work on a different buffer.
" 6 0) (89.99609375 378.13275146484375 449.46087646484375 437.4673156738281 "get-buffer-create
get-buffer
Find a named buffer or create one if a buffer of that name does
not exist. The get-buffer function returns nil if the named
buffer does not exist.
" 7 0) (89.99528503417969 455.660400390625 183.29995727539062 470.02093505859375 "4.6 Exercises
" 8 0) (98.99493408203125 475.7691345214844 449.3077697753906 550.6928100585938 "• Write your own simplified-end-of-buffer function definition; then
test it to see whether it works.
• Use if and get-buffer to write a function that prints a message telling
you whether a buffer exists.
• Using find-tag, find the source for the copy-to-buffer function.
" 9 0)) (80 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "62
Chapter 4: A Few Buffer–Related Functions
" 0 0)) (81 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "The Definition of copy-to-buffer
63
" 0 0) (90.0001220703125 75.14844512939453 384.7303466796875 92.38106536865234 "5 A Few More Complex Functions
" 1 0) (89.9990234375 107.36908721923828 449.5304260253906 180.4272918701172 "In this chapter, we build on what we have learned in previous chapters by
looking at more complex functions. The copy-to-buffer function illustrates
use of two save-excursion expressions in one definition, while the insert-
buffer function illustrates use of an asterisk in an interactive expression,
use of or, and the important distinction between a name and the object to
which the name refers.
" 2 0) (89.99909210205078 200.06036376953125 349.16363525390625 214.43357849121094 "5.1 The Definition of copy-to-buffer
" 3 0) (89.99795532226562 223.049072265625 449.5188903808594 322.8672790527344 "After understanding how append-to-buffer works, it is easy to under-
stand copy-to-buffer.
This function copies text into a buffer, but in-
stead of adding to the second buffer, it replaces the previous text in the
second buffer.
The code for the copy-to-buffer function is almost the
same as the code for append-to-buffer, except that erase-buffer and
a second save-excursion are used. (See Section 4.4, “The Definition of
append-to-buffer”, page 56, for the description of append-to-buffer.)
The body of copy-to-buffer looks like this
" 4 0) (89.998291015625 328.6576232910156 449.4534606933594 553.6273803710938 "...
(interactive \"BCopy to buffer: \\nr\")
(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(erase-buffer)
(save-excursion
(insert-buffer-substring oldbuf start end)))))
This code is similar to the code in append-to-buffer: it is only after
changing to the buffer to which the text will be copied that the definition
for this function diverges from the definition for append-to-buffer: the
copy-to-buffer function erases the buffer’s former contents. (This is what
is meant by ‘replacement’; to replace text, Emacs erases the previous text
and then inserts new text.) After erasing the previous contents of the buffer,
save-excursion is used for a second time and the new text is inserted.
Why is save-excursion used twice? Consider again what the function
does.
In outline, the body of copy-to-buffer looks like this:
" 5 0) (111.599365234375 559.415283203125 368.859130859375 630.6640625 "(let (bind-oldbuf-to-value-of-current-buffer)
(save-excursion
; First use of save-excursion.
change-buffer
(erase-buffer)
(save-excursion
; Second use of save-excursion.
insert-substring-from-oldbuf-into-buffer)))
" 6 0)) (82 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "64
Chapter 5: A Few More Complex Functions
" 0 0) (89.99850463867188 77.48908233642578 449.857421875 198.3072967529297 "The first use of save-excursion returns Emacs to the buffer from which
the text is being copied. That is clear, and is just like its use in append-
to-buffer.
Why the second use?
The reason is that insert-buffer-
substring always leaves point at the end of the region being inserted. The
second save-excursion causes Emacs to leave point at the beginning of the
text being inserted. In most circumstances, users prefer to find point at the
beginning of inserted text. (Of course, the copy-to-buffer function returns
the user to the original buffer when done—but if the user then switches to
the copied-to buffer, point will go to the beginning of the text. Thus, this
use of a second save-excursion is a little nicety.)
" 1 0) (89.99812316894531 224.06036376953125 341.7313537597656 238.43357849121094 "5.2 The Definition of insert-buffer
" 2 0) (89.9962158203125 248.48907470703125 449.5498352050781 337.8672790527344 "insert-buffer is yet another buffer-related function.
This command
copies another buffer into the current buffer. It is the reverse of append-
to-buffer or copy-to-buffer, since they copy a region of text from the
current buffer to another buffer.
In addition, this code illustrates the use of interactive with a buffer
that might be read-only and the important distinction between the name of
an object and the object actually referred to.
" 3 0) (104.99609375 341.00909423828125 184.80690002441406 354.3072814941406 "Here is the code:
" 4 0) (111.59607696533203 361.6576232910156 341.5971374511719 547.0241088867188 "(defun insert-buffer (buffer)
\"Insert after point the contents of BUFFER.
Puts mark after the inserted text.
BUFFER may be a buffer or a buffer name.\"
(interactive \"*bInsert buffer: \")
(or (bufferp buffer)
(setq buffer (get-buffer buffer)))
(let (start end newmark)
(save-excursion
(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
(insert-buffer-substring buffer start end)
(setq newmark (point)))
(push-mark newmark)))
" 5 0) (89.99786376953125 551.7291259765625 449.3534240722656 577.02734375 "As with other function definitions, you can use a template to see an
outline of the function:
" 6 0) (111.59786987304688 584.2577514648438 276.1382141113281 630.6640625 "(defun insert-buffer (buffer)
\"documentation...\"
(interactive \"*bInsert buffer: \")
body...)
" 7 0)) (83 (90.0 47.60907745361328 449.5639343261719 60.90726852416992 "The Body of the insert-buffer Function
65
" 0 0) (90.00027465820312 78.2418212890625 410.762451171875 91.35738372802734 "5.2.1 The Interactive Expression in insert-buffer
" 1 0) (89.99972534179688 101.48908233642578 449.36712646484375 126.78726959228516 "In insert-buffer, the argument to the interactive declaration has
two parts, an asterisk, ‘*’, and ‘bInsert buffer: ’.
" 2 0) (89.99920654296875 146.40179443359375 216.149658203125 159.5057830810547 "A Read-only Buffer
" 3 0) (89.99893188476562 169.6490478515625 449.48577880859375 242.82725524902344 "The asterisk is for the situation when the buffer is a read-only buffer—
a buffer that cannot be modified. If insert-buffer is called on a buffer
that is read-only, a message to this effect is printed in the echo area and
the terminal may beep or blink at you; you will not be permitted to insert
anything into current buffer. The asterisk does not need to be followed by a
newline to separate it from the next argument.
" 4 0) (89.99984741210938 262.4417724609375 290.81427001953125 275.5573425292969 "‘b’ in an Interactive Expression
" 5 0) (89.998291015625 285.68902587890625 449.85748291015625 406.6272277832031 "The next argument in the interactive expression starts with a lower case
‘b’. (This is different from the code for append-to-buffer, which uses an
upper-case ‘B’.
See Section 4.4, “The Definition of append-to-buffer”,
page 56.) The lower-case ‘b’ tells the Lisp interpreter that the argument for
insert-buffer should be an existing buffer or else its name. (The upper-
case ‘B’ option provides for the possibility that the buffer does not exist.)
Emacs will prompt you for the name of the buffer, offering you a default
buffer, with name completion enabled.
If the buffer does not exist, you
receive a message that says “No match”; your terminal may beep at you as
well.
" 6 0) (89.998291015625 426.3617858886719 387.6724853515625 439.47735595703125 "5.2.2 The Body of the insert-buffer Function
" 7 0) (89.997802734375 449.6090393066406 449.5071105957031 538.8673095703125 "The body of the insert-buffer function has two major parts: an or
expression and a let expression. The purpose of the or expression is to
ensure that the argument buffer is bound to a buffer and not just the name
of a buffer. The body of the let expression contains the code which copies
the other buffer into the current buffer.
In outline, the two expressions fit into the insert-buffer function like
this:
" 8 0) (111.59844207763672 545.8576049804688 276.1387634277344 630.6640014648438 "(defun insert-buffer (buffer)
\"documentation...\"
(interactive \"*bInsert buffer: \")
(or ...
...
(let (varlist)
body-of-let... )
" 9 0)) (84 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "66
Chapter 5: A Few More Complex Functions
" 0 0) (89.99993896484375 77.48908233642578 449.58526611328125 141.0673065185547 "To understand how the or expression ensures that the argument buffer
is bound to a buffer and not to the name of a buffer, it is first necessary to
understand the or function.
Before doing this, let me rewrite this part of the function using if so that
you can see what is done in a manner that will be familiar.
" 1 0) (89.99993896484375 156.0018310546875 399.27911376953125 169.1173858642578 "5.2.3 insert-buffer With an if Instead of an or
" 2 0) (89.99954223632812 177.6890869140625 449.4432678222656 279.7873229980469 "The job to be done is to make sure the value of buffer is a buffer itself
and not the name of a buffer. If the value is the name, then the buffer itself
must be got.
You can imagine yourself at a conference where an usher is wandering
around holding a list with your name on it and looking for you: the usher is
“bound” to your name, not to you; but when the usher finds you and takes
your arm, the usher becomes “bound” to you.
In Lisp, you might describe this situation like this:
" 3 0) (90.00009155273438 285.2176818847656 449.4981994628906 360.3073425292969 "(if (not (holding-on-to-guest))
(find-and-take-arm-of-guest))
We want to do the same thing with a buffer—if we do not have the buffer
itself, we want to get it.
Using a predicate called bufferp that tells us whether we have a buffer
(rather than its name), we can write the code like this:
" 4 0) (90.00030517578125 365.85528564453125 449.466064453125 527.107421875 "(if (not (bufferp buffer))
; if-part
(setq buffer (get-buffer buffer)))
; then-part
Here, the true-or-false-test of the if expression is (not (bufferp buffer));
and the then-part is the expression (setq buffer (get-buffer buffer)).
In the test, the function bufferp returns true if its argument is a buffer—
but false if its argument is the name of the buffer. (The last character of
the function name bufferp is the character ‘p’; as we saw earlier, such use
of ‘p’ is a convention that indicates that the function is a predicate, which is
a term that means that the function will determine whether some property
is true or false. See Section 1.8.4, “Using the Wrong Type Object as an
Argument”, page 14.)
The function not precedes the expression (bufferp buffer), so the true-
or-false-test looks like this:
" 5 0) (89.99822998046875 532.6577758789062 449.35491943359375 630.7874145507812 "(not (bufferp buffer))
not is a function that returns true if its argument is false and false if its
argument is true. So if (bufferp buffer) returns true, the not expression
returns false and vice-versa: what is “not true” is false and what is “not
false” is true.
Using this test, the if expression works as follows: when the value of
the variable buffer is actually a buffer rather then its name, the true-or-
false-test returns false and the if expression does not evaluate the then-part.
" 6 0)) (85 (90.0 47.60907745361328 449.7704772949219 60.90726852416992 "The or in the Body
67
" 0 0) (89.999755859375 77.48908233642578 449.2685241699219 102.66727447509766 "This is fine, since we do not need to do anything to the variable buffer if it
really is a buffer.
" 1 0) (89.99874877929688 108.68909454345703 449.5626525878906 193.74729919433594 "On the other hand, when the value of buffer is not a buffer itself, but
the name of a buffer, the true-or-false-test returns true and the then-part
of the expression is evaluated. In this case, the then-part is (setq buffer
(get-buffer buffer)). This expression uses the get-buffer function to
return an actual buffer itself, given its name. The setq then sets the variable
buffer to the value of the buffer itself, replacing its previous value (which
was the name of the buffer).
" 2 0) (89.9990234375 222.96185302734375 252.7234344482422 236.07740783691406 "5.2.4 The or in the Body
" 3 0) (89.99700927734375 249.4490966796875 449.4409484863281 310.6272888183594 "The purpose of the or expression in the insert-buffer function is to
ensure that the argument buffer is bound to a buffer and not just to the
name of a buffer. The previous section shows how the job could have been
done using an if expression. However, the insert-buffer function actually
uses or. To understand this, it is necessary to understand how or works.
" 4 0) (89.99600219726562 316.52911376953125 449.34100341796875 365.7073059082031 "An or function can have any number of arguments. It evaluates each
argument in turn and returns the value of the first of its arguments that is
not nil. Also, and this is a crucial feature of or, it does not evaluate any
subsequent arguments after returning the first non-nil value.
" 5 0) (104.99609375 371.84912109375 263.3631896972656 385.1473083496094 "The or expression looks like this:
" 6 0) (111.59611511230469 395.3776550292969 290.0478820800781 416.82403564453125 "(or (bufferp buffer)
(setq buffer (get-buffer buffer)))
" 7 0) (89.99453735351562 423.5691223144531 449.4162902832031 496.6273193359375 "The first argument to or is the expression (bufferp buffer). This expres-
sion returns true (a non-nil value) if the buffer is actually a buffer, and
not just the name of a buffer.
In the or expression, if this is the case,
the or expression returns this true value and does not evaluate the next
expression—and this is fine with us, since we do not want to do anything to
the value of buffer if it really is a buffer.
" 8 0) (89.99395751953125 502.5291748046875 449.535888671875 575.58740234375 "On the other hand, if the value of (bufferp buffer) is nil, which it will
be if the value of buffer is the name of a buffer, the Lisp interpreter evaluates
the next element of the or expression. This is the expression (setq buffer
(get-buffer buffer)). This expression returns a non-nil value, which is
the value to which it sets the variable buffer—and this value is a buffer
itself, not the name of a buffer.
" 9 0) (89.99322509765625 581.609130859375 449.42596435546875 630.787353515625 "The result of all this is that the symbol buffer is always bound to a buffer
itself rather than to the name of a buffer. All this is necessary because the
set-buffer function in a following line only works with a buffer itself, not
with the name to a buffer.
" 10 0)) (86 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "68
Chapter 5: A Few More Complex Functions
" 0 0) (90.00039672851562 80.48908233642578 449.2470397949219 105.66727447509766 "Incidentally, using or, the situation with the usher would be written like
this:
" 1 0) (111.60039520263672 111.57760620117188 369.3045349121094 120.54399108886719 "(or (holding-on-to-guest) (find-and-take-arm-of-guest))
" 2 0) (89.99978637695312 137.16180419921875 361.75616455078125 150.27735900878906 "5.2.5 The let Expression in insert-buffer
" 3 0) (89.99856567382812 159.20904541015625 449.4969787597656 271.1472473144531 "After ensuring that the variable buffer refers to a buffer itself and not
just to the name of a buffer, the insert-buffer function continues with a
let expression. This specifies three local variables, start, end, and newmark
and binds them to the initial value nil. These variables are used inside the
remainder of the let and temporarily hide any other occurrence of variables
of the same name in Emacs until the end of the let.
The body of the let contains two save-excursion expressions. First, we
will look at the inner save-excursion expression in detail. The expression
looks like this:
" 4 0) (89.99755859375 277.0575866699219 449.5391845703125 463.8672180175781 "(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
The expression (set-buffer buffer) changes Emacs’ attention from the
current buffer to the one from which the text will copied. In that buffer,
the variables start and end are set to the beginning and end of the buffer,
using the commands point-min and point-max. Note that we have here an
illustration of how setq is able to set two variables in the same expression.
The first argument of setq is set to the value of its second, and its third
argument is set to the value of its fourth.
After the body of the inner save-excursion is evaluated, the save-
excursion restores the original buffer, but start and end remain set to the
values of the beginning and end of the buffer from which the text will be
copied.
The outer save-excursion expression looks like this:
" 5 0) (89.99526977539062 469.7775573730469 449.42938232421875 630.7872314453125 "(save-excursion
(inner-save-excursion-expression
(go-to-new-buffer-and-set-start-and-end)
(insert-buffer-substring buffer start end)
(setq newmark (point)))
The insert-buffer-substring function copies the text into the current
buffer from the region indicated by start and end in buffer. Since the
whole of the second buffer lies between start and end, the whole of the
second buffer is copied into the buffer you are editing. Next, the value of
point, which will be at the end of the inserted text, is recorded in the variable
newmark.
After the body of the outer save-excursion is evaluated, point and mark
are relocated to their original places.
" 6 0)) (87 (90.0 47.60907745361328 449.73797607421875 60.90726852416992 "Optional Arguments
69
" 0 0) (89.9996337890625 77.48908233642578 449.650146484375 156.0497589111328 "However, it is convenient to locate a mark at the end of the newly inserted
text and locate point at its beginning. The newmark variable records the end
of the inserted text. In the last line of the let expression, the (push-mark
newmark) expression function sets a mark to this location. (The previous
location of the mark is still accessible; it is recorded on the mark ring and
you can go back to it with C-u C-⟨
" 1 0) (254.8679962158203 140.6319580078125 271.5480041503906 141.11195373535156 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (254.8800048828125 141.84242248535156 271.42596435546875 149.81253051757812 "SPC
" 3 0) (254.8679962158203 149.1519775390625 271.5480041503906 149.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00015258789062 137.2491455078125 449.7162170410156 174.42735290527344 "⟩.) Meanwhile, point is located at the
beginning of the inserted text, which is where it was before you called the
insert function.
" 5 0) (105.00015258789062 180.80914306640625 299.9017028808594 194.1073455810547 "The whole let expression looks like this:
" 6 0) (111.599609375 204.57766723632812 332.24017333984375 300.7839050292969 "(let (start end newmark)
(save-excursion
(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
(insert-buffer-substring buffer start end)
(setq newmark (point)))
(push-mark newmark))
" 7 0) (90.00018310546875 307.64898681640625 449.41094970703125 356.8271789550781 "Like the append-to-buffer function, the insert-buffer function uses
let, save-excursion, and set-buffer. In addition, the function illustrates
one way to use or. All these functions are building blocks that we will find
and use again and again.
" 8 0) (90.00017547607422 395.4202880859375 426.1179504394531 409.79351806640625 "5.3 Complete Definition of beginning-of-buffer
" 9 0) (90.00003051757812 423.0890197753906 449.3235778808594 460.2672119140625 "The basic structure of the beginning-of-buffer function has already
been discussed. (See Section 4.2, “A Simplified beginning-of-buffer Def-
inition”, page 52.) This section describes the complex part of the definition.
" 10 0) (89.99850463867188 466.4090270996094 449.6725769042969 599.3472900390625 "As previously described, when invoked without an argument, beginning-
of-buffer moves the cursor to the beginning of the buffer, leaving the mark
at the previous position. However, when the command is invoked with a
number between one and ten, the function considers that number to be a
fraction of the length of the buffer, measured in tenths, and Emacs moves
the cursor that fraction of the way from the beginning of the buffer. Thus,
you can either call this function with the key command M-<, which will move
the cursor to the beginning of the buffer, or with a key command such as
C-u 7 M-< which will move the cursor to a point 70% of the way through the
buffer. If a number bigger than ten is used for the argument, it moves to
the end of the buffer.
" 11 0) (89.99862670898438 605.489013671875 449.34417724609375 630.7872314453125 "The beginning-of-buffer function can be called with or without an
argument. The use of the argument is optional.
" 12 0)) (88 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "70
Chapter 5: A Few More Complex Functions
" 0 0) (90.00021362304688 78.2418212890625 259.23736572265625 91.34580993652344 "5.3.1 Optional Arguments
" 1 0) (89.9998779296875 104.12909698486328 449.5845642089844 153.3072967529297 "Unless told otherwise, Lisp expects that a function with an argument in
its function definition will be called with a value for that argument. If that
does not happen, you get an error and a message that says ‘Wrong number
of arguments’.
" 2 0) (89.99942016601562 158.60906982421875 449.5632629394531 219.7872772216797 "However, optional arguments are a feature of Lisp: a keyword may be
used to tell the Lisp interpreter that an argument is optional. The keyword
is &optional. (The ‘&’ in front of ‘optional’ is part of the keyword.) In a
function definition, if an argument follows the keyword &optional, a value
does not need to be passed to that argument when the function is called.
" 3 0) (90.00006103515625 225.20904541015625 449.2474060058594 250.5072479248047 "The first line of the function definition of beginning-of-buffer therefore
looks like this:
" 4 0) (111.60009002685547 260.1376037597656 308.9436340332031 269.1039733886719 "(defun beginning-of-buffer (&optional arg)
" 5 0) (104.99986267089844 275.12908935546875 318.5670166015625 288.4272766113281 "In outline, the whole function looks like this:
" 6 0) (111.59992980957031 298.0576477050781 308.9434814453125 406.6239929199219 "(defun beginning-of-buffer (&optional arg)
\"documentation...\"
(interactive \"P\")
(push-mark)
(goto-char
(if-there-is-an-argument
figure-out-where-to-go
else-go-to
(point-min))))
" 7 0) (89.99911499023438 412.7690734863281 449.50860595703125 461.947265625 "The function is similar to the simplified-beginning-of-buffer func-
tion except that the interactive expression has \"P\" as an argument and
the goto-char function is followed by an if-then-else expression that figures
out where to put the cursor if there is an argument.
" 8 0) (89.9998779296875 467.24908447265625 449.541259765625 510.4097900390625 "The \"P\" in the interactive expression tells Emacs to pass a prefix
argument, if there is one, to the function. A prefix argument is made by
typing the ⟨
" 9 0) (146.86801147460938 494.6319885253906 172.18801879882812 495.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (146.8800048828125 495.8424377441406 172.16651916503906 503.8125305175781 "META
" 11 0) (146.86801147460938 503.1520080566406 172.18801879882812 503.63201904296875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (90.00054931640625 490.8890686035156 449.60711669921875 516.4360961914062 "⟩ key followed by a number, or by typing C-u and then a
number (if you don’t type a number, C-u defaults to 4).
" 13 0) (89.99868774414062 521.84912109375 449.5188293457031 630.787353515625 "The true-or-false-test of the if expression is simple: it is simply the
argument arg. If arg has a value that is not nil, which will be the case if
beginning-of-buffer is called with an argument, then this true-or-false-
test will return true and the then-part of the if expression will be evaluated.
On the other hand, if beginning-of-buffer is not called with an argument,
the value of arg will be nil and the else-part of the if expression will be
evaluated. The else-part is simply point-min, and when this is the outcome,
the whole goto-char expression is (goto-char (point-min)), which is how
we saw the beginning-of-buffer function in its simplified form.
" 14 0)) (89 (90.0 47.60907745361328 449.6610107421875 60.90726852416992 "What happens in a large buffer
71
" 0 0) (89.99935913085938 78.2418212890625 379.2123718261719 91.35738372802734 "5.3.2 beginning-of-buffer with an Argument
" 1 0) (89.99972534179688 100.16907501220703 449.3883972167969 149.34727478027344 "When beginning-of-buffer is called with an argument, an expression is
evaluated which calculates what value to pass to goto-char. This expression
is rather complicated at first sight. It includes an inner if expression and
much arithmetic. It looks like this:
" 2 0) (90.0003662109375 155.13754272460938 449.4223937988281 290.2270812988281 "(if (> (buffer-size) 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg) (/ (buffer-size) 10))
(/
(+ 10
(*
(buffer-size) (prefix-numeric-value arg))) 10))
Like other complex-looking expressions, the conditional expression within
beginning-of-buffer can be disentangled by looking at it as parts of a
template, in this case, the template for an if-then-else expression. In skeletal
form, the expression looks like this:
" 3 0) (90.00009155273438 296.01495361328125 449.466796875 443.8271179199219 "(if (buffer-is-large
divide-buffer-size-by-10-and-multiply-by-arg
else-use-alternate-calculation
The true-or-false-test of this inner if expression checks the size of the
buffer. The reason for this is that the old Version 18 Emacs used numbers
that are no bigger than eight million or so and in the computation that
followed, the programmer feared that Emacs might try to use over-large
numbers if the buffer were large.
The term ‘overflow’, mentioned in the
comment, means numbers that are over large. Version 21 Emacs uses larger
numbers, but this code has not been touched, if only because people now
look at buffers that are far, far larger than ever before.
There are two cases: if the buffer is large and if it is not.
" 4 0) (90.00003051757812 459.481689453125 291.9230041503906 472.585693359375 "What happens in a large buffer
" 5 0) (90.0006103515625 481.5289306640625 449.33489990234375 533.587158203125 "In beginning-of-buffer, the inner if expression tests whether the size
of the buffer is greater than 10,000 characters. To do this, it uses the >
function and the buffer-size function.
The line looks like this:
" 6 0) (89.99990844726562 539.3775024414062 449.3666687011719 575.587158203125 "(if (> (buffer-size) 10000)
When the buffer is large, the then-part of the if expression is evaluated. It
reads like this (after formatting for easy reading):
" 7 0) (89.9999771118164 581.3775024414062 442.1563720703125 630.7871704101562 "(*
(prefix-numeric-value arg)
(/ (buffer-size) 10))
This expression is a multiplication, with two arguments to the function *.
" 8 0)) (90 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "72
Chapter 5: A Few More Complex Functions
" 0 0) (89.9993896484375 77.48908233642578 449.4656066894531 138.5472869873047 "The first argument is (prefix-numeric-value arg). When \"P\" is used
as the argument for interactive, the value passed to the function as its
argument is passed a “raw prefix argument”, and not a number. (It is a
number in a list.) To perform the arithmetic, a conversion is necessary, and
prefix-numeric-value does the job.
" 1 0) (89.99932861328125 143.12908935546875 449.3666076660156 192.3072967529297 "The second argument is (/ (buffer-size) 10). This expression divides
the numeric value of the buffer by ten. This produces a number that tells
how many characters make up one tenth of the buffer size. (In Lisp, / is
used for division, just as * is used for multiplication.)
" 2 0) (89.99911499023438 196.88909912109375 449.3331298828125 222.0673065185547 "In the multiplication expression as a whole, this amount is multiplied by
the value of the prefix argument—the multiplication looks like this:
" 3 0) (111.59896850585938 230.9752197265625 320.8189697265625 252.4239959716797 "(* numeric-value-of-prefix-arg
number-of-characters-in-one-tenth-of-the-buffer)
" 4 0) (89.99862670898438 257.60906982421875 449.3546142578125 282.9072570800781 "If, for example, the prefix argument is ‘7’, the one-tenth value will be mul-
tiplied by 7 to give a position 70% of the way through the buffer.
" 5 0) (89.998291015625 287.48907470703125 449.2565612792969 312.6672668457031 "The result of all this is that if the buffer is large, the goto-char expression
reads like this:
" 6 0) (111.59825897216797 321.5777282714844 299.4787292480469 343.02410888671875 "(goto-char (* (prefix-numeric-value arg)
(/ (buffer-size) 10)))
" 7 0) (104.99807739257812 348.2091979980469 289.9832458496094 361.50738525390625 "This puts the cursor where we want it.
" 8 0) (89.99833679199219 386.4019470214844 294.0572814941406 399.5059509277344 "What happens in a small buffer
" 9 0) (89.99761962890625 411.4491882324219 449.4306335449219 472.50738525390625 "If the buffer contains fewer than 10,000 characters, a slightly different
computation is performed.
You might think this is not necessary, since
the first computation could do the job.
However, in a small buffer, the
first method may not put the cursor on exactly the desired line; the second
method does a better job.
" 10 0) (104.99754333496094 477.2091979980469 220.85206604003906 490.50738525390625 "The code looks like this:
" 11 0) (111.59766387939453 499.2977294921875 388.8701477050781 508.26409912109375 "(/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
" 12 0) (89.9962158203125 513.3292236328125 449.4185485839844 550.5074462890625 "This is code in which you figure out what happens by discovering how the
functions are embedded in parentheses. It is easier to read if you reformat
it with each expression indented more deeply than its enclosing expression:
" 13 0) (120.95587158203125 559.4177856445312 276.04156494140625 630.6641845703125 "(/
(+ 10
(*
(buffer-size)
(prefix-numeric-value arg)))
10))
" 14 0)) (91 (90.0 47.60907745361328 449.5965576171875 60.90726852416992 "The Complete beginning-of-buffer
73
" 0 0) (89.99990844726562 80.00910186767578 449.55206298828125 117.18729400634766 "Looking at parentheses, we see that the innermost operation is (prefix-
numeric-value arg), which converts the raw argument to a number. This
number is multiplied by the buffer size in the following expression:
" 1 0) (89.99945068359375 122.61764526367188 449.4430847167969 220.7473602294922 "(* (buffer-size) (prefix-numeric-value arg)
This multiplication creates a number that may be larger than the size of
the buffer—seven times larger if the argument is 7, for example.
Ten is
then added to this number and finally the large number is divided by ten to
provide a value that is one character larger than the percentage position in
the buffer.
The number that results from all this is passed to goto-char and the
cursor is moved to that point.
" 2 0) (90.000244140625 235.44189453125 351.8075256347656 248.5574493408203 "5.3.3 The Complete beginning-of-buffer
" 3 0) (105.00023651123047 257.129150390625 414.5348205566406 270.4273376464844 "Here is the complete text of the beginning-of-buffer function:
" 4 0) (111.59982299804688 275.8576965332031 323.009033203125 396.9041748046875 "(defun beginning-of-buffer (&optional arg)
\"Move point to the beginning of the buffer;
leave mark at previous position.
With arg N, put point N/10 of the way
from the true beginning.
Don’t use this in Lisp programs!
\\(goto-char (point-min)) is faster
and does not set the mark.\"
(interactive \"P\")
(push-mark)
" 5 0) (120.96048736572266 401.497802734375 323.555908203125 472.6241760253906 "(goto-char
(if arg
(if (> (buffer-size) 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg)
(/ (buffer-size) 10))
" 6 0) (90.00030517578125 477.2178039550781 449.400146484375 589.5075073242188 "(/ (+ 10 (* (buffer-size)
(prefix-numeric-value arg)))
10))
(point-min)))
(if arg (forward-line 1)))
Except for two small points, the previous discussion shows how this function
works. The first point deals with a detail in the documentation string, and
the second point concerns the last line of the function.
In the documentation string, there is reference to an expression:
" 7 0) (90.00033569335938 594.9378662109375 449.37799072265625 630.7875366210938 "\\(goto-char (point-min))
A ‘\\\\u2019 is used before the first parenthesis of this expression. This ‘\\\\u2019 tells
the Lisp interpreter that the expression should be printed as shown in the
" 8 0)) (92 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "74
Chapter 5: A Few More Complex Functions
" 0 0) (90.00021362304688 77.48908233642578 449.34564208984375 141.5472869873047 "documentation rather than evaluated as a symbolic expression, which is what
it looks like.
Finally, the last line of the beginning-of-buffer command says to move
point to the beginning of the next line if the command is invoked with an
argument:
" 1 0) (90.00003051757812 147.45761108398438 449.4874267578125 219.4272918701172 "(if arg (forward-line 1)))
This puts the cursor at the beginning of the first line after the appropriate
tenths position in the buffer. This is a flourish that means that the cursor is
always located at least the requested tenths of the way through the buffer,
which is a nicety that is, perhaps, not necessary, but which, if it did not
occur, would be sure to draw complaints.
" 2 0) (89.99974060058594 239.30035400390625 169.89073181152344 253.660888671875 "5.4 Review
" 3 0) (104.99974060058594 262.2890625 437.1813049316406 275.5872497558594 "Here is a brief summary of some of the topics covered in this chapter.
" 4 0) (90.00003051757812 281.96905517578125 449.48760986328125 343.0272521972656 "or
Evaluate each argument in sequence, and return the value of
the first argument that is not nil; if none return a value that
is not nil, return nil. In brief, return the first true value of
the arguments; return a true value if one or any of the other are
true.
" 5 0) (90.00080108642578 349.4090576171875 449.5203552246094 398.5872497558594 "and
Evaluate each argument in sequence, and if any are nil, return
nil; if none are nil, return the value of the last argument. In
brief, return a true value only if all the arguments are true;
return a true value if one and each of the others is true.
" 6 0) (90.00076293945312 406.81268310546875 449.488037109375 454.1472473144531 "&optional
A keyword used to indicate that an argument to a function defi-
nition is optional; this means that the function can be evaluated
without the argument, if desired.
" 7 0) (90.00105285644531 462.252685546875 449.7936706542969 497.7072448730469 "prefix-numeric-value
Convert the ‘raw prefix argument’ produced by (interactive
\"P\") to a numeric value.
" 8 0) (90.00175476074219 505.81268310546875 449.7944641113281 577.0272827148438 "forward-line
Move point forward to the beginning of the next line, or if the
argument is greater than one, forward that many lines.
If it
can’t move as far forward as it is supposed to, forward-line
goes forward as far as it can and then returns a count of the
number of additional lines it was supposed to move but couldn’t.
" 9 0) (90.00173950195312 585.252685546875 373.3979187011719 608.707275390625 "erase-buffer
Delete the entire contents of the current buffer.
" 10 0) (90.00173950195312 615.0890502929688 424.12506103515625 628.3872680664062 "bufferp
Return t if its argument is a buffer; otherwise return nil.
" 11 0)) (93 (90.0 47.60907745361328 449.6620178222656 60.90726852416992 "optional Argument Exercise
75
" 0 0) (90.0003662109375 77.30034637451172 318.1007385253906 91.67356872558594 "5.5 optional Argument Exercise
" 1 0) (90.000244140625 99.32910919189453 449.43304443359375 148.50730895996094 "Write an interactive function with an optional argument that tests
whether its argument, a number, is greater or less than the value of fill-
column, and tells you which, in a message. However, if you do not pass an
argument to the function, use 56 as a default value.
" 2 0)) (94 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "76
Chapter 5: A Few More Complex Functions
" 0 0)) (95 (90.0 47.60907745361328 449.5958557128906 60.90726852416992 "The save-restriction Special Form
77
" 0 0) (89.99920654296875 75.14844512939453 324.1742858886719 92.38106536865234 "6 Narrowing and Widening
" 1 0) (89.9981689453125 117.92908477783203 449.35504150390625 155.10728454589844 "Narrowing is a feature of Emacs that makes it possible for you to focus
on a specific part of a buffer, and work without accidentally changing other
parts. Narrowing is normally disabled since it can confuse novices.
" 2 0) (89.99758911132812 158.72906494140625 449.4089660644531 255.67608642578125 "With narrowing, the rest of a buffer is made invisible, as if it weren’t
there. This is an advantage if, for example, you want to replace a word in
one part of a buffer but not in another: you narrow to the part you want
and the replacement is carried out only in that section, not in the rest of
the buffer. Searches will only work within a narrowed region, not outside of
one, so if you are fixing a part of a document, you can keep yourself from
accidentally finding parts you do not need to fix by narrowing just to the
region you want. (The key binding for narrow-to-region is C-x n n.)
" 3 0) (89.99505615234375 259.2890625 449.5495300292969 344.3560791015625 "However, narrowing does make the rest of the buffer invisible, which can
scare people who inadvertently invoke narrowing and think they have deleted
a part of their file. Moreover, the undo command (which is usually bound
to C-x u) does not turn off narrowing (nor should it), so people can become
quite desperate if they do not know that they can return the rest of a buffer
to visibility with the widen command. (The key binding for widen is C-x n
w.)
" 4 0) (89.99188232421875 347.84906005859375 449.5561218261719 456.7872619628906 "Narrowing is just as useful to the Lisp interpreter as to a human. Often,
an Emacs Lisp function is designed to work on just part of a buffer; or
conversely, an Emacs Lisp function needs to work on all of a buffer that
has been narrowed.
The what-line function, for example, removes the
narrowing from a buffer, if it has any narrowing and when it has finished its
job, restores the narrowing to what it was. On the other hand, the count-
lines function, which is called by what-line, uses narrowing to restrict
itself to just that portion of the buffer in which it is interested and then
restores the previous situation.
" 5 0) (89.99147033691406 484.8203430175781 366.9673156738281 499.1935729980469 "6.1 The save-restriction Special Form
" 6 0) (89.99102783203125 509.84906005859375 449.4242248535156 630.7872924804688 "In Emacs Lisp, you can use the save-restriction special form to keep
track of whatever narrowing is in effect, if any. When the Lisp interpreter
meets with save-restriction, it executes the code in the body of the save-
restriction expression, and then undoes any changes to narrowing that the
code caused. If, for example, the buffer is narrowed and the code that follows
save-restriction gets rid of the narrowing, save-restriction returns the
buffer to its narrowed region afterwards. In the what-line command, any
narrowing the buffer may have is undone by the widen command that im-
mediately follows the save-restriction command. Any original narrowing
is restored just before the completion of the function.
" 7 0)) (96 (90.0 47.60907745361328 449.7270202636719 60.90726852416992 "78
Chapter 6: Narrowing and Widening
" 0 0) (104.999755859375 80.60907745361328 390.3377380371094 93.90726470947266 "The template for a save-restriction expression is simple:
" 1 0) (89.99880981445312 99.81759643554688 449.5189208984375 223.6272430419922 "(save-restriction
body... )
The body of the save-restriction is one or more expressions that will be
evaluated in sequence by the Lisp interpreter.
Finally, a point to note: when you use both save-excursion and save-
restriction, one right after the other, you should use save-excursion out-
ermost. If you write them in reverse order, you may fail to record narrowing
in the buffer to which Emacs switches after calling save-excursion. Thus,
when written together, save-excursion and save-restriction should be
written like this:
" 2 0) (89.99862670898438 229.53756713867188 449.7917785644531 318.0671691894531 "(save-excursion
(save-restriction
body...))
In other circumstances, when not written together, the save-excursion
and save-restriction special forms must be written in the order appro-
priate to the function.
For example,
" 3 0) (120.95866394042969 323.9776306152344 200.5467071533203 370.384033203125 "(save-restriction
(widen)
(save-excursion
body...))
" 4 0) (89.99861145019531 389.42041015625 185.49827575683594 403.79364013671875 "6.2 what-line
" 5 0) (89.99871826171875 412.5291442871094 449.74725341796875 449.70733642578125 "The what-line command tells you the number of the line in which the
cursor is located. The function illustrates the use of the save-restriction
and save-excursion commands. Here is the text of the function in full:
" 6 0) (89.99655151367188 455.7377014160156 449.4836730957031 630.7874145507812 "(defun what-line ()
\"Print the current line number (in the buffer) of point.\"
(interactive)
(save-restriction
(widen)
(save-excursion
(beginning-of-line)
(message \"Line %d\"
(1+ (count-lines 1 (point)))))))
The function has a documentation line and is interactive, as you would
expect. The next two lines use the functions save-restriction and widen.
The save-restriction special form notes whatever narrowing is in ef-
fect, if any, in the current buffer and restores that narrowing after the code
in the body of the save-restriction has been evaluated.
" 7 0)) (97 (90.0 47.60907745361328 449.6940612792969 60.90726852416992 "Exercise with Narrowing
79
" 0 0) (89.99636840820312 77.48908233642578 449.9323425292969 288.1872253417969 "The save-restriction special form is followed by widen. This function
undoes any narrowing the current buffer may have had when what-line
was called.
(The narrowing that was there is the narrowing that save-
restriction remembers.)
This widening makes it possible for the line
counting commands to count from the beginning of the buffer. Otherwise,
they would have been limited to counting within the accessible region. Any
original narrowing is restored just before the completion of the function by
the save-restriction special form.
The call to widen is followed by save-excursion, which saves the loca-
tion of the cursor (i.e., of point) and of the mark, and restores them after
the code in the body of the save-excursion uses the beginning-of-line
function to move point.
(Note that the (widen) expression comes between the save-restriction
and save-excursion special forms.
When you write the two save- ...
expressions in sequence, write save-excursion outermost.)
The last two lines of the what-line function are functions to count the
number of lines in the buffer and then print the number in the echo area.
" 1 0) (89.99569702148438 293.1376037597656 449.43963623046875 403.02734375 "(message \"Line %d\"
(1+ (count-lines 1 (point)))))))
The message function prints a one-line message at the bottom of the
Emacs screen. The first argument is inside of quotation marks and is printed
as a string of characters. However, it may contain ‘%d’, ‘%s’, or ‘%c’ to print
arguments that follow the string. ‘%d’ prints the argument as a decimal, so
the message will say something such as ‘Line 243’.
The number that is printed in place of the ‘%d’ is computed by the last
line of the function:
" 2 0) (89.99578857421875 408.0976867675781 449.48358154296875 517.1473999023438 "(1+ (count-lines 1 (point)))
What this does is count the lines from the first position of the buffer, indi-
cated by the 1, up to (point), and then add one to that number. (The 1+
function adds one to its argument.) We add one to it because line 2 has only
one line before it, and count-lines counts only the lines before the current
line.
After count-lines has done its job, and the message has been printed in
the echo area, the save-excursion restores point and mark to their original
positions; and save-restriction restores the original narrowing, if any.
" 3 0) (89.99539184570312 533.5404663085938 293.41778564453125 547.9010009765625 "6.3 Exercise with Narrowing
" 4 0) (89.99453735351562 555.689208984375 449.53631591796875 616.7474365234375 "Write a function that will display the first 60 characters of the current
buffer, even if you have narrowed the buffer to its latter half so that the first
line is inaccessible. Restore point, mark, and narrowing. For this exercise,
you need to use save-restriction, widen, goto-char, point-min, buffer-
substring, message, and other functions, a whole potpourri.
" 5 0)) (98 (90.0 47.60907745361328 449.7270202636719 60.90726852416992 "80
Chapter 6: Narrowing and Widening
" 0 0)) (99 (90.0 47.60907745361328 449.8250427246094 60.90726852416992 "car and cdr
81
" 0 0) (89.9993896484375 75.14844512939453 434.5227966308594 92.39627838134766 "7 car, cdr, cons: Fundamental Functions
" 1 0) (89.99911499023438 124.28907012939453 449.2903747558594 161.46726989746094 "In Lisp, car, cdr, and cons are fundamental functions. The cons function
is used to construct lists, and the car and cdr functions are used to take
them apart.
" 2 0) (89.9986572265625 166.2890625 449.32257080078125 203.46726989746094 "In the walk through of the copy-region-as-kill function, we will see
cons as well as two variants on cdr, namely, setcdr and nthcdr.
(See
Section 8.5, “copy-region-as-kill”, page 102.)
" 3 0) (89.9974365234375 208.2890625 449.4090881347656 353.1072692871094 "The name of the cons function is not unreasonable: it is an abbreviation
of the word ‘construct’. The origins of the names for car and cdr, on the
other hand, are esoteric: car is an acronym from the phrase ‘Contents of
the Address part of the Register’; and cdr (pronounced ‘could-er’) is an
acronym from the phrase ‘Contents of the Decrement part of the Register’.
These phrases refer to specific pieces of hardware on the very early computer
on which the original Lisp was developed. Besides being obsolete, the phrases
have been completely irrelevant for more than 25 years to anyone thinking
about Lisp. Nonetheless, although a few brave scholars have begun to use
more reasonable names for these functions, the old terms are still in use. In
particular, since the terms are used in the Emacs Lisp source code, we will
use them in this introduction.
" 4 0) (89.99783325195312 386.18035888671875 199.543701171875 400.5535888671875 "7.1 car and cdr
" 5 0) (89.99740600585938 412.5291748046875 449.451904296875 437.7073669433594 "The car of a list is, quite simply, the first item in the list. Thus the car
of the list (rose violet daisy buttercup) is rose.
" 6 0) (89.99795532226562 442.649169921875 449.2989807128906 467.9473571777344 "If you are reading this in Info in GNU Emacs, you can see this by evalu-
ating the following:
" 7 0) (111.59794616699219 477.09771728515625 280.5611877441406 486.0640869140625 "(car ’(rose violet daisy buttercup))
" 8 0) (89.998046875 491.3691711425781 406.93951416015625 504.6673583984375 "After evaluating the expression, rose will appear in the echo area.
" 9 0) (89.9986572265625 509.4891357421875 449.4852600097656 534.787353515625 "Clearly, a more reasonable name for the car function would be first
and this is often suggested.
" 10 0) (89.9981689453125 539.609130859375 449.37591552734375 576.787353515625 "car does not remove the first item from the list; it only reports what it
is. After car has been applied to a list, the list is still the same as it was. In
the jargon, car is ‘non-destructive’. This feature turns out to be important.
" 11 0) (89.99746704101562 581.609130859375 449.451904296875 630.787353515625 "The cdr of a list is the rest of the list, that is, the cdr function returns
the part of the list that follows the first item. Thus, while the car of the
list ’(rose violet daisy buttercup) is rose, the rest of the list, the value
returned by the cdr function, is (violet daisy buttercup).
" 12 0)) (100 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "82
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (105.00006103515625 80.72907257080078 399.5671081542969 94.02725982666016 "You can see this by evaluating the following in the usual way:
" 1 0) (89.99603271484375 100.17758178710938 449.50537109375 379.5072326660156 "(cdr ’(rose violet daisy buttercup))
When you evaluate this, (violet daisy buttercup) will appear in the echo
area.
Like car, cdr does not remove any elements from the list—it just returns
a report of what the second and subsequent elements are.
Incidentally, in the example, the list of flowers is quoted. If it were not, the
Lisp interpreter would try to evaluate the list by calling rose as a function.
In this example, we do not want to do that.
Clearly, a more reasonable name for cdr would be rest.
(There is a lesson here: when you name new functions, consider very
carefully what you are doing, since you may be stuck with the names for far
longer than you expect. The reason this document perpetuates these names
is that the Emacs Lisp source code uses them, and if I did not use them,
you would have a hard time reading the code; but do, please, try to avoid
using these terms yourself. The people who come after you will be grateful
to you.)
When car and cdr are applied to a list made up of symbols, such as the
list (pine fir oak maple), the element of the list returned by the function
car is the symbol pine without any parentheses around it. pine is the first
element in the list. However, the cdr of the list is a list itself, (fir oak
maple), as you can see by evaluating the following expressions in the usual
way:
" 2 0) (111.59603118896484 385.6575927734375 238.39585876464844 394.62396240234375 "(car ’(pine fir oak maple))
" 3 0) (89.99554443359375 410.6175842285156 449.4280090332031 471.1872253417969 "(cdr ’(pine fir oak maple))
On the other hand, in a list of lists, the first element is itself a list. car
returns this first element as a list. For example, the following list contains
three sub-lists, a list of carnivores, a list of herbivores and a list of sea
mammals:
" 4 0) (89.995849609375 477.33758544921875 449.592041015625 550.9873046875 "(car ’((lion tiger cheetah)
(gazelle antelope zebra)
(whale dolphin seal)))
In this example, the first element or car of the list is the list of carnivores,
(lion tiger cheetah), and the rest of the list is ((gazelle antelope
zebra) (whale dolphin seal)).
" 5 0) (89.99578857421875 557.1376342773438 449.3960266113281 630.7872924804688 "(cdr ’((lion tiger cheetah)
(gazelle antelope zebra)
(whale dolphin seal)))
It is worth saying again that car and cdr are non-destructive—that is,
they do not modify or change lists to which they are applied. This is very
important for how they are used.
" 6 0)) (101 (90.0 47.60907745361328 449.8796691894531 60.90726852416992 "cons
83
" 0 0) (89.99908447265625 77.48908233642578 449.39910888671875 198.3072967529297 "Also, in the first chapter, in the discussion about atoms, I said that in
Lisp, “certain kinds of atom, such as an array, can be separated into parts;
but the mechanism for doing this is different from the mechanism for splitting
a list. As far as Lisp is concerned, the atoms of a list are unsplittable.”
(See Section 1.1.1, “Lisp Atoms”, page 1.) The car and cdr functions are
used for splitting lists and are considered fundamental to Lisp. Since they
cannot split or gain access to the parts of an array, an array is considered an
atom. Conversely, the other fundamental function, cons, can put together
or construct a list, but not an array. (Arrays are handled by array-specific
functions. See section “Arrays” in The GNU Emacs Lisp Reference Manual.)
" 1 0) (89.99948120117188 215.660400390625 148.34246826171875 230.0336151123047 "7.2 cons
" 2 0) (89.99945068359375 238.04913330078125 449.1919250488281 275.2273254394531 "The cons function constructs lists; it is the inverse of car and cdr. For
example, cons can be used to make a four element list from the three element
list, (fir oak maple):
" 3 0) (89.99906921386719 280.4175720214844 268.2425537109375 304.1472473144531 "(cons ’pine ’(fir oak maple))
After evaluating this list, you will see
" 4 0) (89.997802734375 309.4576110839844 449.58367919921875 426.0127258300781 "(pine fir oak maple)
appear in the echo area. cons puts a new element at the beginning of a list;
it attaches or pushes elements onto the list.
cons must have a list to attach to.1 You cannot start from absolutely
nothing. If you are building a list, you need to provide at least an empty
list at the beginning. Here is a series of cons expressions that build up a list
of flowers. If you are reading this in Info in GNU Emacs, you can evaluate
each of the expressions in the usual way; the value is printed in this text
after ‘⇒’, which you may read as ‘evaluates to’.
" 5 0) (111.59840393066406 424.1776428222656 205.56089782714844 451.36981201171875 "(cons ’buttercup ())
⇒ (buttercup)
" 6 0) (111.59838104248047 453.6976623535156 233.4697723388672 480.88983154296875 "(cons ’daisy ’(buttercup))
⇒ (daisy buttercup)
" 7 0) (111.59847259521484 483.3376770019531 266.4187927246094 510.52984619140625 "(cons ’violet ’(daisy buttercup))
⇒ (violet daisy buttercup)
" 8 0) (89.99783325195312 512.8577270507812 449.4844665527344 585.0673828125 "(cons ’rose ’(violet daisy buttercup))
⇒ (rose violet daisy buttercup)
In the first example, the empty list is shown as () and a list made up
of buttercup followed by the empty list is constructed. As you can see,
the empty list is not shown in the list that was constructed. All that you
see is (buttercup). The empty list is not counted as an element of a list
" 9 0) (89.98799896240234 594.5919799804688 233.98800659179688 595.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (95.87999725341797 595.5352172851562 449.7353515625 630.3015747070312 "1 Actually, you can cons an element to an atom to produce a dotted pair. Dotted pairs
are not discussed here; see section “Dotted Pair Notation” in The GNU Emacs Lisp
Reference Manual.
" 11 0)) (102 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "84
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (89.99978637695312 77.48908233642578 449.4430236816406 153.9072723388672 "because there is nothing in an empty list. Generally speaking, an empty list
is invisible.
The second example, (cons ’daisy ’(buttercup)) constructs a new,
two element list by putting daisy in front of buttercup; and the third
example constructs a three element list by putting violet in front of daisy
and buttercup.
" 1 0) (90.00016021728516 171.601806640625 342.6677551269531 184.7173614501953 "7.2.1 Find the Length of a List: length
" 2 0) (90.00006103515625 194.24908447265625 449.4648132324219 219.4272918701172 "You can find out how many elements there are in a list by using the Lisp
function length, as in the following examples:
" 3 0) (111.59971618652344 225.93765258789062 209.98521423339844 253.0098419189453 "(length ’(buttercup))
⇒ 1
" 4 0) (111.59981536865234 255.45761108398438 238.2627410888672 282.6497802734375 "(length ’(daisy buttercup))
⇒ 2
" 5 0) (90.00047302246094 284.9775695800781 449.4336242675781 361.9871826171875 "(length (cons ’violet ’(daisy buttercup)))
⇒ 3
In the third example, the cons function is used to construct a three element
list which is then passed to the length function as its argument.
We can also use length to count the number of elements in an empty
list:
" 6 0) (90.00161743164062 368.3775329589844 449.4566650390625 445.1471862792969 "(length ())
⇒ 0
As you would expect, the number of elements in an empty list is zero.
An interesting experiment is to find out what happens if you try to find
the length of no list at all; that is, if you try to call length without giving
it an argument, not even an empty list:
" 7 0) (90.0020751953125 451.65753173828125 353.7944641113281 476.5871887207031 "(length )
What you see, if you evaluate this, is the error message
" 8 0) (90.00070190429688 482.9775390625 449.422607421875 630.7872314453125 "Wrong number of arguments: #<subr length>, 0
This means that the function receives the wrong number of arguments, zero,
when it expects some other number of arguments. In this case, one argument
is expected, the argument being a list whose length the function is measuring.
(Note that one list is one argument, even if the list has many elements inside
it.)
The part of the error message that says ‘#<subr length>’ is the name of
the function. This is written with a special notation, ‘#<subr’, that indicates
that the function length is one of the primitive functions written in C rather
than in Emacs Lisp. (‘subr’ is an abbreviation for ‘subroutine’.) See section
“What Is a Function?” in The GNU Emacs Lisp Reference Manual, for more
about subroutines.
" 9 0)) (103 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "nthcdr
85
" 0 0) (90.0 77.30034637451172 163.20565795898438 91.67356872558594 "7.3 nthcdr
" 1 0) (89.99871826171875 99.80908966064453 450.03179931640625 237.42735290527344 "The nthcdr function is associated with the cdr function. What it does
is take the cdr of a list repeatedly.
If you take the cdr of the list (pine fir oak maple), you will be returned
the list (fir oak maple).
If you repeat this on what was returned, you
will be returned the list (oak maple). (Of course, repeated cdring on the
original list will just give you the original cdr since the function does not
change the list. You need to evaluate the cdr of the cdr and so on.) If you
continue this, eventually you will be returned an empty list, which in this
case, instead of being shown as () is shown as nil.
For review, here is a series of repeated cdrs, the text following the ‘⇒’
shows what is returned.
" 2 0) (111.59909057617188 242.85769653320312 238.39891052246094 269.92987060546875 "(cdr ’(pine fir oak maple))
⇒(fir oak maple)
" 3 0) (111.59908294677734 272.3777770996094 214.7930145263672 299.5699462890625 "(cdr ’(fir oak maple))
⇒ (oak maple)
" 4 0) (111.59908294677734 301.8977355957031 196.09861755371094 329.08990478515625 "(cdr ’(oak maple))
⇒(maple)
" 5 0) (111.59907531738281 331.5377197265625 177.16415405273438 358.7298889160156 "(cdr ’(maple))
⇒ nil
" 6 0) (111.5990982055664 361.0577392578125 163.3294219970703 388.2499084472656 "(cdr ’nil)
⇒ nil
" 7 0) (89.99932861328125 390.69775390625 449.2679443359375 440.107421875 "(cdr ())
⇒ nil
You can also do several cdrs without printing the values in between, like
this:
" 8 0) (89.9970703125 445.41778564453125 449.45233154296875 603.907470703125 "(cdr (cdr ’(pine fir oak maple)))
⇒ (oak maple)
In this example, the Lisp interpreter evaluates the innermost list first. The
innermost list is quoted, so it just passes the list as it is to the innermost cdr.
This cdr passes a list made up of the second and subsequent elements of the
list to the outermost cdr, which produces a list composed of the third and
subsequent elements of the original list. In this example, the cdr function is
repeated and returns a list that consists of the original list without its first
two elements.
The nthcdr function does the same as repeating the call to cdr. In the
following example, the argument 2 is passed to the function nthcdr, along
with the list, and the value returned is the list without its first two items,
which is exactly the same as repeating cdr twice on the list:
" 9 0) (111.59686279296875 609.2178344726562 261.8825988769531 636.4099731445312 "(nthcdr 2 ’(pine fir oak maple))
⇒ (oak maple)
" 10 0)) (104 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "86
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (89.99990844726562 84.92908477783203 449.3125915527344 110.2272720336914 "Using the original four element list, we can see what happens when various
numeric arguments are passed to nthcdr, including 0, 1, and 5:
" 1 0) (111.60033416748047 120.45520782470703 261.8860778808594 160.12977600097656 ";; Leave the list as it was.
(nthcdr 0 ’(pine fir oak maple))
⇒ (pine fir oak maple)
" 2 0) (111.60026550292969 162.57513427734375 288.8662109375 202.1297149658203 ";; Return a copy without the first element.
(nthcdr 1 ’(pine fir oak maple))
⇒ (fir oak maple)
" 3 0) (111.60029602050781 204.5750732421875 322.9229736328125 244.24964904785156 ";; Return a copy of the list without three elements.
(nthcdr 3 ’(pine fir oak maple))
⇒ (maple)
" 4 0) (111.60054779052734 246.57501220703125 286.4632263183594 286.24957275390625 ";; Return a copy lacking all four elements.
(nthcdr 4 ’(pine fir oak maple))
⇒ nil
" 5 0) (111.60079193115234 288.574951171875 267.28466796875 328.24951171875 ";; Return a copy lacking all elements.
(nthcdr 5 ’(pine fir oak maple))
⇒ nil
" 6 0) (90.00125122070312 359.06005859375 140.91290283203125 373.43328857421875 "7.4 nth
" 7 0) (90.00137329101562 386.48876953125 449.30267333984375 423.7869567871094 "The nthcdr function takes the cdr of a list repeatedly. The nth function
takes the car of the result returned by nthcdr. It returns the Nth element
of the list.
" 8 0) (90.00167846679688 429.80877685546875 449.346435546875 455.1069641113281 "Thus, if it were not defined in C for speed, the definition of nth would
be:
" 9 0) (111.60151672363281 465.4573059082031 412.1624755859375 511.7436828613281 "(defun nth (n list)
\"Returns the Nth element of LIST.
N counts from zero.
If LIST is not that long, nil is returned.\"
(car (nthcdr n list)))
" 10 0) (90.00147247314453 519.0887451171875 449.281005859375 544.386962890625 "(Originally, nth was defined in Emacs Lisp in ‘subr.el’, but its definition
was redone in C in the 1980s.)
" 11 0) (90.00204467773438 550.4088134765625 449.4012145996094 575.5870361328125 "The nth function returns a single element of a list. This can be very
convenient.
" 12 0) (90.00192260742188 581.6087646484375 449.3797302246094 630.7869873046875 "Note that the elements are numbered from zero, not one.
That is to
say, the first element of a list, its car is the zeroth element. This is called
‘zero-based’ counting and often bothers people who are accustomed to the
first element in a list being number one, which is ‘one-based’.
" 13 0)) (105 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "setcdr
87
" 0 0) (105.0 80.84906768798828 166.4837188720703 94.14725494384766 "For example:
" 1 0) (111.60000610351562 100.29757690429688 252.4142303466797 127.48975372314453 "(nth 0 ’(\"one\" \"two\" \"three\"))
⇒ \"one\"
" 2 0) (90.00054931640625 137.61758422851562 449.31256103515625 198.90721130371094 "(nth 1 ’(\"one\" \"two\" \"three\"))
⇒ \"two\"
It is worth mentioning that nth, like nthcdr and cdr, does not change
the original list—the function is non-destructive. This is in sharp contrast
to the setcar and setcdr functions.
" 3 0) (90.0003662109375 220.22027587890625 163.20602416992188 234.59349060058594 "7.5 setcar
" 4 0) (90.00042724609375 243.5689697265625 449.44384765625 331.8671569824219 "As you might guess from their names, the setcar and setcdr functions
set the car or the cdr of a list to a new value. They actually change the
original list, unlike car and cdr which leave the original list as it was. One
way to find out how this works is to experiment. We will start with the
setcar function.
First, we can make a list and then set the value of a variable to the list,
using the setq function. Here is a list of animals:
" 5 0) (89.99884033203125 338.13751220703125 449.4419250488281 437.8271484375 "(setq animals ’(antelope giraffe lion tiger))
If you are reading this in Info inside of GNU Emacs, you can evaluate this
expression in the usual fashion, by positioning the cursor after the expression
and typing C-x C-e.
(I’m doing this right here as I write this.
This is
one of the advantages of having the interpreter built into the computing
environment.)
When we evaluate the variable animals, we see that it is bound to the
list (antelope giraffe lion tiger):
" 6 0) (89.997314453125 443.9775085449219 449.5286865234375 544.2672119140625 "animals
⇒ (antelope giraffe lion tiger)
Put another way, the variable animals points to the list (antelope giraffe
lion tiger).
Next, evaluate the function setcar while passing it two arguments, the
variable animals and the quoted symbol hippopotamus; this is done by
writing the three element list (setcar animals ’hippopotamus) and then
evaluating it in the usual fashion:
" 7 0) (89.9971923828125 550.5375366210938 449.12408447265625 587.2271728515625 "(setcar animals ’hippopotamus)
After evaluating this expression, evaluate the variable animals again. You
will see that the list of animals has changed:
" 8 0) (89.99752807617188 593.4974975585938 420.6189880371094 630.7871704101562 "animals
⇒ (hippopotamus giraffe lion tiger)
The first element on the list, antelope is replaced by hippopotamus.
" 9 0)) (106 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "88
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (90.00006103515625 77.48908233642578 449.4975891113281 102.66727447509766 "So we can see that setcar did not add a new element to the list as cons
would have; it replaced giraffe with hippopotamus; it changed the list.
" 1 0) (90.0001220703125 119.18035125732422 163.20578002929688 133.55357360839844 "7.6 setcdr
" 2 0) (89.999755859375 141.2091064453125 449.41064453125 204.4272918701172 "The setcdr function is similar to the setcar function, except that the
function replaces the second and subsequent elements of a list rather than
the first element.
To see how this works, set the value of the variable to a list of domesti-
cated animals by evaluating the following expression:
" 3 0) (89.99969482421875 209.49765014648438 449.4212951660156 244.86729431152344 "(setq domesticated-animals ’(horse cow sheep goat))
If you now evaluate the list, you will be returned the list (horse cow sheep
goat):
" 4 0) (89.9986572265625 249.93765258789062 449.322509765625 310.8672790527344 "domesticated-animals
⇒ (horse cow sheep goat)
Next, evaluate setcdr with two arguments, the name of the variable
which has a list as its value, and the list to which the cdr of the first list
will be set;
" 5 0) (89.9986572265625 315.9376525878906 449.27886962890625 375.18731689453125 "(setcdr domesticated-animals ’(cat dog))
If you evaluate this expression, the list (cat dog) will appear in the echo
area. This is the value returned by the function. The result we are inter-
ested in is the “side effect”, which we can see by evaluating the variable
domesticated-animals:
" 6 0) (89.99832153320312 380.1376647949219 449.5284118652344 428.2274169921875 "domesticated-animals
⇒ (horse cat dog)
Indeed, the list is changed from (horse cow sheep goat) to (horse cat
dog). The cdr of the list is changed from (cow sheep goat) to (cat dog).
" 7 0) (89.99771118164062 444.6205139160156 176.97572326660156 458.9810485839844 "7.7 Exercise
" 8 0) (89.99710083007812 466.76922607421875 449.5281982421875 515.8274536132812 "Construct a list of four birds by evaluating several expressions with cons.
Find out what happens when you cons a list onto itself. Replace the first
element of the list of four birds with a fish. Replace the rest of that list with
a list of other fish.
" 9 0)) (107 (90.0 47.60907745361328 449.80364990234375 60.90726852416992 "zap-to-char
89
" 0 0) (90.0 75.14844512939453 325.3755187988281 92.38106536865234 "8 Cutting and Storing Text
" 1 0) (89.99948120117188 112.28907012939453 449.3558349609375 264.6672058105469 "Whenever you cut or clip text out of a buffer with a ‘kill’ command in
GNU Emacs, it is stored in a list and you can bring it back with a ‘yank’
command.
(The use of the word ‘kill’ in Emacs for processes which specifically do
not destroy the values of the entities is an unfortunate historical accident.
A much more appropriate word would be ‘clip’ since that is what the kill
commands do; they clip text out of a buffer and put it into storage from
which it can be brought back. I have often been tempted to replace globally
all occurrences of ‘kill’ in the Emacs sources with ‘clip’ and all occurrences
of ‘killed’ with ‘clipped’.)
When text is cut out of a buffer, it is stored on a list. Successive pieces
of text are stored on the list successively, so the list might look like this:
" 2 0) (90.00041198730469 271.4175720214844 440.9891357421875 296.7072448730469 "(\"a piece of text\" \"previous piece\")
The function cons can be used to add a piece of text to the list, like this:
" 3 0) (111.60003662109375 303.4576110839844 318.2345886230469 324.9039611816406 "(cons \"another piece\"
’(\"a piece of text\" \"previous piece\"))
" 4 0) (89.999755859375 329.0090637207031 449.3665771484375 354.3072509765625 "If you evaluate this expression, a list of three elements will appear in the
echo area:
" 5 0) (89.99966430664062 361.0576171875 449.464599609375 422.1072692871094 "(\"another piece\" \"a piece of text\" \"previous piece\")
With the car and nthcdr functions, you can retrieve whichever piece of
text you want. For example, in the following code, nthcdr 1 ... returns
the list with the first item removed; and the car returns the first element of
that remainder—the second element of the original list:
" 6 0) (89.99789428710938 428.9776306152344 449.49700927734375 630.787353515625 "(car (nthcdr 1 ’(\"another piece\"
\"a piece of text\"
\"previous piece\")))
⇒ \"a piece of text\"
The actual functions in Emacs are more complex than this, of course.
The code for cutting and retrieving text has to be written so that Emacs
can figure out which element in the list you want—the first, second, third,
or whatever. In addition, when you get to the end of the list, Emacs should
give you the first element of the list, rather than nothing at all.
The list that holds the pieces of text is called the kill ring. This chapter
leads up to a description of the kill ring and how it is used by first tracing how
the zap-to-char function works. This function uses (or ‘calls’) a function
that invokes a function that manipulates the kill ring. Thus, before reaching
the mountains, we climb the foothills.
A subsequent chapter describes how text that is cut from the buffer is
retrieved. See Chapter 10, “Yanking Text Back”, page 117.
" 7 0))))

(provide 'baleen)
;;; baleen.el ends here

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 20:53         ` dalanicolai
@ 2023-02-24 21:19           ` dalanicolai
  2023-02-24 21:43             ` dalanicolai
  2023-02-25 10:51           ` Eli Zaretskii
  1 sibling, 1 reply; 14+ messages in thread
From: dalanicolai @ 2023-02-24 21:19 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel

[-- Attachment #1: Type: text/plain, Size: 2496 bytes --]

Okay, in that attachment of my previous mail, I forgot to comment out the
`(set-window-margins nil 4)`.

So here I another mail (and attachment) with an extremely brief recipe:

- load the file in the attachment
- do `M-x baleen2`
- type 'emacs' followed by RET
- do `M-x find-function` `baleen2` and uncomment the line
`(set-window-margins nil 4)` in the function
- (re)evalute and repeat (do `M-x baleen2`, try typing 'emacs')

notice the buffer update speed difference

Any idea what might be causing this?

Thanks!

On Fri, 24 Feb 2023 at 21:53, dalanicolai <dalanicolai@gmail.com> wrote:

> B.t.w if someone want to have a look, I'll attach a smaller file here where
> I have just removed about 200 pages of the book text data, so that it is
> the file is much smaller, but there is still enough date to clearly show
> the
> 'undesired' behavior.
>
> So now, Emacs will not 'hang', but there will still be a clear difference
> in time it
> takes to update the buffer (between when window margins are displayed,
> and when they are not).
>
> On Fri, 24 Feb 2023 at 21:41, dalanicolai <dalanicolai@gmail.com> wrote:
>
>> I hope you might have an idea what causes this behavior. And maybe you
>> have a suggestion how to prevent it. Furthermore, I guess the behavior
>> might
>> be interesting for you to note/observe (but that is just a guess).
>>
>> On Fri, 24 Feb 2023 at 21:29, Eli Zaretskii <eliz@gnu.org> wrote:
>>
>>> > From: dalanicolai <dalanicolai@gmail.com>
>>> > Date: Fri, 24 Feb 2023 21:26:05 +0100
>>> > Cc: emacs-devel@gnu.org
>>> >
>>> > I have not really looked at it yet, but just as a quick thought:
>>> > I am not sure if/why I should debug an infloop, because the
>>> functionality
>>> > works perfectly fine when not showing the margins (i.e. when just
>>> setting
>>> > the window margins to nil). So it seems to me its not about an
>>> infinite loop.
>>> >
>>> > I was saying 'more or less' because it does not really hang, it just
>>> takes
>>> > extremely long to update the buffer text. When waiting long enough,
>>> > then it seems to continue.
>>> >
>>> > Of course, I don't want to waste your time, but I think my instructions
>>> > for reproducing the error, are very clear and short this time (i.e.
>>> take less
>>> > than/about a minute). I think it would be most informative if you
>>> reproduce the
>>> > error there.
>>>
>>> What should I do after I reproduce it, though?  What are your
>>> expectations from me (or whoever else tries your recipe)?
>>>
>>

[-- Attachment #2: Type: text/html, Size: 3847 bytes --]

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 20:41       ` dalanicolai
  2023-02-24 20:53         ` dalanicolai
@ 2023-02-24 21:25         ` Eli Zaretskii
  2023-02-24 21:41           ` dalanicolai
  1 sibling, 1 reply; 14+ messages in thread
From: Eli Zaretskii @ 2023-02-24 21:25 UTC (permalink / raw)
  To: dalanicolai; +Cc: emacs-devel

> From: dalanicolai <dalanicolai@gmail.com>
> Date: Fri, 24 Feb 2023 21:41:59 +0100
> Cc: emacs-devel@gnu.org
> 
> I hope you might have an idea what causes this behavior. And maybe you
> have a suggestion how to prevent it. Furthermore, I guess the behavior might
> be interesting for you to note/observe (but that is just a guess).

I'll try to see if I can find something, but in general if some Lisp
program is very slow, the first thing that's advisable is to profile
it with profiler.el.



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 21:25         ` Eli Zaretskii
@ 2023-02-24 21:41           ` dalanicolai
  0 siblings, 0 replies; 14+ messages in thread
From: dalanicolai @ 2023-02-24 21:41 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel

[-- Attachment #1: Type: text/plain, Size: 651 bytes --]

Great, thanks!

Also, this kind of suggestions are very helpful.

On Fri, 24 Feb 2023 at 22:25, Eli Zaretskii <eliz@gnu.org> wrote:

> > From: dalanicolai <dalanicolai@gmail.com>
> > Date: Fri, 24 Feb 2023 21:41:59 +0100
> > Cc: emacs-devel@gnu.org
> >
> > I hope you might have an idea what causes this behavior. And maybe you
> > have a suggestion how to prevent it. Furthermore, I guess the behavior
> might
> > be interesting for you to note/observe (but that is just a guess).
>
> I'll try to see if I can find something, but in general if some Lisp
> program is very slow, the first thing that's advisable is to profile
> it with profiler.el.
>

[-- Attachment #2: Type: text/html, Size: 1144 bytes --]

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 21:19           ` dalanicolai
@ 2023-02-24 21:43             ` dalanicolai
  0 siblings, 0 replies; 14+ messages in thread
From: dalanicolai @ 2023-02-24 21:43 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel


[-- Attachment #1.1: Type: text/plain, Size: 2704 bytes --]

Looks like this I forgot to attach the file

On Fri, 24 Feb 2023 at 22:19, dalanicolai <dalanicolai@gmail.com> wrote:

> Okay, in that attachment of my previous mail, I forgot to comment out the
> `(set-window-margins nil 4)`.
>
> So here I another mail (and attachment) with an extremely brief recipe:
>
> - load the file in the attachment
> - do `M-x baleen2`
> - type 'emacs' followed by RET
> - do `M-x find-function` `baleen2` and uncomment the line
> `(set-window-margins nil 4)` in the function
> - (re)evalute and repeat (do `M-x baleen2`, try typing 'emacs')
>
> notice the buffer update speed difference
>
> Any idea what might be causing this?
>
> Thanks!
>
> On Fri, 24 Feb 2023 at 21:53, dalanicolai <dalanicolai@gmail.com> wrote:
>
>> B.t.w if someone want to have a look, I'll attach a smaller file here
>> where
>> I have just removed about 200 pages of the book text data, so that it is
>> the file is much smaller, but there is still enough date to clearly show
>> the
>> 'undesired' behavior.
>>
>> So now, Emacs will not 'hang', but there will still be a clear difference
>> in time it
>> takes to update the buffer (between when window margins are displayed,
>> and when they are not).
>>
>> On Fri, 24 Feb 2023 at 21:41, dalanicolai <dalanicolai@gmail.com> wrote:
>>
>>> I hope you might have an idea what causes this behavior. And maybe you
>>> have a suggestion how to prevent it. Furthermore, I guess the behavior
>>> might
>>> be interesting for you to note/observe (but that is just a guess).
>>>
>>> On Fri, 24 Feb 2023 at 21:29, Eli Zaretskii <eliz@gnu.org> wrote:
>>>
>>>> > From: dalanicolai <dalanicolai@gmail.com>
>>>> > Date: Fri, 24 Feb 2023 21:26:05 +0100
>>>> > Cc: emacs-devel@gnu.org
>>>> >
>>>> > I have not really looked at it yet, but just as a quick thought:
>>>> > I am not sure if/why I should debug an infloop, because the
>>>> functionality
>>>> > works perfectly fine when not showing the margins (i.e. when just
>>>> setting
>>>> > the window margins to nil). So it seems to me its not about an
>>>> infinite loop.
>>>> >
>>>> > I was saying 'more or less' because it does not really hang, it just
>>>> takes
>>>> > extremely long to update the buffer text. When waiting long enough,
>>>> > then it seems to continue.
>>>> >
>>>> > Of course, I don't want to waste your time, but I think my
>>>> instructions
>>>> > for reproducing the error, are very clear and short this time (i.e.
>>>> take less
>>>> > than/about a minute). I think it would be most informative if you
>>>> reproduce the
>>>> > error there.
>>>>
>>>> What should I do after I reproduce it, though?  What are your
>>>> expectations from me (or whoever else tries your recipe)?
>>>>
>>>

[-- Attachment #1.2: Type: text/html, Size: 4267 bytes --]

[-- Attachment #2: baleen.el --]
[-- Type: text/x-emacs-lisp, Size: 307240 bytes --]

;;; baleen.el --- Search documents by filtering.     -*- lexical-binding: t; -*-

;; Copyright (C) 2023  Daniel Nicolai

;; Author: Daniel Nicolai <dalanicolai@gmail.com>
;; Keywords: tools

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; 

;;; Code:
(require 'cl-lib)
(require 'page-break-lines nil t)

(defun baleen-render (data)
  (dolist (page data)
    (let* ((props (cdr page))
           (max (1- (length props))))
      (seq-do-indexed (lambda (match i)
                        (let ((o (make-overlay (point)
                                               (progn (progn (insert (nth 4 match))
                                                             (point))))))
                          (overlay-put o
                                       'before-string (propertize " "
                                                                  'display `((margin left-margin)
                                                                             ,(propertize (format " %3d" (car page))
                                                                                          'face 'bold))
                                                                  )))
                        ;; (unless (= i max) (insert "\n")))
                      (insert "\n"))
                      props))
    (insert "\f\n")))

(defun baleen-filter-page (data query)
  (seq-filter (lambda (c)
               (string-match-p query (nth 4 c)))
             (cdr data)))

;; (baleen-filter-page (car test) "ho")

(defun baleen-filter (data query)
  (nreverse
   (seq-reduce (lambda (v p)
                 (if-let (m (baleen-filter-page p query))
                     (cons (cons (car p) m)
                           v)
                   v))
               data
               nil)))

;; (baleen-filter test "ho")

(defun baleen-update ()
  (let* ((query (minibuffer-contents))
         (query-length (length query))
         (parent-results (unless (< query-length 2)
                             (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
         (current-results (if parent-results
                              (baleen-filter parent-results query)
                            (unless (string-empty-p query) (baleen-filter test query)))))
    (when current-results
      (with-current-buffer (get-buffer-create "*baleen*")
        (erase-buffer)
        (baleen-render current-results))
      (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))))

(defun baleen ()
  (interactive)
  (pop-to-buffer "*baleen*")
  (set-window-margins nil 4)
  (when (featurep 'page-break-lines)
    (page-break-lines-mode))
  (minibuffer-with-setup-hook
      (lambda ()
        (add-hook 'post-command-hook #'baleen-update nil t))
    (dlet (baleen-results)
      (read-string "Baleen: ")
      (pp baleen-results)))
  (kill-buffer "*baleen*"))

;; NOTE alternatively use doc-pymupdf-text-blocks
(setq test '((1 (1 2 3 4 "hello emac")
                (2 3 4 5 "hoi ema"))
             (2 (3 4 2 4 "how do emil"))
             (3 (2 4 5 9 "emacs"))
             (4 (3 5 3 5 "emoe"))))

(defun baleen-update2 ()
  ;; (let ((query (minibuffer-contents)))
  ;;   (with-current-buffer (get-buffer-create "*baleen*")
  ;;     (erase-buffer)
  ;;     (baleen-render (baleen-filter test2 query)))))
  (let* ((query (minibuffer-contents))
         (query-length (length query)))
    (if (> (length previous-query) query-length)
        (with-current-buffer (get-buffer-create "*baleen*")
          (erase-buffer)
          (baleen-render (cdr (alist-get query baleen-results nil nil #'string=))))
      (let* ((parent-results (unless (< query-length 2)
                               (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
             (current-results (if parent-results
                                  (baleen-filter parent-results query)
                                (unless (string-empty-p query) (baleen-filter test2 query)))))
        (when current-results
          (with-current-buffer (get-buffer-create "*baleen*")
            (erase-buffer)
            (baleen-render current-results))
          (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))

        (setq previous-query query)))))

(defun baleen2 ()
  (interactive)
  (pop-to-buffer "*baleen*")
  (buffer-disable-undo)
  ;; (set-window-margins nil 4)
  (when (featurep 'page-break-lines)
    (page-break-lines-mode))
  (minibuffer-with-setup-hook
      (lambda ()
        (add-hook 'post-command-hook #'baleen-update2 nil t))
    (dlet (previous-query
           baleen-results)
      (read-string "Baleen: ")
      (print (length baleen-results))))
  (kill-buffer "*baleen*"))

;; NOTE alternatively use doc-pymupdf-text-blocks
(setq test2
      '((1 (189.0 195.02845764160156 350.99603271484375 212.2610626220703 "An Introduction to
" 0 0) (149.28021240234375 237.02845764160156 390.6446228027344 254.2610626220703 "Programming in Emacs Lisp
" 1 0)) (3 (172.8000030517578 267.5661315917969 367.04559326171875 288.2452697753906 "An Introduction to
" 0 0) (125.160400390625 306.9261169433594 414.5801696777344 327.6052551269531 "Programming in Emacs Lisp
" 1 0) (233.8809051513672 347.60906982421875 305.9354553222656 360.9072570800781 "Second Edition
" 2 0) (218.40089416503906 407.48907470703125 321.4480895996094 420.7872619628906 "by Robert J. Chassell
" 3 0)) (4 (89.999755859375 389.84906005859375 449.3995666503906 415.38726806640625 "Copyright c⃝ 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002 Free
Software Foundation, Inc.
" 0 0) (89.99954223632812 440.00909423828125 321.0759582519531 477.1872863769531 "Published by the Free Software Foundation, Inc.
59 Temple Place, Suite 330
Boston, MA 02111-1307 USA
" 1 0) (89.99752807617188 489.8091125488281 449.4958190917969 628.6273803710938 "Edition 2.05, 2001 Jan 5
ISBN 1-882114-43-4
Permission is granted to copy, distribute and/or modify this document under
the terms of the GNU Free Documentation License, Version 1.1 or any later
version published by the Free Software Foundation; there being no Invariant
Section, with the Front-Cover Texts being “A GNU Manual”, and with the
Back-Cover Texts as in (a) below. A copy of the license is included in the
section entitled “GNU Free Documentation License”.
(a) The FSF’s Back-Cover Text is: “You have freedom to copy and modify
this GNU Manual, like GNU software. Copies published by the Free Software
Foundation raise funds for GNU development.”
" 2 0)) (5 (446.760009765625 49.213592529296875 450.0118103027344 61.180747985839844 "i
" 0 0) (90.0 75.14844512939453 219.12728881835938 92.38106536865234 "Short Contents
" 1 0) (89.99615478515625 106.16294860839844 449.7834167480469 510.0864562988281 "Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1
List Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2
Practicing Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3
How To Write Function Definitions . . . . . . . . . . . . . . . . . . 29
4
A Few Buffer–Related Functions . . . . . . . . . . . . . . . . . . . . 51
5
A Few More Complex Functions . . . . . . . . . . . . . . . . . . . . 63
6
Narrowing and Widening . . . . . . . . . . . . . . . . . . . . . . . . . 77
7
car, cdr, cons: Fundamental Functions . . . . . . . . . . . . . 81
8
Cutting and Storing Text. . . . . . . . . . . . . . . . . . . . . . . . . 89
9
How Lists are Implemented. . . . . . . . . . . . . . . . . . . . . . . 113
10
Yanking Text Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
11
Loops and Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
12
Regular Expression Searches . . . . . . . . . . . . . . . . . . . . . . 149
13
Counting: Repetition and Regexps. . . . . . . . . . . . . . . . . . 167
14
Counting Words in a defun. . . . . . . . . . . . . . . . . . . . . . 181
15
Readying a Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
16
Your ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
18
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Appendix A
The the-the Function . . . . . . . . . . . . . . . . . . 241
Appendix B
Handling the Kill Ring . . . . . . . . . . . . . . . . . . . 243
Appendix C
A Graph with Labelled Axes . . . . . . . . . . . . . . . 255
Appendix D
GNU Free Documentation License . . . . . . . . . . . 279
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
" 2 0)) (6 (90.0 49.213592529296875 96.4916763305664 61.180747985839844 "ii
" 0 0)) (7 (440.8800048828125 47.60907745361328 449.89093017578125 60.90726852416992 "iii
" 0 0) (90.0 75.14844512939453 240.67727661132812 92.38106536865234 "Table of Contents
" 1 0) (90.00009155273438 117.08299255371094 449.61639404296875 193.38731384277344 "Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
On Reading this Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
For Whom This is Written. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Lisp History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
A Note for Novices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Thank You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv
" 2 0) (90.000732421875 207.6830291748047 449.66815185546875 535.1473999023438 "1
List Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1
Lisp Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1
Lisp Atoms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2
Whitespace in Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3
GNU Emacs Helps You Type Lists . . . . . . . . . . . . . . . 3
1.2
Run a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3
Generate an Error Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4
Symbol Names and Function Definitions . . . . . . . . . . . . . . . . . . 6
1.5
The Lisp Interpreter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5.1
Byte Compiling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6
Evaluation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6.1
Evaluating Inner Lists . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7.1
Error Message for a Symbol Without a Function. . 11
1.7.2
Error Message for a Symbol Without a Value . . . . 11
1.8
Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8.1
Arguments’ Data Types . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8.2
An Argument as the Value of a Variable or List . . 13
1.8.3
Variable Number of Arguments . . . . . . . . . . . . . . . . . 14
1.8.4
Using the Wrong Type Object as an Argument . . 14
1.8.5
The message Function . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9
Setting the Value of a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9.1
Using set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9.2
Using setq. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.9.3
Counting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.10
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.11
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
" 3 0) (90.00164794921875 549.443115234375 449.662109375 625.7474365234375 "2
Practicing Evaluation . . . . . . . . . . . . . . . . . . . . . 23
2.1
Buffer Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2
Getting Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3
Switching Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4
Buffer Size and the Location of Point . . . . . . . . . . . . . . . . . . . . 27
2.5
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
" 4 0)) (8 (90.0 47.60907745361328 98.74909210205078 60.90726852416992 "iv
" 0 0) (90.0 71.24296569824219 449.7541198730469 314.9472961425781 "3
How To Write Function Definitions . . . . . . . . 29
3.1
The defun Special Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2
Install a Function Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1
Change a Function Definition. . . . . . . . . . . . . . . . . . . 32
3.3
Make a Function Interactive . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.1
An Interactive multiply-by-seven .. . . . . . . . . . . . 34
3.4
Different Options for interactive . . . . . . . . . . . . . . . . . . . . . . 35
3.5
Install Code Permanently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6
let . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.6.1
The Parts of a let Expression . . . . . . . . . . . . . . . . . . 37
3.6.2
Sample let Expression. . . . . . . . . . . . . . . . . . . . . . . . . 38
3.6.3
Uninitialized Variables in a let Statement. . . . . . . 39
3.7
The if Special Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7.1
The type-of-animal Function in Detail. . . . . . . . . 41
3.8
If–then–else Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.9
Truth and Falsehood in Emacs Lisp . . . . . . . . . . . . . . . . . . . . . 43
3.10
save-excursion .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.10.1
Template for a save-excursion Expression . . . . 45
3.11
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.12
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
" 1 0) (90.00115966796875 329.24298095703125 449.7353210449219 465.30731201171875 "4
A Few Buffer–Related Functions. . . . . . . . . . . 51
4.1
Finding More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.2
A Simplified beginning-of-buffer Definition. . . . . . . . . . . . 52
4.3
The Definition of mark-whole-buffer . . . . . . . . . . . . . . . . . . . 54
4.3.1
Body of mark-whole-buffer .. . . . . . . . . . . . . . . . . . 55
4.4
The Definition of append-to-buffer . . . . . . . . . . . . . . . . . . . . 56
4.4.1
The append-to-buffer Interactive Expression. . . 57
4.4.2
The Body of append-to-buffer .. . . . . . . . . . . . . . . 57
4.4.3
save-excursion in append-to-buffer.. . . . . . . . . 58
4.5
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.6
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
" 2 0)) (9 (444.239990234375 47.60907745361328 450.0 60.90726852416992 "v
" 0 0) (90.0 71.24296569824219 449.7479553222656 291.0672912597656 "5
A Few More Complex Functions . . . . . . . . . . . 63
5.1
The Definition of copy-to-buffer.. . . . . . . . . . . . . . . . . . . . . . 63
5.2
The Definition of insert-buffer.. . . . . . . . . . . . . . . . . . . . . . . 64
5.2.1
The Interactive Expression in insert-buffer.. . . 65
A Read-only Buffer. . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
‘b’ in an Interactive Expression. . . . . . . . . . . . . . . . . 65
5.2.2
The Body of the insert-buffer Function . . . . . . . 65
5.2.3
insert-buffer With an if Instead of an or. . . . . 66
5.2.4
The or in the Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.2.5
The let Expression in insert-buffer .. . . . . . . . . 68
5.3
Complete Definition of beginning-of-buffer .. . . . . . . . . . . 69
5.3.1
Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.3.2
beginning-of-buffer with an Argument . . . . . . . 71
What happens in a large buffer. . . . . . . . . . . . . . . . . 71
What happens in a small buffer . . . . . . . . . . . . . . . . 72
5.3.3
The Complete beginning-of-buffer .. . . . . . . . . . 73
5.4
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.5
optional Argument Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
" 1 0) (89.99783325195312 305.3630065917969 449.7347106933594 357.7873229980469 "6
Narrowing and Widening. . . . . . . . . . . . . . . . . . 77
6.1
The save-restriction Special Form . . . . . . . . . . . . . . . . . . . . 77
6.2
what-line.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.3
Exercise with Narrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
" 2 0) (89.9976806640625 372.0830078125 449.7032775878906 484.267333984375 "7
car, cdr, cons: Fundamental Functions . . . . . 81
7.1
car and cdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.2
cons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2.1
Find the Length of a List: length . . . . . . . . . . . . . . 84
7.3
nthcdr .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.4
nth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.5
setcar .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.6
setcdr .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.7
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
" 3 0)) (10 (90.0 47.60907745361328 98.78182220458984 60.90726852416992 "vi
" 0 0) (90.0 71.24296569824219 449.7066650390625 302.9472961425781 "8
Cutting and Storing Text . . . . . . . . . . . . . . . . . 89
8.1
zap-to-char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.1.1
The interactive Expression . . . . . . . . . . . . . . . . . . . 90
8.1.2
The Body of zap-to-char.. . . . . . . . . . . . . . . . . . . . . 91
8.1.3
The search-forward Function . . . . . . . . . . . . . . . . . 92
8.1.4
The progn Special Form . . . . . . . . . . . . . . . . . . . . . . . 93
8.1.5
Summing up zap-to-char . . . . . . . . . . . . . . . . . . . . . 93
8.2
kill-region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.2.1
condition-case.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
8.2.2
delete-and-extract-region . . . . . . . . . . . . . . . . . . 96
8.3
delete-and-extract-region: Digressing into C . . . . . . . . . 98
8.4
Initializing a Variable with defvar . . . . . . . . . . . . . . . . . . . . . 100
8.4.1
defvar and an asterisk. . . . . . . . . . . . . . . . . . . . . . . . 101
8.5
copy-region-as-kill.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.5.1
The Body of copy-region-as-kill.. . . . . . . . . . . 103
The kill-append function. . . . . . . . . . . . . . . . . . . . 104
The kill-new function . . . . . . . . . . . . . . . . . . . . . . . 105
8.6
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.7
Searching Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
" 1 0) (90.00201416015625 317.3630065917969 449.6243896484375 357.7873229980469 "9
How Lists are Implemented . . . . . . . . . . . . . . 113
9.1
Symbols as a Chest of Drawers . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.2
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
" 2 0) (90.00247192382812 372.0830078125 449.5589599609375 424.50732421875 "10
Yanking Text Back . . . . . . . . . . . . . . . . . . . . . 117
10.1
Kill Ring Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
10.2
The kill-ring-yank-pointer Variable . . . . . . . . . . . . . . . 117
10.3
Exercises with yank and nthcdr. . . . . . . . . . . . . . . . . . . . . . . 119
" 3 0) (90.00210571289062 438.9230041503906 449.5998229980469 622.7473754882812 "11
Loops and Recursion. . . . . . . . . . . . . . . . . . . . 121
11.1
while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
11.1.1
A while Loop and a List. . . . . . . . . . . . . . . . . . . . . 122
11.1.2
An Example: print-elements-of-list . . . . . . 123
11.1.3
A Loop with an Incrementing Counter . . . . . . . . 124
Example with incrementing counter . . . . . . . . . . . 125
The parts of the function definition. . . . . . . . . . . . 126
Putting the function definition together . . . . . . . . 127
11.1.4
Loop with a Decrementing Counter . . . . . . . . . . . 129
Example with decrementing counter . . . . . . . . . . . 129
The parts of the function definition. . . . . . . . . . . . 130
Putting the function definition together . . . . . . . . 130
11.2
Save your time: dolist and dotimes . . . . . . . . . . . . . . . . . . 131
The dolist Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
The dotimes Macro . . . . . . . . . . . . . . . . . . . . . . . . . . 133
" 4 0)) (11 (438.239990234375 47.60907745361328 450.0108947753906 60.90726852416992 "vii
" 0 0) (125.8800048828125 71.48908233642578 449.4754333496094 240.1873016357422 "11.3
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
11.3.1
Building Robots: Extending the Metaphor. . . . . 134
11.3.2
The Parts of a Recursive Definition . . . . . . . . . . . 135
11.3.3
Recursion with a List . . . . . . . . . . . . . . . . . . . . . . . . 136
11.3.4
Recursion in Place of a Counter . . . . . . . . . . . . . . 137
An argument of 3 or 4. . . . . . . . . . . . . . . . . . . . . . . . 138
11.3.5
Recursion Example Using cond . . . . . . . . . . . . . . . 139
11.3.6
Recursive Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Recursive Pattern: every . . . . . . . . . . . . . . . . . . . . . 141
Recursive Pattern: accumulate . . . . . . . . . . . . . . . . 142
Recursive Pattern: keep . . . . . . . . . . . . . . . . . . . . . . 143
11.3.7
Recursion without Deferments . . . . . . . . . . . . . . . . 143
11.3.8
No Deferment Solution. . . . . . . . . . . . . . . . . . . . . . . 145
11.4
Looping Exercise. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
" 1 0) (90.00149536132812 254.60301208496094 449.6435241699219 462.4273376464844 "12
Regular Expression Searches . . . . . . . . . . . . 149
12.1
The Regular Expression for sentence-end .. . . . . . . . . . . . 149
12.2
The re-search-forward Function. . . . . . . . . . . . . . . . . . . . . 150
12.3
forward-sentence .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
The while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
The regular expression search . . . . . . . . . . . . . . . . . . . . . . . . 154
12.4
forward-paragraph: a Goldmine of Functions . . . . . . . . . 155
The let* expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
The forward motion while loop . . . . . . . . . . . . . . . . . . . . . . 158
Between paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Within paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
No fill prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
With a fill prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Summary.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12.5
Create Your Own ‘TAGS’ File. . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.6
Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.7
Exercises with re-search-forward.. . . . . . . . . . . . . . . . . . . 166
" 2 0) (90.00076293945312 476.7230224609375 449.64251708984375 541.02734375 "13
Counting: Repetition and Regexps . . . . . . 167
13.1
The count-words-region Function . . . . . . . . . . . . . . . . . . . 167
13.1.1
The Whitespace Bug in count-words-region.. 170
13.2
Count Words Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
13.3
Exercise: Counting Punctuation . . . . . . . . . . . . . . . . . . . . . . . 179
" 3 0)) (12 (90.0 47.60907745361328 104.76000213623047 60.90726852416992 "viii
" 0 0) (90.0 71.24296569824219 449.6117858886719 243.1873016357422 "14
Counting Words in a defun . . . . . . . . . . . . . . 181
14.1
What to Count? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
14.2
What Constitutes a Word or Symbol? . . . . . . . . . . . . . . . . . 182
14.3
The count-words-in-defun Function . . . . . . . . . . . . . . . . . 183
14.4
Count Several defuns Within a File . . . . . . . . . . . . . . . . . . . 186
14.5
Find a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
14.6
lengths-list-file in Detail . . . . . . . . . . . . . . . . . . . . . . . . . 188
14.7
Count Words in defuns in Different Files . . . . . . . . . . . . . . 190
14.7.1
The append Function . . . . . . . . . . . . . . . . . . . . . . . . 191
14.8
Recursively Count Words in Different Files. . . . . . . . . . . . . 192
14.9
Prepare the Data for Display in a Graph . . . . . . . . . . . . . . . 193
14.9.1
Sorting Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
14.9.2
Making a List of Files. . . . . . . . . . . . . . . . . . . . . . . . 194
14.9.3
Counting function definitions . . . . . . . . . . . . . . . . . 197
" 1 0) (89.99942016601562 257.6029968261719 449.582275390625 321.9073181152344 "15
Readying a Graph . . . . . . . . . . . . . . . . . . . . . . 203
15.1
The graph-body-print Function. . . . . . . . . . . . . . . . . . . . . . 208
15.2
The recursive-graph-body-print Function. . . . . . . . . . . 210
15.3
Need for Printed Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
15.4
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
" 2 0) (89.99984741210938 336.2030029296875 449.5562744140625 520.1473388671875 "16
Your ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . 213
16.1
Site-wide Initialization Files. . . . . . . . . . . . . . . . . . . . . . . . . . . 213
16.2
Specifying Variables using defcustom.. . . . . . . . . . . . . . . . . 214
16.3
Beginning a ‘.emacs’ File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
16.4
Text and Auto Fill Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
16.5
Mail Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.6
Indent Tabs Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
16.7
Some Keybindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
16.8
Keymaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
16.9
Loading Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
16.10
Autoloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
16.11
A Simple Extension: line-to-top-of-window . . . . . . . . 224
16.12
X11 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
16.13
Miscellaneous Settings for a ‘.emacs’ File . . . . . . . . . . . . . 227
16.14
A Modified Mode Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
" 3 0) (90.00198364257812 534.5630493164062 449.5606689453125 610.8673706054688 "17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
17.1
debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
17.2
debug-on-entry .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
17.3
debug-on-quit and (debug).. . . . . . . . . . . . . . . . . . . . . . . . . 234
17.4
The edebug Source Level Debugger. . . . . . . . . . . . . . . . . . . . 235
17.5
Debugging Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
" 4 0)) (13 (441.239990234375 47.60907745361328 449.9891052246094 60.90726852416992 "ix
" 0 0) (90.0 71.24296569824219 449.5467834472656 85.66089630126953 "18
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
" 1 0) (90.0001220703125 102.08299255371094 449.6182556152344 116.51359558105469 "Appendix A
The the-the Function. . . . . . . . . . 241
" 2 0) (89.99960327148438 133.0430145263672 449.6458740234375 269.1073303222656 "Appendix B
Handling the Kill Ring . . . . . . . . 243
B.1
The rotate-yank-pointer Function . . . . . . . . . . . . . . . . . . . 243
B.1.1
The Body of rotate-yank-pointer .. . . . . . . . . . 244
The else-part of the if expression . . . . . . . . . . . . . 245
The % remainder function . . . . . . . . . . . . . . . . . . . . . 247
Using % in rotate-yank-pointer . . . . . . . . . . . . . 248
Pointing to the last element. . . . . . . . . . . . . . . . . . . 248
B.2
yank.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Passing the argument . . . . . . . . . . . . . . . . . . . . . . . . 250
Passing a negative argument . . . . . . . . . . . . . . . . . . 251
B.3
yank-pop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
" 3 0) (90.0001220703125 283.4030456542969 449.68988037109375 479.3473815917969 "Appendix C
A Graph with Labelled Axes. . . 255
C.1
The print-graph Varlist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
C.2
The print-Y-axis Function. . . . . . . . . . . . . . . . . . . . . . . . . . . 256
C.2.1
Side Trip: Compute a Remainder. . . . . . . . . . . . . . 258
C.2.2
Construct a Y Axis Element . . . . . . . . . . . . . . . . . . 259
C.2.3
Create a Y Axis Column. . . . . . . . . . . . . . . . . . . . . . 261
C.2.4
The Not Quite Final Version of print-Y-axis.. 262
C.3
The print-X-axis Function. . . . . . . . . . . . . . . . . . . . . . . . . . . 263
C.3.1
X Axis Tic Marks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
C.4
Printing the Whole Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
C.4.1
Testing print-graph .. . . . . . . . . . . . . . . . . . . . . . . . 270
C.4.2
Graphing Numbers of Words and Symbols . . . . . 271
C.4.3
A lambda Expression: Useful Anonymity. . . . . . . 272
C.4.4
The mapcar Function. . . . . . . . . . . . . . . . . . . . . . . . . 274
C.4.5
Another Bug . . . Most Insidious . . . . . . . . . . . . . . 274
C.4.6
The Printed Graph. . . . . . . . . . . . . . . . . . . . . . . . . . . 277
" 4 0) (89.99880981445312 493.7004699707031 449.52435302734375 524.02099609375 "Appendix D
GNU Free Documentation License
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
" 5 0) (89.99868774414062 540.443115234375 449.5042724609375 554.8610229492188 "Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
" 6 0)) (14 (90.0 47.60907745361328 95.76000213623047 60.90726852416992 "x
" 0 0)) (15 (90.0 47.60907745361328 449.83599853515625 60.90726852416992 "On Reading this Text
xi
" 0 0) (90.00021362304688 75.14844512939453 152.6470489501953 92.38106536865234 "Preface
" 1 0) (89.999267578125 102.08905792236328 449.4326477050781 360.4271545410156 "Most of the GNU Emacs integrated environment is written in the pro-
gramming language called Emacs Lisp. The code written in this program-
ming language is the software—the sets of instructions—that tell the com-
puter what to do when you give it commands. Emacs is designed so that
you can write new code in Emacs Lisp and easily install it as an extension
to the editor.
(GNU Emacs is sometimes called an “extensible editor”, but it does much
more than provide editing capabilities.
It is better to refer to Emacs as
an “extensible computing environment”. However, that phrase is quite a
mouthful.
It is easier to refer to Emacs simply as an editor.
Moreover,
everything you do in Emacs—find the Mayan date and phases of the moon,
simplify polynomials, debug code, manage files, read letters, write books—all
these activities are kinds of editing in the most general sense of the word.)
Although Emacs Lisp is usually thought of in association only with
Emacs, it is a full computer programming language. You can use Emacs
Lisp as you would any other programming language.
Perhaps you want to understand programming; perhaps you want to ex-
tend Emacs; or perhaps you want to become a programmer. This introduc-
tion to Emacs Lisp is designed to get you started: to guide you in learning
the fundamentals of programming, and more importantly, to show you how
you can teach yourself to go further.
" 2 0) (90.00047302246094 376.2202453613281 243.05418395996094 390.5807800292969 "On Reading this Text
" 3 0) (89.99932861328125 398.24896240234375 449.6614685058594 630.7872314453125 "All through this document, you will see little sample programs you can
run inside of Emacs.
If you read this document in Info inside of GNU
Emacs, you can run the programs as they appear. (This is easy to do and
is explained when the examples are presented.) Alternatively, you can read
this introduction as a printed book while sitting beside a computer running
Emacs. (This is what I like to do; I like printed books.) If you don’t have a
running Emacs beside you, you can still read this book, but in this case, it
is best to treat it as a novel or as a travel guide to a country not yet visited:
interesting, but not the same as being there.
Much of this introduction is dedicated to walk-throughs or guided tours
of code used in GNU Emacs. These tours are designed for two purposes:
first, to give you familiarity with real, working code (code you use every
day); and, second, to give you familiarity with the way Emacs works. It is
interesting to see how a working environment is implemented. Also, I hope
that you will pick up the habit of browsing through source code. You can
learn from it and mine it for ideas. Having GNU Emacs is like having a
dragon’s cave of treasures.
In addition to learning about Emacs as an editor and Emacs Lisp as
a programming language, the examples and guided tours will give you an
" 4 0)) (16 (90.0 47.60907745361328 449.8251953125 60.90726852416992 "xii
Preface
" 0 0) (89.99826049804688 77.48908233642578 449.3992919921875 201.1873016357422 "opportunity to get acquainted with Emacs as a Lisp programming environ-
ment. GNU Emacs supports programming and provides tools that you will
want to become comfortable using, such as M-. (the key which invokes the
find-tag command). You will also learn about buffers and other objects
that are part of the environment. Learning about these features of Emacs is
like learning new routes around your home town.
Finally, I hope to convey some of the skills for using Emacs to learn
aspects of programming that you don’t know. You can often use Emacs to
help you understand what puzzles you or to find out how to do something
new. This self-reliance is not only a pleasure, but an advantage.
" 1 0) (89.99856567382812 221.06036376953125 279.07073974609375 235.4208984375 "For Whom This is Written
" 2 0) (89.99630737304688 244.049072265625 449.50616455078125 630.7874755859375 "This text is written as an elementary introduction for people who are not
programmers. If you are a programmer, you may not be satisfied with this
primer. The reason is that you may have become expert at reading reference
manuals and be put off by the way this text is organized.
An expert programmer who reviewed this text said to me:
I prefer to learn from reference manuals. I “dive into” each para-
graph, and “come up for air” between paragraphs.
When I get to the end of a paragraph, I assume that that subject
is done, finished, that I know everything I need (with the possible
exception of the case when the next paragraph starts talking about
it in more detail). I expect that a well written reference manual
will not have a lot of redundancy, and that it will have excellent
pointers to the (one) place where the information I want is.
This introduction is not written for this person!
Firstly, I try to say everything at least three times: first, to introduce it;
second, to show it in context; and third, to show it in a different context, or
to review it.
Secondly, I hardly ever put all the information about a subject in one
place, much less in one paragraph. To my way of thinking, that imposes
too heavy a burden on the reader. Instead I try to explain only what you
need to know at the time. (Sometimes I include a little extra information
so you won’t be surprised later when the additional information is formally
introduced.)
When you read this text, you are not expected to learn everything the first
time. Frequently, you need only make, as it were, a ‘nodding acquaintance’
with some of the items mentioned. My hope is that I have structured the
text and given you enough hints that you will be alert to what is important,
and concentrate on it.
You will need to “dive into” some paragraphs; there is no other way to
read them. But I have tried to keep down the number of such paragraphs.
" 3 0)) (17 (90.0 47.60907745361328 449.7156982421875 60.90726852416992 "A Note for Novices
xiii
" 0 0) (89.99826049804688 77.48908233642578 449.42022705078125 188.34727478027344 "This book is intended as an approachable hill, rather than as a daunting
mountain.
This introduction to Programming in Emacs Lisp has a companion doc-
ument, The GNU Emacs Lisp Reference Manual. The reference manual has
more detail than this introduction. In the reference manual, all the infor-
mation about one topic is concentrated in one place. You should turn to it
if you are like the programmer quoted above. And, of course, after you have
read this Introduction, you will find the Reference Manual useful when you
are writing your own programs.
" 1 0) (89.99887084960938 204.8603515625 177.66000366210938 219.22088623046875 "Lisp History
" 2 0) (89.999267578125 226.88909912109375 449.4208068847656 337.8672790527344 "Lisp was first developed in the late 1950s at the Massachusetts Institute
of Technology for research in artificial intelligence. The great power of the
Lisp language makes it superior for other purposes as well, such as writing
editor commands and integrated environments.
GNU Emacs Lisp is largely inspired by Maclisp, which was written at
MIT in the 1960s. It is somewhat inspired by Common Lisp, which became
a standard in the 1980s. However, Emacs Lisp is much simpler than Common
Lisp. (The standard Emacs distribution contains an optional extensions file,
‘cl.el’, that adds many Common Lisp features to Emacs Lisp.)
" 3 0) (89.99957275390625 354.2603759765625 226.11309814453125 368.62091064453125 "A Note for Novices
" 4 0) (89.99993896484375 376.4090881347656 449.44329833984375 443.3298034667969 "If you don’t know GNU Emacs, you can still read this document prof-
itably. However, I recommend you learn Emacs, if only to learn to move
around your computer screen. You can teach yourself how to use Emacs
with the on-line tutorial. To use it, type C-h t. (This means you press and
release the ⟨
" 5 0) (145.54800415039062 427.552001953125 169.30799865722656 428.0320129394531 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (145.55999755859375 428.7624206542969 169.3109130859375 436.7325134277344 "CTRL
" 7 0) (145.54800415039062 436.1919860839844 169.30799865722656 436.6719970703125 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99853515625 423.80908203125 449.4320983886719 541.0098266601562 "⟩ key and the h at the same time, and then press and release
t.)
Also, I often refer to one of Emacs’ standard commands by listing the
keys which you press to invoke the command and then giving the name of
the command in parentheses, like this: M-C-\\ (indent-region). What this
means is that the indent-region command is customarily invoked by typing
M-C-\\. (You can, if you wish, change the keys that are typed to invoke the
command; this is called rebinding. See Section 16.8, “Keymaps”, page 221.)
The abbreviation M-C-\\ means that you type your ⟨
" 9 0) (344.26800537109375 525.2319946289062 369.5880126953125 525.7119750976562 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (344.2799987792969 526.4424438476562 369.5664978027344 534.41259765625 "META
" 11 0) (344.26800537109375 533.751953125 369.5880126953125 534.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (369.0 521.4890747070312 403.426513671875 541.0098266601562 "⟩ key, ⟨
" 13 0) (402.7080078125 525.2319946289062 426.468017578125 525.7119750976562 "<image: None, width: 1, height: 1, bpc: 1>" 14 1) (402.7200012207031 526.4424438476562 426.4709167480469 534.41259765625 "CTRL
" 15 0) (402.7080078125 533.751953125 426.468017578125 534.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 16 1) (90.00009155273438 521.4890747070312 449.8581848144531 552.8898315429688 "⟩ key
and ⟨
" 17 0) (114.58800506591797 536.751953125 120.34800720214844 537.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 18 1) (114.5999984741211 535.5726928710938 120.32727813720703 546.8636474609375 "\\
" 19 0) (114.58800506591797 545.751953125 120.34800720214844 546.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 20 1) (119.76000213623047 533.3690795898438 422.3863830566406 552.8897705078125 "⟩ key all at the same time. (On many modern keyboards the ⟨
" 21 0) (421.66802978515625 537.1119995117188 446.988037109375 537.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 22 1) (421.67999267578125 538.3223876953125 446.9664001464844 546.2925415039062 "META
" 23 0) (421.66802978515625 545.751953125 446.988037109375 546.23193359375 "<image: None, width: 1, height: 1, bpc: 1>" 24 1) (90.0 536.97314453125 449.9865417480469 564.8897705078125 "⟩
key is labelled ⟨
" 25 0) (161.26800537109375 549.1119995117188 178.42800903320312 549.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 26 1) (161.27999877929688 550.3223876953125 178.3014678955078 558.2925415039062 "ALT
" 27 0) (161.26800537109375 557.6319580078125 178.42800903320312 558.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 28 1) (89.99942016601562 545.7290649414062 449.3890380859375 588.769775390625 "⟩.) Sometimes a combination like this is called a keychord,
since it is similar to the way you play a chord on a piano. If your keyboard
does not have a ⟨
" 29 0) (174.58799743652344 572.991943359375 199.90798950195312 573.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 30 1) (174.60000610351562 574.202392578125 199.8865203857422 582.1725463867188 "META
" 31 0) (174.58799743652344 581.6319580078125 199.90798950195312 582.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 32 1) (199.32000732421875 569.2490844726562 253.54656982421875 588.7698364257812 "⟩ key, the ⟨
" 33 0) (252.8280029296875 572.991943359375 269.50799560546875 573.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 34 1) (252.83999633789062 574.202392578125 269.3859558105469 582.1725463867188 "ESC
" 35 0) (252.8280029296875 581.6319580078125 269.50799560546875 582.1119384765625 "<image: None, width: 1, height: 1, bpc: 1>" 36 1) (90.00003051757812 569.2490844726562 449.7705993652344 600.7698364257812 "⟩ key prefix is used in place of it. In
this case, M-C-\\ means that you press and release your ⟨
" 37 0) (363.3479919433594 584.991943359375 380.0279846191406 585.471923828125 "<image: None, width: 1, height: 1, bpc: 1>" 38 1) (363.3599853515625 586.202392578125 379.90594482421875 594.1725463867188 "ESC
" 39 0) (363.3479919433594 593.5120239257812 380.0279846191406 593.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 40 1) (90.00039672851562 581.2490844726562 449.8471374511719 612.7698364257812 "⟩ key and then
type the ⟨
" 41 0) (137.7480010986328 596.9920043945312 161.50799560546875 597.4719848632812 "<image: None, width: 1, height: 1, bpc: 1>" 42 1) (137.75999450683594 598.202392578125 161.5109100341797 606.1725463867188 "CTRL
" 43 0) (137.7480010986328 605.5120239257812 161.50799560546875 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 44 1) (161.0399932861328 593.2490844726562 234.58642578125 612.7698364257812 "⟩ key and the ⟨
" 45 0) (233.9879913330078 596.5120239257812 239.74798583984375 596.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 46 1) (234.0 595.4526977539062 239.72727966308594 606.74365234375 "\\
" 47 0) (233.9879913330078 605.5120239257812 239.74798583984375 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 48 1) (90.00027465820312 593.2490844726562 449.7488708496094 624.6498413085938 "⟩ key at the same time. But usually M-C-\\
means press the ⟨
" 49 0) (172.42800903320312 608.8720092773438 196.18800354003906 609.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 50 1) (172.44000244140625 610.0823974609375 196.19091796875 618.0525512695312 "CTRL
" 51 0) (172.42800903320312 617.5120239257812 196.18800354003906 617.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 52 1) (195.60000610351562 605.1290893554688 393.1064147949219 624.6497802734375 "⟩ key along with the key that is labelled ⟨
" 53 0) (392.38800048828125 608.8720092773438 409.5480041503906 609.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 54 1) (392.3999938964844 610.0823974609375 409.42144775390625 618.0525512695312 "ALT
" 55 0) (392.38800048828125 617.5120239257812 409.5480041503906 617.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 56 1) (90.00039672851562 605.1290893554688 449.869140625 636.6497802734375 "⟩ and, at
the same time, press the ⟨
" 57 0) (213.10801696777344 620.3919677734375 218.86801147460938 620.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 58 1) (213.1199951171875 619.3327026367188 218.84727478027344 630.6236572265625 "\\
" 59 0) (213.10801696777344 629.3919677734375 218.86801147460938 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 60 1) (218.27999877929688 617.1290893554688 243.59999084472656 636.289794921875 "⟩ key.
" 61 0)) (18 (90.0 47.60907745361328 449.8251953125 60.90726852416992 "xiv
Preface
" 0 0) (89.9986572265625 77.48908233642578 449.4637756347656 194.2097930908203 "In addition to typing a lone keychord, you can prefix what you type with
C-u, which is called the ‘universal argument’. The C-u keychord passes an
argument to the subsequent command. Thus, to indent a region of plain
text by 6 spaces, mark the region, and then type C-u 6 M-C-\\. (If you do
not specify a number, Emacs either passes the number 4 to the command
or otherwise runs the command differently than it would otherwise.) See
section “Numeric Arguments” in The GNU Emacs Manual.
If you are reading this in Info using GNU Emacs, you can read through
this whole document just by pressing the space bar, ⟨
" 1 0) (346.3080139160156 178.43194580078125 362.9880065917969 178.9119415283203 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (346.32000732421875 179.6424102783203 362.865966796875 187.61251831054688 "SPC
" 3 0) (346.3080139160156 187.072021484375 362.9880065917969 187.55201721191406 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (89.9993896484375 175.049072265625 449.90179443359375 238.2672576904297 "⟩. (To learn about
Info, type C-h i and then select Info.)
A note on terminology: when I use the word Lisp alone, I often am
referring to the various dialects of Lisp in general, but when I speak of
Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
" 5 0) (89.99943542480469 254.66033935546875 168.7605743408203 269.0208740234375 "Thank You
" 6 0) (89.99978637695312 276.6890869140625 449.869384765625 352.26727294921875 "My thanks to all who helped me with this book. My especial thanks to
Jim Blandy, Noah Friedman, Jim Kingdon, Roland McGrath, Frank Ritter,
Randy Smith, Richard M. Stallman, and Melissa Weisshaus.
My thanks
also go to both Philip Johnson and David Stampe for their patient encour-
agement. My mistakes are my own.
Robert J. Chassell
" 7 0)) (19 (90.0 47.60907745361328 449.9559631347656 60.90726852416992 "Lisp Atoms
1
" 0 0) (89.9993896484375 75.14844512939453 237.94793701171875 92.38106536865234 "1 List Processing
" 1 0) (89.9981689453125 104.12909698486328 449.4855041503906 189.1873016357422 "To the untutored eye, Lisp is a strange programming language. In Lisp
code there are parentheses everywhere. Some people even claim that the
name stands for ‘Lots of Isolated Silly Parentheses’. But the claim is un-
warranted. Lisp stands for LISt Processing, and the programming language
handles lists (and lists of lists) by putting them between parentheses. The
parentheses mark the boundaries of the list. Sometimes a list is preceded by
a single apostrophe or quotation mark, ‘’’. Lists are the basis of Lisp.
" 2 0) (89.99810791015625 206.18035888671875 186.65130615234375 220.5408935546875 "1.1 Lisp Lists
" 3 0) (89.997314453125 228.4490966796875 449.47412109375 277.6272888183594 "In Lisp, a list looks like this: ’(rose violet daisy buttercup). This
list is preceded by a single apostrophe. It could just as well be written as
follows, which looks more like the kind of list you are likely to be familiar
with:
" 4 0) (89.99658203125 282.6976623535156 449.4080810546875 481.8672790527344 "’(rose
violet
daisy
buttercup)
The elements of this list are the names of the four different flowers, separated
from each other by whitespace and surrounded by parentheses, like flowers
in a field with a stone wall around them.
Lists can also have numbers in them, as in this list: (+ 2 2). This list
has a plus-sign, ‘+’, followed by two ‘2’s, each separated by whitespace.
In Lisp, both data and programs are represented the same way; that is,
they are both lists of words, numbers, or other lists, separated by white-
space and surrounded by parentheses. (Since a program looks like data, one
program may easily serve as data for another; this is a very powerful feature
of Lisp.) (Incidentally, these two parenthetical remarks are not Lisp lists,
because they contain ‘;’ and ‘.’ as punctuation marks.)
Here is another list, this time with a list inside of it:
" 5 0) (89.99627685546875 487.0576477050781 449.39642333984375 534.54736328125 "’(this list has (a list inside of it))
The components of this list are the words ‘this’, ‘list’, ‘has’, and the
list ‘(a list inside of it)’. The interior list is made up of the words ‘a’,
‘list’, ‘inside’, ‘of’, ‘it’.
" 6 0) (89.99640655517578 548.2818603515625 201.3193817138672 561.3858642578125 "1.1.1 Lisp Atoms
" 7 0) (89.99514770507812 569.609130859375 449.3634948730469 630.787353515625 "In Lisp, what we have been calling words are called atoms. This term
comes from the historical meaning of the word atom, which means ‘indivis-
ible’. As far as Lisp is concerned, the words we have been using in the lists
cannot be divided into any smaller parts and still mean the same thing as
part of a program; likewise with numbers and single character symbols like
" 8 0)) (20 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "2
Chapter 1: List Processing
" 0 0) (90.00003051757812 77.48908233642578 449.2689514160156 102.66727447509766 "‘+’. On the other hand, unlike an atom, a list can be split into parts. (See
Chapter 7, “car cdr & cons Fundamental Functions”, page 81.)
" 1 0) (89.99966430664062 117.68909454345703 449.32330322265625 142.86729431152344 "In a list, atoms are separated from each other by whitespace. They can
be right next to a parenthesis.
" 2 0) (89.9991455078125 157.88909912109375 449.6281433105469 230.9473114013672 "Technically speaking, a list in Lisp consists of parentheses surrounding
atoms separated by whitespace or surrounding other lists or surrounding
both atoms and other lists.
A list can have just one atom in it or have
nothing in it at all. A list with nothing in it looks like this: (), and is called
the empty list. Unlike anything else, an empty list is considered both an
atom and a list at the same time.
" 3 0) (89.99899291992188 245.84912109375 449.39892578125 318.9073181152344 "The printed representation of both atoms and lists are called symbolic
expressions or, more concisely, s-expressions. The word expression by itself
can refer to either the printed representation, or to the atom or list as it
is held internally in the computer. Often, people use the term expression
indiscriminately. (Also, in many texts, the word form is used as a synonym
for expression.)
" 4 0) (89.99847412109375 333.80914306640625 449.4320373535156 430.8673400878906 "Incidentally, the atoms that make up our universe were named such when
they were thought to be indivisible; but it has been found that physical atoms
are not indivisible. Parts can split off an atom or it can fission into two parts
of roughly equal size. Physical atoms were named prematurely, before their
truer nature was found. In Lisp, certain kinds of atom, such as an array, can
be separated into parts; but the mechanism for doing this is different from
the mechanism for splitting a list. As far as list operations are concerned,
the atoms of a list are unsplittable.
" 5 0) (89.99725341796875 445.7691650390625 449.41961669921875 494.9473571777344 "As in English, the meanings of the component letters of a Lisp atom are
different from the meaning the letters make as a word. For example, the
word for the South American sloth, the ‘ai’, is completely different from the
two words, ‘a’, and ‘i’.
" 6 0) (89.99642944335938 509.84918212890625 449.41912841796875 630.7874145507812 "There are many kinds of atom in nature but only a few in Lisp: for
example, numbers, such as 37, 511, or 1729, and symbols, such as ‘+’, ‘foo’,
or ‘forward-line’. The words we have listed in the examples above are
all symbols. In everyday Lisp conversation, the word “atom” is not often
used, because programmers usually try to be more specific about what kind
of atom they are dealing with. Lisp programming is mostly about symbols
(and sometimes numbers) within lists.
(Incidentally, the preceding three
word parenthetical remark is a proper list in Lisp, since it consists of atoms,
which in this case are symbols, separated by whitespace and enclosed by
parentheses, without any non-Lisp punctuation.)
" 7 0)) (21 (90.0 47.60907745361328 449.78131103515625 60.90726852416992 "GNU Emacs Helps You Type Lists
3
" 0 0) (89.99951171875 79.64905548095703 449.333984375 104.9472427368164 "In addition, text between double quotation marks—even sentences or
paragraphs—is an atom. Here is an example:
" 1 0) (89.998046875 110.13748168945312 449.41973876953125 181.5071258544922 "’(this list includes \"text between quotation marks.\")
In Lisp, all of the quoted text including the punctuation mark and the blank
spaces is a single atom. This kind of atom is called a string (for ‘string
of characters’) and is the sort of thing that is used for messages that a
computer can print for a human to read. Strings are a different kind of atom
than numbers or symbols and are used differently.
" 2 0) (89.99826049804688 195.24169921875 254.18441772460938 208.34568786621094 "1.1.2 Whitespace in Lists
" 3 0) (89.99853515625 216.68896484375 449.3758239746094 241.86717224121094 "The amount of whitespace in a list does not matter. From the point of
view of the Lisp language,
" 4 0) (89.9984359741211 247.05752563476562 218.55104064941406 284.2271423339844 "’(this list
looks like this)
is exactly the same as this:
" 5 0) (89.99649047851562 289.4173889160156 449.4737854003906 460.7470397949219 "’(this list looks like this)
Both examples show what to Lisp is the same list, the list made up of
the symbols ‘this’, ‘list’, ‘looks’, ‘like’, and ‘this’ in that order.
Extra whitespace and newlines are designed to make a list more readable
by humans. When Lisp reads the expression, it gets rid of all the extra
whitespace (but it needs to have at least one space between atoms in order
to tell them apart.)
Odd as it seems, the examples we have seen cover almost all of what
Lisp lists look like! Every other list in Lisp looks more or less like one of
these examples, except that the list may be longer and more complex. In
brief, a list is between parentheses, a string is between quotation marks, a
symbol looks like a word, and a number looks like a number. (For certain
situations, square brackets, dots and a few other special characters may be
used; however, we will go quite far without them.)
" 6 0) (89.99827575683594 474.4815979003906 352.74591064453125 487.5856018066406 "1.1.3 GNU Emacs Helps You Type Lists
" 7 0) (89.99734497070312 495.808837890625 449.5176086425781 550.8495483398438 "When you type a Lisp expression in GNU Emacs using either Lisp Interac-
tion mode or Emacs Lisp mode, you have available to you several commands
to format the Lisp expression so it is easy to read. For example, pressing
the ⟨
" 8 0) (112.66800689697266 535.072021484375 130.42800903320312 535.552001953125 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (112.68000030517578 536.2824096679688 130.4187774658203 544.2525634765625 "TAB
" 10 0) (112.66800689697266 543.5919799804688 130.42800903320312 544.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (90.00009155273438 531.3291015625 449.35589599609375 630.787353515625 "⟩ key automatically indents the line the cursor is on by the right
amount. A command to properly indent the code in a region is customarily
bound to M-C-\\. Indentation is designed so that you can see which elements
of a list belongs to which list—elements of a sub-list are indented more than
the elements of the enclosing list.
In addition, when you type a closing parenthesis, Emacs momentarily
jumps the cursor back to the matching opening parenthesis, so you can see
which one it is. This is very useful, since every list you type in Lisp must have
" 12 0)) (22 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "4
Chapter 1: List Processing
" 0 0) (90.00039672851562 77.48908233642578 449.3244323730469 114.66727447509766 "its closing parenthesis match its opening parenthesis. (See section “Major
Modes” in The GNU Emacs Manual, for more information about Emacs’
modes.)
" 1 0) (90.001220703125 131.30035400390625 228.78074645996094 145.660888671875 "1.2 Run a Program
" 2 0) (90.00100708007812 153.4490966796875 449.4663391113281 350.236083984375 "A list in Lisp—any list—is a program ready to run. If you run it (for
which the Lisp jargon is evaluate), the computer will do one of three things:
do nothing except return to you the list itself; send you an error message; or,
treat the first symbol in the list as a command to do something. (Usually,
of course, it is the last of these three things that you really want!)
The single apostrophe, ’, that I put in front of some of the example lists
in preceding sections is called a quote; when it precedes a list, it tells Lisp
to do nothing with the list, other than take it as it is written. But if there is
no quote preceding a list, the first item of the list is special: it is a command
for the computer to obey. (In Lisp, these commands are called functions.)
The list (+ 2 2) shown above did not have a quote in front of it, so Lisp
understands that the + is an instruction to do something with the rest of the
list: add the numbers that follow.
If you are reading this inside of GNU Emacs in Info, here is how you
can evaluate such a list: place your cursor immediately after the right hand
parenthesis of the following list and then type C-x C-e:
" 3 0) (90.00213623046875 355.297607421875 449.45660400390625 414.67608642578125 "(+ 2 2)
You will see the number 4 appear in the echo area. (In the jargon, what you
have just done is “evaluate the list.” The echo area is the line at the bottom
of the screen that displays or “echoes” text.) Now try the same thing with a
quoted list: place the cursor right after the following list and type C-x C-e:
" 4 0) (89.99981689453125 419.61761474609375 449.44403076171875 566.7073364257812 "’(this is a quoted list)
You will see (this is a quoted list) appear in the echo area.
In both cases, what you are doing is giving a command to the program
inside of GNU Emacs called the Lisp interpreter—giving the interpreter a
command to evaluate the expression. The name of the Lisp interpreter comes
from the word for the task done by a human who comes up with the meaning
of an expression—who “interprets” it.
You can also evaluate an atom that is not part of a list—one that is not
surrounded by parentheses; again, the Lisp interpreter translates from the
humanly readable expression to the language of the computer. But before
discussing this (see Section 1.7, “Variables”, page 10), we will discuss what
the Lisp interpreter does when you make an error.
" 5 0) (90.00013732910156 583.3403930664062 312.9887390136719 597.700927734375 "1.3 Generate an Error Message
" 6 0) (90.00048828125 605.4891357421875 449.4440612792969 630.787353515625 "Partly so you won’t worry if you do it accidentally, we will now give a
command to the Lisp interpreter that generates an error message. This is a
" 7 0)) (23 (90.0 47.60907745361328 449.8147888183594 60.90726852416992 "Generate an Error Message
5
" 0 0) (89.99969482421875 77.48908233642578 449.3667907714844 138.5472869873047 "harmless activity; and indeed, we will often try to generate error messages
intentionally. Once you understand the jargon, error messages can be in-
formative. Instead of being called “error” messages, they should be called
“help” messages. They are like signposts to a traveller in a strange country;
deciphering them can be hard, but once understood, they can point the way.
" 1 0) (89.99981689453125 141.80908203125 449.3234558105469 167.10728454589844 "The error message is generated by a built-in GNU Emacs debugger. We
will ‘enter the debugger’. You get out of the debugger by typing q.
" 2 0) (89.99853515625 170.24908447265625 449.3768005371094 219.43609619140625 "What we will do is evaluate a list that is not quoted and does not have
a meaningful command as its first element. Here is a list almost exactly the
same as the one we just used, but without the single-quote in front of it.
Position the cursor right after it and type C-x C-e:
" 3 0) (111.59806823730469 227.01760864257812 233.72633361816406 235.98399353027344 "(this is an unquoted list)
" 4 0) (89.9980697631836 239.72906494140625 449.3874206542969 288.9072570800781 "What you see depends on which version of Emacs you are running. GNU
Emacs version 21 provides more information than version 20 and before.
First, the more recent result of generating an error; then the earlier, version
20 result.
" 5 0) (89.998046875 292.1690673828125 449.3435974121094 317.4672546386719 "In GNU Emacs version 21, a ‘*Backtrace*’ window will open up and you
will see the following in it:
" 6 0) (111.59724426269531 325.0576171875 346.4422912597656 421.1441345214844 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function this)
(this is an unquoted list)
eval((this is an unquoted list))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 7 0) (89.99765014648438 426.689208984375 449.3754577636719 463.9873962402344 "Your cursor will be in this window (you may have to wait a few seconds
before it becomes visible). To quit the debugger and make the debugger
window go away, type:
" 8 0) (111.5979995727539 471.5777587890625 116.30535125732422 480.54412841796875 "q
" 9 0) (89.99800109863281 484.1692199707031 449.3653259277344 509.4762268066406 "Please type q right now, so you become confident that you can get out of
the debugger. Then, type C-x C-e again to re-enter it.
" 10 0) (104.99765014648438 512.729248046875 449.299072265625 526.0274658203125 "Based on what we already know, we can almost read this error message.
" 11 0) (89.99639892578125 529.169189453125 449.42919921875 590.347412109375 "You read the ‘*Backtrace*’ buffer from the bottom up; it tells you what
Emacs did. When you typed C-x C-e, you made an interactive call to the
command eval-last-sexp. eval is an abbreviation for ‘evaluate’ and sexp
is an abbreviation for ‘symbolic expression’. The command means ‘evaluate
last symbolic expression’, which is the expression just before your cursor.
" 12 0) (89.99649047851562 593.6092529296875 449.75628662109375 630.7874755859375 "Each line above tells you what the Lisp interpreter evaluated next. The
most recent action is at the top. The buffer is called the ‘*Backtrace*’
buffer because it enables you to track Emacs backwards.
" 13 0)) (24 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "6
Chapter 1: List Processing
" 0 0) (105.00039672851562 79.88904571533203 373.5820617675781 93.1872329711914 "At the top of the ‘*Backtrace*’ buffer, you see the line:
" 1 0) (89.99893188476562 98.61758422851562 449.7381286621094 363.90740966796875 "Debugger entered--Lisp error: (void-function this)
The Lisp interpreter tried to evaluate the first atom of the list, the word
‘this’. It is this action that generated the error message ‘void-function
this’.
The message contains the words ‘void-function’ and ‘this’.
The word ‘function’ was mentioned once before. It is a very important
word. For our purposes, we can define it by saying that a function is a set
of instructions to the computer that tell the computer to do something.
Now we can begin to understand the error message: ‘void-function
this’. The function (that is, the word ‘this’) does not have a definition of
any set of instructions for the computer to carry out.
The slightly odd word, ‘void-function’, is designed to cover the way
Emacs Lisp is implemented, which is that when a symbol does not have a
function definition attached to it, the place that should contain the instruc-
tions is ‘void’.
On the other hand, since we were able to add 2 plus 2 successfully, by
evaluating (+ 2 2), we can infer that the symbol + must have a set of in-
structions for the computer to obey and those instructions must be to add
the numbers that follow the +.
In GNU Emacs version 20, and in earlier versions, you will see only one
line of error message; it will appear in the echo area and look like this:
" 2 0) (89.99703979492188 369.2177734375 449.7022399902344 517.2674560546875 "Symbol’s function definition is void: this
(Also, your terminal may beep at you—some do, some don’t; and others
blink. This is just a device to get your attention.) The message goes away
as soon as you type another key, even just to move the cursor.
We know the meaning of the word ‘Symbol’. It refers to the first atom of
the list, the word ‘this’. The word ‘function’ refers to the instructions that
tell the computer what to do. (Technically, the symbol tells the computer
where to find the instructions, but this is a complication we can ignore for
the moment.)
The error message can be understood: ‘Symbol’s function definition
is void: this’. The symbol (that is, the word ‘this’) lacks instructions for
the computer to carry out.
" 3 0) (89.99691772460938 535.2205200195312 403.7975158691406 549.5810546875 "1.4 Symbol Names and Function Definitions
" 4 0) (89.996826171875 557.729248046875 449.39691162109375 630.7874755859375 "We can articulate another characteristic of Lisp based on what we have
discussed so far—an important characteristic: a symbol, like +, is not itself
the set of instructions for the computer to carry out. Instead, the symbol
is used, perhaps temporarily, as a way of locating the definition or set of
instructions. What we see is the name through which the instructions can
be found. Names of people work the same way.
I can be referred to as
" 5 0)) (25 (90.0 47.60907745361328 449.8582458496094 60.90726852416992 "The Lisp Interpreter
7
" 0 0) (89.99691772460938 77.48908233642578 449.4644775390625 305.9473571777344 "‘Bob’; however, I am not the letters ‘B’, ‘o’, ‘b’ but am the consciousness
consistently associated with a particular life-form. The name is not me, but
it can be used to refer to me.
In Lisp, one set of instructions can be attached to several names. For
example, the computer instructions for adding numbers can be linked to the
symbol plus as well as to the symbol + (and are in some dialects of Lisp).
Among humans, I can be referred to as ‘Robert’ as well as ‘Bob’ and by
other words as well.
On the other hand, a symbol can have only one function definition at-
tached to it at a time. Otherwise, the computer would be confused as to
which definition to use. If this were the case among people, only one person
in the world could be named ‘Bob’. However, the function definition to which
the name refers can be changed readily. (See Section 3.2, “Install a Function
Definition”, page 31.)
Since Emacs Lisp is large, it is customary to name symbols in a way that
identifies the part of Emacs to which the function belongs. Thus, all the
names for functions that deal with Texinfo start with ‘texinfo-’ and those
for functions that deal with reading mail start with ‘rmail-’.
" 1 0) (89.99710083007812 330.38043212890625 264.1138916015625 344.740966796875 "1.5 The Lisp Interpreter
" 2 0) (89.99496459960938 354.44915771484375 449.4619140625 630.787353515625 "Based on what we have seen, we can now start to figure out what the Lisp
interpreter does when we command it to evaluate a list. First, it looks to see
whether there is a quote before the list; if there is, the interpreter just gives
us the list. On the other hand, if there is no quote, the interpreter looks at
the first element in the list and sees whether it has a function definition. If
it does, the interpreter carries out the instructions in the function definition.
Otherwise, the interpreter prints an error message.
This is how Lisp works. Simple. There are added complications which
we will get to in a minute, but these are the fundamentals. Of course, to
write Lisp programs, you need to know how to write function definitions and
attach them to names, and how to do this without confusing either yourself
or the computer.
Now, for the first complication. In addition to lists, the Lisp interpreter
can evaluate a symbol that is not quoted and does not have parentheses
around it.
The Lisp interpreter will attempt to determine the symbol’s
value as a variable. This situation is described in the section on variables.
(See Section 1.7, “Variables”, page 10.)
The second complication occurs because some functions are unusual and
do not work in the usual manner. Those that don’t are called special forms.
They are used for special jobs, like defining a function, and there are not
many of them. In the next few chapters, you will be introduced to several
of the more important special forms.
" 3 0)) (26 (90.0 47.60907745361328 449.8034973144531 60.90726852416992 "8
Chapter 1: List Processing
" 0 0) (89.99853515625 77.48908233642578 449.49615478515625 213.4272918701172 "The third and final complication is this: if the function that the Lisp
interpreter is looking at is not a special form, and if it is part of a list, the
Lisp interpreter looks to see whether the list has a list inside of it. If there
is an inner list, the Lisp interpreter first figures out what it should do with
the inside list, and then it works on the outside list. If there is yet another
list embedded inside the inner list, it works on that one first, and so on.
It always works on the innermost list first. The interpreter works on the
innermost list first, to evaluate the result of that list. The result may be
used by the enclosing expression.
Otherwise, the interpreter works left to right, from one expression to the
next.
" 1 0) (89.99853515625 229.9217529296875 229.24867248535156 243.02574157714844 "1.5.1 Byte Compiling
" 2 0) (89.99526977539062 252.208984375 449.4936218261719 427.0271911621094 "One other aspect of interpreting: the Lisp interpreter is able to interpret
two kinds of entity: humanly readable code, on which we will focus exclu-
sively, and specially processed code, called byte compiled code, which is not
humanly readable. Byte compiled code runs faster than humanly readable
code.
You can transform humanly readable code into byte compiled code by
running one of the compile commands such as byte-compile-file. Byte
compiled code is usually stored in a file that ends with a ‘.elc’ exten-
sion rather than a ‘.el’ extension. You will see both kinds of file in the
‘emacs/lisp’ directory; the files to read are those with ‘.el’ extensions.
As a practical matter, for most things you might do to customize or
extend Emacs, you do not need to byte compile; and I will not discuss
the topic here. See section “Byte Compilation” in The GNU Emacs Lisp
Reference Manual, for a full description of byte compilation.
" 3 0) (89.99472045898438 447.74029541015625 193.54904174804688 462.100830078125 "1.6 Evaluation
" 4 0) (89.99298095703125 470.9690246582031 449.40380859375 630.7872314453125 "When the Lisp interpreter works on an expression, the term for the ac-
tivity is called evaluation. We say that the interpreter ‘evaluates the expres-
sion’. I’ve used this term several times before. The word comes from its
use in everyday language, ‘to ascertain the value or amount of; to appraise’,
according to Webster’s New Collegiate Dictionary.
After evaluating an expression, the Lisp interpreter will most likely return
the value that the computer produces by carrying out the instructions it
found in the function definition, or perhaps it will give up on that function
and produce an error message. (The interpreter may also find itself tossed,
so to speak, to a different function or it may attempt to repeat continually
what it is doing for ever and ever in what is called an ‘infinite loop’. These
actions are less common; and we can ignore them.) Most frequently, the
interpreter returns a value.
" 5 0)) (27 (90.0 47.60907745361328 449.83587646484375 60.90726852416992 "Evaluating Inner Lists
9
" 0 0) (89.99923706054688 77.48908233642578 449.3990783691406 188.58726501464844 "At the same time the interpreter returns a value, it may do something
else as well, such as move a cursor or copy a file; this other kind of action
is called a side effect. Actions that we humans think are important, such as
printing results, are often “side effects” to the Lisp interpreter. The jargon
can sound peculiar, but it turns out that it is fairly easy to learn to use side
effects.
In summary, evaluating a symbolic expression most commonly causes the
Lisp interpreter to return a value and perhaps carry out a side effect; or else
produce an error.
" 1 0) (89.99913024902344 202.56182861328125 270.7168884277344 215.6658172607422 "1.6.1 Evaluating Inner Lists
" 2 0) (89.99765014648438 223.88909912109375 449.3211669921875 299.2362060546875 "If evaluation applies to a list that is inside another list, the outer list may
use the value returned by the first evaluation as information when the outer
list is evaluated. This explains why inner expressions are evaluated first: the
values they return are used by the outer expressions.
We can investigate this process by evaluating another addition example.
Place your cursor after the following expression and type C-x C-e:
" 3 0) (89.99594116210938 304.4176330566406 449.461181640625 492.1872863769531 "(+ 2 (+ 3 3))
The number 8 will appear in the echo area.
What happens is that the Lisp interpreter first evaluates the inner ex-
pression, (+ 3 3), for which the value 6 is returned; then it evaluates the
outer expression as if it were written (+ 2 6), which returns the value 8.
Since there are no more enclosing expressions to evaluate, the interpreter
prints that value in the echo area.
Now it is easy to understand the name of the command invoked by the
keystrokes C-x C-e: the name is eval-last-sexp.
The letters sexp are
an abbreviation for ‘symbolic expression’, and eval is an abbreviation for
‘evaluate’. The command means ‘evaluate last symbolic expression’.
As an experiment, you can try evaluating the expression by putting the
cursor at the beginning of the next line immediately following the expression,
or inside the expression.
Here is another copy of the expression:
" 4 0) (89.99530029296875 497.3776550292969 449.4059143066406 630.787353515625 "(+ 2 (+ 3 3))
If you place the cursor at the beginning of the blank line that immediately
follows the expression and type C-x C-e, you will still get the value 8 printed
in the echo area. Now try putting the cursor inside the expression. If you
put it right after the next to last parenthesis (so it appears to sit on top
of the last parenthesis), you will get a 6 printed in the echo area! This is
because the command evaluates the expression (+ 3 3).
Now put the cursor immediately after a number. Type C-x C-e and you
will get the number itself. In Lisp, if you evaluate a number, you get the
number itself—this is how numbers differ from symbols. If you evaluate a
list starting with a symbol like +, you will get a value returned that is the
" 5 0)) (28 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "10
Chapter 1: List Processing
" 0 0) (89.999267578125 77.48908233642578 449.2245178222656 114.66727447509766 "result of the computer carrying out the instructions in the function definition
attached to that name. If a symbol by itself is evaluated, something different
happens, as we will see in the next section.
" 1 0) (89.9996337890625 137.54034423828125 183.30419921875 151.90087890625 "1.7 Variables
" 2 0) (89.9949951171875 161.24908447265625 449.5032958984375 436.5160827636719 "In Emacs Lisp, a symbol can have a value attached to it just as it can
have a function definition attached to it. The two are different. The function
definition is a set of instructions that a computer will obey. A value, on the
other hand, is something, such as number or a name, that can vary (which
is why such a symbol is called a variable). The value of a symbol can be any
expression in Lisp, such as a symbol, number, list, or string. A symbol that
has a value is often called a variable.
A symbol can have both a function definition and a value attached to it
at the same time. Or it can have just one or the other. The two are separate.
This is somewhat similar to the way the name Cambridge can refer to the
city in Massachusetts and have some information attached to the name as
well, such as “great programming center”.
Another way to think about this is to imagine a symbol as being a chest of
drawers. The function definition is put in one drawer, the value in another,
and so on. What is put in the drawer holding the value can be changed
without affecting the contents of the drawer holding the function definition,
and vice-versa.
The variable fill-column illustrates a symbol with a value attached to
it: in every GNU Emacs buffer, this symbol is set to some value, usually 72
or 70, but sometimes to some other value. To find the value of this symbol,
evaluate it by itself. If you are reading this in Info inside of GNU Emacs,
you can do this by putting the cursor after the symbol and typing C-x C-e:
" 3 0) (89.9940185546875 443.1376037597656 449.47039794921875 630.787353515625 "fill-column
After I typed C-x C-e, Emacs printed the number 72 in my echo area. This
is the value for which fill-column is set for me as I write this. It may
be different for you in your Info buffer. Notice that the value returned as
a variable is printed in exactly the same way as the value returned by a
function carrying out its instructions. From the point of view of the Lisp
interpreter, a value returned is a value returned. What kind of expression it
came from ceases to matter once the value is known.
A symbol can have any value attached to it or, to use the jargon, we can
bind the variable to a value: to a number, such as 72; to a string, \"such as
this\"; to a list, such as (spruce pine oak); we can even bind a variable to
a function definition.
A symbol can be bound to a value in several ways.
See Section 1.9,
“Setting the Value of a Variable”, page 17, for information about one way
to do this.
" 4 0)) (29 (90.0 47.60907745361328 449.5411682128906 60.90726852416992 "Error Message for a Symbol Without a Value
11
" 0 0) (89.99951171875 78.2418212890625 441.228759765625 91.34580993652344 "1.7.1 Error Message for a Symbol Without a Function
" 1 0) (89.99884033203125 99.68909454345703 449.4649353027344 175.02732849121094 "When we evaluated fill-column to find its value as a variable, we did
not place parentheses around the word. This is because we did not intend
to use it as a function name.
If fill-column were the first or only element of a list, the Lisp interpreter
would attempt to find the function definition attached to it.
But fill-
column has no function definition. Try evaluating this:
" 2 0) (89.99842071533203 180.33767700195312 449.25616455078125 204.06736755371094 "(fill-column)
In GNU Emacs version 21, you will create a ‘*Backtrace*’ buffer that says:
" 3 0) (89.99859619140625 209.37771606445312 449.3437194824219 359.34735107421875 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-function fill-column)
(fill-column)
eval((fill-column))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(Remember, to quit the debugger and make the debugger window go away,
type q in the ‘*Backtrace*’ buffer.)
In GNU Emacs 20 and before, you will produce an error message that
says:
" 4 0) (89.99845886230469 364.65771484375 449.4523620605469 400.2673645019531 "Symbol’s function definition is void: fill-column
(The message will go away away as soon as you move the cursor or type
another key.)
" 5 0) (89.99870300292969 414.6019287109375 421.0548095703125 427.7059326171875 "1.7.2 Error Message for a Symbol Without a Value
" 6 0) (89.99868774414062 436.0491943359375 449.5945739746094 485.2362060546875 "If you attempt to evaluate a symbol that does not have a value bound
to it, you will receive an error message. You can see this by experimenting
with our 2 plus 2 addition. In the following expression, put your cursor right
after the +, before the first number 2, type C-x C-e:
" 7 0) (89.99947357177734 490.4177551269531 416.4536437988281 514.2673950195312 "(+ 2 2)
In GNU Emacs 21, you will create a ‘*Backtrace*’ buffer that says:
" 8 0) (89.99969482421875 519.5778198242188 449.3229675292969 630.7874755859375 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error: (void-variable +)
eval(+)
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
(As with the other times we entered the debugger, you can quit by typing q
in the ‘*Backtrace*’ buffer.)
" 9 0)) (30 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "12
Chapter 1: List Processing
" 0 0) (89.99711608886719 77.48908233642578 449.40985107421875 275.7072448730469 "This backtrace is different from the very first error message we saw,
which said, ‘Debugger entered--Lisp error: (void-function this)’. In
this case, the function does not have a value as a variable; while in the other
error message, the function (the word ‘this’) did not have a definition.
In this experiment with the +, what we did was cause the Lisp interpreter
to evaluate the + and look for the value of the variable instead of the function
definition. We did this by placing the cursor right after the symbol rather
than after the parenthesis of the enclosing list as we did before. As a conse-
quence, the Lisp interpreter evaluated the preceding s-expression, which in
this case was the + by itself.
Since + does not have a value bound to it, just the function definition,
the error message reported that the symbol’s value as a variable was void.
In GNU Emacs version 20 and before, your error message will say:
Symbol’s value as variable is void: +
The meaning is the same as in GNU Emacs 21.
" 1 0) (89.99661254882812 297.7403564453125 196.37869262695312 312.10089111328125 "1.8 Arguments
" 2 0) (89.9964599609375 321.2090759277344 449.287109375 346.50726318359375 "To see how information is passed to functions, let’s look again at our old
standby, the addition of two plus two. In Lisp, this is written as follows:
" 3 0) (89.99591064453125 352.8976135253906 449.4605712890625 503.9472351074219 "(+ 2 2)
If you evaluate this expression, the number 4 will appear in your echo
area. What the Lisp interpreter does is add the numbers that follow the +.
The numbers added by + are called the arguments of the function +.
These numbers are the information that is given to or passed to the function.
The word ‘argument’ comes from the way it is used in mathematics and
does not refer to a disputation between two people; instead it refers to the
information presented to the function, in this case, to the +. In Lisp, the
arguments to a function are the atoms or lists that follow the function. The
values returned by the evaluation of these atoms or lists are passed to the
function. Different functions require different numbers of arguments; some
functions require none at all.1
" 4 0) (89.98799896240234 517.9119873046875 233.98800659179688 518.3919677734375 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (95.87999725341797 518.8551635742188 449.8175354003906 630.3016357421875 "1 It is curious to track the path by which the word ‘argument’ came to have two differ-
ent meanings, one in mathematics and the other in everyday English. According to
the Oxford English Dictionary, the word derives from the Latin for ‘to make clear,
prove’; thus it came to mean, by one thread of derivation, ‘the evidence offered as
proof’, which is to say, ‘the information offered’, which led to its meaning in Lisp.
But in the other thread of derivation, it came to mean ‘to assert in a manner against
which others may make counter assertions’, which led to the meaning of the word as a
disputation. (Note here that the English word has two different definitions attached to
it at the same time. By contrast, in Emacs Lisp, a symbol cannot have two different
function definitions at the same time.)
" 6 0)) (31 (90.0 47.60907745361328 449.5195007324219 60.90726852416992 "An Argument as the Value of a Variable or List
13
" 0 0) (89.99984741210938 78.2418212890625 282.3642272949219 91.34580993652344 "1.8.1 Arguments’ Data Types
" 1 0) (89.99920654296875 99.56909942626953 449.4541320800781 198.6672821044922 "The type of data that should be passed to a function depends on what
kind of information it uses. The arguments to a function such as + must
have values that are numbers, since + adds numbers. Other functions use
different kinds of data for their arguments.
For example, the concat function links together or unites two or more
strings of text to produce a string. The arguments are strings. Concate-
nating the two character strings abc, def produces the single string abcdef.
This can be seen by evaluating the following:
" 2 0) (89.99880981445312 203.73764038085938 449.5189208984375 327.3072204589844 "(concat \"abc\" \"def\")
The value produced by evaluating this expression is \"abcdef\".
A function such as substring uses both a string and numbers as argu-
ments. The function returns a part of the string, a substring of the first
argument. This function takes three arguments. Its first argument is the
string of characters, the second and third arguments are numbers that in-
dicate the beginning and end of the substring. The numbers are a count
of the number of characters (including spaces and punctuations) from the
beginning of the string.
For example, if you evaluate the following:
" 3 0) (89.99746704101562 332.3775634765625 449.5065002441406 453.7873229980469 "(substring \"The quick brown fox jumped.\" 16 19)
you will see \"fox\" appear in the echo area. The arguments are the string
and the two numbers.
Note that the string passed to substring is a single atom even though
it is made up of several words separated by spaces. Lisp counts everything
between the two quotation marks as part of the string, including the spaces.
You can think of the substring function as a kind of ‘atom smasher’ since it
takes an otherwise indivisible atom and extracts a part. However, substring
is only able to extract a substring from an argument that is a string, not
from another type of atom such as a number or symbol.
" 4 0) (89.99795532226562 467.5218811035156 435.76593017578125 480.6258850097656 "1.8.2 An Argument as the Value of a Variable or List
" 5 0) (89.99832153320312 488.84912109375 449.4090576171875 540.1961669921875 "An argument can be a symbol that returns a value when it is evaluated.
For example, when the symbol fill-column by itself is evaluated, it returns
a number. This number can be used in an addition.
Position the cursor after the following expression and type C-x C-e:
" 6 0) (89.9979248046875 545.3777465820312 449.3211669921875 630.787353515625 "(+ 2 fill-column)
The value will be a number two more than what you get by evaluating
fill-column alone. For me, this is 74, because the value of fill-column is
72.
As we have just seen, an argument can be a symbol that returns a value
when evaluated. In addition, an argument can be a list that returns a value
when it is evaluated. For example, in the following expression, the arguments
" 7 0)) (32 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "14
Chapter 1: List Processing
" 0 0) (89.99893188476562 77.48908233642578 449.4317321777344 102.66727447509766 "to the function concat are the strings \"The \" and \" red foxes.\" and the
list (number-to-string (+ 2 fill-column)).
" 1 0) (89.9990234375 108.93759155273438 449.813720703125 193.3872528076172 "(concat \"The \" (number-to-string (+ 2 fill-column)) \" red foxes.\")
If you evaluate this expression—and if, as with my Emacs, fill-column
evaluates to 72—\"The 74 red foxes.\" will appear in the echo area. (Note
that you must put spaces after the word ‘The’ and before the word ‘red’
so they will appear in the final string.
The function number-to-string
converts the integer that the addition function returns to a string. number-
to-string is also known as int-to-string.)
" 2 0) (89.99903869628906 210.601806640625 331.18389892578125 223.70579528808594 "1.8.3 Variable Number of Arguments
" 3 0) (89.99853515625 233.009033203125 449.4313049316406 309.4272155761719 "Some functions, such as concat, + or *, take any number of arguments.
(The * is the symbol for multiplication.) This can be seen by evaluating
each of the following expressions in the usual way. What you will see in the
echo area is printed in this text after ‘⇒’, which you may read as ‘evaluates
to’.
In the first set, the functions have no arguments:
" 4 0) (111.59883117675781 314.8530578613281 177.5061798095703 330.40972900390625 "(+)
⇒ 0
" 5 0) (111.59883117675781 339.8130187988281 177.5061798095703 355.36968994140625 "(*)
⇒ 1
" 6 0) (104.99882507324219 353.2489929199219 343.0240783691406 366.54718017578125 "In this set, the functions have one argument each:
" 7 0) (111.59925842285156 371.9730224609375 177.50660705566406 387.5296936035156 "(+ 3)
⇒ 3
" 8 0) (111.59925842285156 396.8130187988281 177.50660705566406 412.36968994140625 "(* 3)
⇒ 3
" 9 0) (104.99925231933594 410.3689880371094 355.2318115234375 423.66717529296875 "In this set, the functions have three arguments each:
" 10 0) (111.5989990234375 429.093017578125 182.17779541015625 445.24969482421875 "(+ 3 4 5) ⇒ 12
" 11 0) (111.59896850585938 453.9330139160156 182.17776489257812 470.0896911621094 "(* 3 4 5) ⇒ 60
" 12 0) (89.99893188476562 480.4817199707031 431.9792785644531 493.5857238769531 "1.8.4 Using the Wrong Type Object as an Argument
" 13 0) (89.99838256835938 502.88897705078125 449.4961242675781 563.9559936523438 "When a function is passed an argument of the wrong type, the Lisp
interpreter produces an error message. For example, the + function expects
the values of its arguments to be numbers. As an experiment we can pass it
the quoted symbol hello instead of a number. Position the cursor after the
following expression and type C-x C-e:
" 14 0) (89.99658203125 570.2175903320312 449.3319091796875 630.7872314453125 "(+ 2 ’hello)
When you do this you will generate an error message. What has happened is
that + has tried to add the 2 to the value returned by ’hello, but the value
returned by ’hello is the symbol hello, not a number. Only numbers can
be added. So + could not carry out its addition.
" 15 0)) (33 (90.0 47.60907745361328 449.54150390625 60.90726852416992 "Using the Wrong Type Object as an Argument
15
" 0 0) (89.99951171875 85.52906036376953 449.80322265625 110.8272476196289 "In GNU Emacs version 21, you will create and enter a ‘*Backtrace*’
buffer that says:
" 1 0) (111.59939575195312 121.77761840820312 369.980712890625 230.46385192871094 "---------- Buffer: *Backtrace* ----------
Debugger entered--Lisp error:
(wrong-type-argument number-or-marker-p hello)
+(2 hello)
eval((+ 2 (quote hello)))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
---------- Buffer: *Backtrace* ----------
" 2 0) (90.00003051757812 238.7689208984375 449.30157470703125 264.0671081542969 "As usual, the error message tries to be helpful and makes sense after you
learn how to read it.
" 3 0) (89.99972534179688 270.68890380859375 449.4212341308594 307.8670959472656 "The first part of the error message is straightforward; it says ‘wrong type
argument’. Next comes the mysterious jargon word ‘number-or-marker-p’.
This word is trying to tell you what kind of argument the + expected.
" 4 0) (89.99972534179688 314.60888671875 449.43310546875 405.0495910644531 "The symbol number-or-marker-p says that the Lisp interpreter is try-
ing to determine whether the information presented it (the value of the
argument) is a number or a marker (a special object representing a buffer
position). What it does is test to see whether the + is being given numbers to
add. It also tests to see whether the argument is something called a marker,
which is a specific feature of Emacs Lisp. (In Emacs, locations in a buffer
are recorded as markers.
When the mark is set with the C-@ or C-⟨
" 5 0) (430.3080139160156 389.6319885253906 446.9880065917969 390.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (430.32000732421875 390.8424377441406 446.865966796875 398.8125305175781 "SPC
" 7 0) (430.3080139160156 398.2720031738281 446.9880065917969 398.75201416015625 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.99850463867188 389.49310302734375 449.9865417480469 447.42724609375 "⟩
command, its position is kept as a marker. The mark can be considered a
number—the number of characters the location is from the beginning of the
buffer.) In Emacs Lisp, + can be used to add the numeric value of marker
positions as numbers.
" 9 0) (89.99911499023438 454.049072265625 449.3556213378906 562.9873046875 "The ‘p’ of number-or-marker-p is the embodiment of a practice started
in the early days of Lisp programming. The ‘p’ stands for ‘predicate’. In the
jargon used by the early Lisp researchers, a predicate refers to a function
to determine whether some property is true or false. So the ‘p’ tells us that
number-or-marker-p is the name of a function that determines whether it
is true or false that the argument supplied is a number or a marker. Other
Lisp symbols that end in ‘p’ include zerop, a function that tests whether its
argument has the value of zero, and listp, a function that tests whether its
argument is a list.
" 10 0) (89.99859619140625 569.609130859375 449.3768005371094 630.787353515625 "Finally, the last part of the error message is the symbol hello. This is the
value of the argument that was passed to +. If the addition had been passed
the correct type of object, the value passed would have been a number, such
as 37, rather than a symbol like hello. But then you would not have got
the error message.
" 11 0)) (34 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "16
Chapter 1: List Processing
" 0 0) (89.99951171875 79.52906036376953 449.3662414550781 104.8272476196289 "In GNU Emacs version 20 and before, the echo area displays an error
message that says:
" 1 0) (89.99954223632812 109.77761840820312 449.72625732421875 145.1472625732422 "Wrong type argument: number-or-marker-p, hello
This says, in different words, the same as the top line of the ‘*Backtrace*’
buffer.
" 2 0) (89.99954223632812 157.92181396484375 265.9501037597656 171.03736877441406 "1.8.5 The message Function
" 3 0) (89.99853515625 179.00909423828125 449.47509765625 242.22727966308594 "Like +, the message function takes a variable number of arguments. It is
used to send messages to the user and is so useful that we will describe it
here.
A message is printed in the echo area.
For example, you can print a
message in your echo area by evaluating the following list:
" 4 0) (89.99856567382812 247.29763793945312 449.5411376953125 418.2760009765625 "(message \"This message appears in the echo area!\")
The whole string between double quotation marks is a single argument
and is printed in toto. (Note that in this example, the message itself will ap-
pear in the echo area within double quotes; that is because you see the value
returned by the message function. In most uses of message in programs that
you write, the text will be printed in the echo area as a side-effect, without
the quotes. See Section 3.3.1, “multiply-by-seven in detail”, page 34, for
an example of this.)
However, if there is a ‘%s’ in the quoted string of characters, the message
function does not print the ‘%s’ as such, but looks to the argument that
follows the string. It evaluates the second argument and prints the value at
the location in the string where the ‘%s’ is.
You can see this by positioning the cursor after the following expression
and typing C-x C-e:
" 5 0) (89.9979248046875 423.217529296875 449.4093017578125 508.38720703125 "(message \"The name of this buffer is: %s.\" (buffer-name))
In Info, \"The name of this buffer is: *info*.\" will appear in the echo
area. The function buffer-name returns the name of the buffer as a string,
which the message function inserts in place of %s.
To print a value as an integer, use ‘%d’ in the same way as ‘%s’. For
example, to print a message in the echo area that states the value of the
fill-column, evaluate the following:
" 6 0) (89.9979248046875 513.3375854492188 449.5290832519531 598.5072631835938 "(message \"The value of fill-column is %d.\" fill-column)
On my system, when I evaluate this list, \"The value of fill-column is
72.\" appears in my echo area2.
If there is more than one ‘%s’ in the quoted string, the value of the first
argument following the quoted string is printed at the location of the first
‘%s’ and the value of the second argument is printed at the location of the
second ‘%s’, and so on.
" 7 0) (89.98799896240234 605.5120239257812 233.98800659179688 605.9920043945312 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (95.87999725341797 606.5751953125 449.7224426269531 630.3015747070312 "2 Actually, you can use %s to print a number. It is non-specific. %d prints only the part
of a number left of a decimal point, and not anything that is not a number.
" 9 0)) (35 (90.0 47.60907745361328 449.8360595703125 60.90726852416992 "Using set
17
" 0 0) (104.9993896484375 80.60907745361328 307.3194274902344 93.90726470947266 "For example, if you evaluate the following,
" 1 0) (89.99725341796875 100.05758666992188 449.41925048828125 250.9872283935547 "(message \"There are %d %s in the office!\"
(- fill-column 14) \"pink elephants\")
a rather whimsical message will appear in your echo area. On my system it
says, \"There are 58 pink elephants in the office!\".
The expression (- fill-column 14) is evaluated and the resulting num-
ber is inserted in place of the ‘%d’; and the string in double quotes, \"pink
elephants\", is treated as a single argument and inserted in place of the
‘%s’. (That is to say, a string between double quotes evaluates to itself, like
a number.)
Finally, here is a somewhat complex example that not only illustrates
the computation of a number, but also shows how you can use an expression
within an expression to generate the text that is substituted for ‘%s’:
" 2 0) (89.99569702148438 257.1375427246094 449.5152893066406 418.9872131347656 "(message \"He saw %d %s\"
(- fill-column 34)
(concat \"red \"
(substring
\"The quick brown foxes jumped.\" 16 21)
\" leaping.\"))
In this example, message has three arguments: the string, \"He saw %d
%s\", the expression, (- fill-column 32), and the expression beginning with
the function concat. The value resulting from the evaluation of (- fill-
column 32) is inserted in place of the ‘%d’; and the value returned by the
expression beginning with concat is inserted in place of the ‘%s’.
When I evaluate the expression, the message \"He saw 38 red foxes
leaping.\" appears in my echo area.
" 3 0) (89.99574279785156 439.7003173828125 337.15985107421875 454.06085205078125 "1.9 Setting the Value of a Variable
" 4 0) (89.99496459960938 462.9290466308594 449.36309814453125 539.1072998046875 "There are several ways by which a variable can be given a value. One of
the ways is to use either the function set or the function setq. Another way
is to use let (see Section 3.6, “let”, page 36). (The jargon for this process
is to bind a variable to a value.)
The following sections not only describe how set and setq work but also
illustrate how arguments are passed.
" 5 0) (89.99526977539062 555.7218017578125 189.42724609375 568.8373413085938 "1.9.1 Using set
" 6 0) (89.99478149414062 578.009033203125 449.4709777832031 615.196044921875 "To set the value of the symbol flowers to the list ’(rose violet daisy
buttercup), evaluate the following expression by positioning the cursor after
the expression and typing C-x C-e.
" 7 0) (111.59518432617188 621.337646484375 322.8502197265625 630.3040161132812 "(set ’flowers ’(rose violet daisy buttercup))
" 8 0)) (36 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "18
Chapter 1: List Processing
" 0 0) (89.99588012695312 77.48908233642578 449.5401611328125 214.6361083984375 "The list (rose violet daisy buttercup) will appear in the echo area. This
is what is returned by the set function. As a side effect, the symbol flowers
is bound to the list ; that is, the symbol flowers, which can be viewed as a
variable, is given the list as its value. (This process, by the way, illustrates
how a side effect to the Lisp interpreter, setting the value, can be the primary
effect that we humans are interested in. This is because every Lisp function
must return a value if it does not get an error, but it will only have a side
effect if it is designed to have one.)
After evaluating the set expression, you can evaluate the symbol flowers
and it will return the value you just set. Here is the symbol. Place your
cursor after it and type C-x C-e.
" 1 0) (89.99557495117188 221.97763061523438 449.3955078125 299.8273010253906 "flowers
When you evaluate flowers, the list (rose violet daisy buttercup) ap-
pears in the echo area.
Incidentally, if you evaluate ’flowers, the variable with a quote in front
of it, what you will see in the echo area is the symbol itself, flowers. Here
is the quoted symbol, so you can try this:
" 2 0) (89.99444580078125 307.1776428222656 449.5155334472656 440.5873107910156 "’flowers
Note also, that when you use set, you need to quote both arguments to
set, unless you want them evaluated. Since we do not want either argument
evaluated, neither the variable flowers nor the list (rose violet daisy
buttercup), both are quoted. (When you use set without quoting its first
argument, the first argument is evaluated before anything else is done. If
you did this and flowers did not have a value already, you would get an
error message that the ‘Symbol’s value as variable is void’; on the other
hand, if flowers did return a value after it was evaluated, the set would
attempt to set the value that was returned. There are situations where this
is the right thing for the function to do; but such situations are rare.)
" 3 0) (89.99407958984375 460.921875 196.14169311523438 474.0374450683594 "1.9.2 Using setq
" 4 0) (89.99331665039062 484.40911865234375 449.50286865234375 585.787353515625 "As a practical matter, you almost always quote the first argument to set.
The combination of set and a quoted first argument is so common that it
has its own name: the special form setq. This special form is just like set
except that the first argument is quoted automatically, so you don’t need to
type the quote mark yourself. Also, as an added convenience, setq permits
you to set several different variables to different values, all in one expression.
To set the value of the variable carnivores to the list ’(lion tiger
leopard) using setq, the following expression is used:
" 5 0) (89.99374389648438 593.0177001953125 449.1311950683594 630.787353515625 "(setq carnivores ’(lion tiger leopard))
This is exactly the same as using set except the first argument is automat-
ically quoted by setq. (The ‘q’ in setq means quote.)
" 6 0)) (37 (90.0 47.60907745361328 449.8360595703125 60.90726852416992 "Counting
19
" 0 0) (104.9993896484375 79.52906036376953 324.09747314453125 92.8272476196289 "With set, the expression would look like this:
" 1 0) (89.99957275390625 97.89761352539062 449.4219665527344 169.1472625732422 "(set ’carnivores ’(lion tiger leopard))
Also, setq can be used to assign different values to different variables.
The first argument is bound to the value of the second argument, the third
argument is bound to the value of the fourth argument, and so on.
For
example, you could use the following to assign a list of trees to the symbol
trees and a list of herbivores to the symbol herbivores:
" 2 0) (89.99673461914062 174.09762573242188 449.462646484375 308.4672546386719 "(setq trees ’(pine fir oak maple)
herbivores ’(gazelle antelope zebra))
(The expression could just as well have been on one line, but it might not
have fit on a page; and humans find it easier to read nicely formatted lists.)
Although I have been using the term ‘assign’, there is another way of
thinking about the workings of set and setq; and that is to say that set
and setq make the symbol point to the list. This latter way of thinking is
very common and in forthcoming chapters we shall come upon at least one
symbol that has ‘pointer’ as part of its name. The name is chosen because the
symbol has a value, specifically a list, attached to it; or, expressed another
way, the symbol is set to “point” to the list.
" 3 0) (89.99659729003906 321.9618225097656 186.9347686767578 335.0658264160156 "1.9.3 Counting
" 4 0) (89.99603271484375 343.049072265625 449.38531494140625 428.1072692871094 "Here is an example that shows how to use setq in a counter. You might
use this to count how many times a part of your program repeats itself. First
set a variable to zero; then add one to the number each time the program
repeats itself. To do this, you need a variable that serves as a counter, and
two expressions: an initial setq expression that sets the counter variable to
zero; and a second setq expression that increments the counter each time it
is evaluated.
" 5 0) (111.59613800048828 433.1752014160156 385.1600646972656 442.14398193359375 "(setq counter 0)
; Let’s call this the initializer.
" 6 0) (111.59576416015625 458.01519775390625 367.5655212402344 466.9839782714844 "(setq counter (+ counter 1))
; This is the incrementer.
" 7 0) (89.99337768554688 482.9751892089844 449.4482727050781 630.7872924804688 "counter
; This is the counter.
(The text following the ‘;’ are comments.
See Section 3.2.1, “Change a
Function Definition”, page 32.)
If you evaluate the first of these expressions, the initializer, (setq
counter 0), and then evaluate the third expression, counter, the number 0
will appear in the echo area. If you then evaluate the second expression, the
incrementer, (setq counter (+ counter 1)), the counter will get the value
1. So if you again evaluate counter, the number 1 will appear in the echo
area. Each time you evaluate the second expression, the value of the counter
will be incremented.
When you evaluate the incrementer, (setq counter (+ counter 1)), the
Lisp interpreter first evaluates the innermost list; this is the addition. In
" 8 0)) (38 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "20
Chapter 1: List Processing
" 0 0) (89.99929809570312 77.48908233642578 449.4102478027344 150.5472869873047 "order to evaluate this list, it must evaluate the variable counter and the
number 1. When it evaluates the variable counter, it receives its current
value.
It passes this value and the number 1 to the + which adds them
together. The sum is then returned as the value of the inner list and passed
to the setq which sets the variable counter to this new value. Thus, the
value of the variable, counter, is changed.
" 1 0) (89.99888610839844 168.2603759765625 194.45069885253906 182.62091064453125 "1.10 Summary
" 2 0) (89.99853515625 190.64910888671875 449.4289855957031 550.1472778320312 "Learning Lisp is like climbing a hill in which the first part is the steepest.
You have now climbed the most difficult part; what remains becomes easier
as you progress onwards.
In summary,
• Lisp programs are made up of expressions, which are lists or single
atoms.
• Lists are made up of zero or more atoms or inner lists, separated by
whitespace and surrounded by parentheses. A list can be empty.
• Atoms are multi-character symbols, like forward-paragraph, single
character symbols like +, strings of characters between double quota-
tion marks, or numbers.
• A number evaluates to itself.
• A string between double quotes also evaluates to itself.
• When you evaluate a symbol by itself, its value is returned.
• When you evaluate a list, the Lisp interpreter looks at the first symbol
in the list and then at the function definition bound to that symbol.
Then the instructions in the function definition are carried out.
• A single-quote, ’, tells the Lisp interpreter that it should return the
following expression as written, and not evaluate it as it would if the
quote were not there.
• Arguments are the information passed to a function. The arguments to
a function are computed by evaluating the rest of the elements of the
list of which the function is the first element.
• A function always returns a value when it is evaluated (unless it gets
an error); in addition, it may also carry out some action called a “side
effect”. In many cases, a function’s primary purpose is to create a side
effect.
" 3 0) (89.99552154541016 567.8603515625 191.33419799804688 582.2208862304688 "1.11 Exercises
" 4 0) (98.99540710449219 590.2490844726562 449.3295593261719 630.7872924804688 "A few simple exercises:
• Generate an error message by evaluating an appropriate symbol that is
not within parentheses.
" 5 0)) (39 (90.0 47.60907745361328 449.8256530761719 60.90726852416992 "Exercises
21
" 0 0) (98.99981689453125 77.48908233642578 449.3341979980469 144.5472869873047 "• Generate an error message by evaluating an appropriate symbol that is
between parentheses.
• Create a counter that increments by two rather than one.
• Write an expression that prints a message in the echo area when evalu-
ated.
" 1 0)) (40 (90.0 47.60907745361328 449.7926025390625 60.90726852416992 "22
Chapter 1: List Processing
" 0 0)) (41 (90.0 47.60907745361328 449.8140563964844 60.90726852416992 "Buffer Names
23
" 0 0) (89.9993896484375 75.14844512939453 292.32098388671875 92.38106536865234 "2 Practicing Evaluation
" 1 0) (89.997802734375 102.08905792236328 449.6385498046875 434.1072692871094 "Before learning how to write a function definition in Emacs Lisp, it is
useful to spend a little time evaluating various expressions that have already
been written. These expressions will be lists with the functions as their first
(and often only) element. Since some of the functions associated with buffers
are both simple and interesting, we will start with those. In this section, we
will evaluate a few of these. In another section, we will study the code of
several other buffer-related functions, to see how they were written.
Whenever you give an editing command to Emacs Lisp, such as the com-
mand to move the cursor or to scroll the screen, you are evaluating an ex-
pression, the first element of which is a function. This is how Emacs works.
When you type keys, you cause the Lisp interpreter to evaluate an expres-
sion and that is how you get your results. Even typing plain text involves
evaluating an Emacs Lisp function, in this case, one that uses self-insert-
command, which simply inserts the character you typed. The functions you
evaluate by typing keystrokes are called interactive functions, or commands;
how you make a function interactive will be illustrated in the chapter on
how to write function definitions. See Section 3.3, “Making a Function In-
teractive”, page 33.
In addition to typing keyboard commands, we have seen a second way
to evaluate an expression: by positioning the cursor after a list and typing
C-x C-e. This is what we will do in the rest of this section. There are other
ways to evaluate an expression as well; these will be described as we come
to them.
Besides being used for practicing evaluation, the functions shown in the
next few sections are important in their own right. A study of these functions
makes clear the distinction between buffers and files, how to switch to a
buffer, and how to determine a location within it.
" 2 0) (89.9981689453125 449.9003601074219 215.32943725585938 464.2608947753906 "2.1 Buffer Names
" 3 0) (89.99673461914062 472.049072265625 449.4408264160156 630.787353515625 "The two functions, buffer-name and buffer-file-name, show the differ-
ence between a file and a buffer. When you evaluate the following expression,
(buffer-name), the name of the buffer appears in the echo area. When you
evaluate (buffer-file-name), the name of the file to which the buffer refers
appears in the echo area. Usually, the name returned by (buffer-name) is
the same as the name of the file to which it refers, and the name returned
by (buffer-file-name) is the full path-name of the file.
A file and a buffer are two different entities. A file is information recorded
permanently in the computer (unless you delete it). A buffer, on the other
hand, is information inside of Emacs that will vanish at the end of the editing
session (or when you kill the buffer). Usually, a buffer contains information
that you have copied from a file; we say the buffer is visiting that file. This
copy is what you work on and modify. Changes to the buffer do not change
" 4 0)) (42 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "24
Chapter 2: Practicing Evaluation
" 0 0) (89.99951171875 77.48908233642578 449.3558044433594 142.15606689453125 "the file, until you save the buffer. When you save the buffer, the buffer is
copied to the file and is thus saved permanently.
If you are reading this in Info inside of GNU Emacs, you can evaluate
each of the following expressions by positioning the cursor after it and typing
C-x C-e.
" 1 0) (111.60028076171875 148.53750610351562 172.3654022216797 157.50389099121094 "(buffer-name)
" 2 0) (89.99502563476562 173.49752807617188 450.076171875 630.7871704101562 "(buffer-file-name)
When I do this, ‘\"introduction.texinfo\"’ is the value returned by eval-
uating (buffer-name), and ‘\"/gnu/work/intro/introduction.texinfo\"’
is the value returned by evaluating (buffer-file-name). The former is the
name of the buffer and the latter is the name of the file. (In the expres-
sions, the parentheses tell the Lisp interpreter to treat buffer-name and
buffer-file-name as functions; without the parentheses, the interpreter
would attempt to evaluate the symbols as variables. See Section 1.7, “Vari-
ables”, page 10.)
In spite of the distinction between files and buffers, you will often find
that people refer to a file when they mean a buffer and vice-versa. Indeed,
most people say, “I am editing a file,” rather than saying, “I am editing a
buffer which I will soon save to a file.” It is almost always clear from context
what people mean. When dealing with computer programs, however, it is
important to keep the distinction in mind, since the computer is not as smart
as a person.
The word ‘buffer’, by the way, comes from the meaning of the word as
a cushion that deadens the force of a collision. In early computers, a buffer
cushioned the interaction between files and the computer’s central processing
unit. The drums or tapes that held a file and the central processing unit
were pieces of equipment that were very different from each other, working
at their own speeds, in spurts. The buffer made it possible for them to work
together effectively. Eventually, the buffer grew from being an intermediary,
a temporary holding place, to being the place where work is done. This
transformation is rather like that of a small seaport that grew into a great
city: once it was merely the place where cargo was warehoused temporarily
before being loaded onto ships; then it became a business and cultural center
in its own right.
Not all buffers are associated with files. For example, when you start
an Emacs session by typing the command emacs alone, without naming any
files, Emacs will start with the ‘*scratch*’ buffer on the screen. This buffer
is not visiting any file. Similarly, a ‘*Help*’ buffer is not associated with
any file.
If you switch to the ‘*scratch*’ buffer, type (buffer-name), position
the cursor after it, and type C-x C-e to evaluate the expression, the name
\"*scratch*\" is returned and will appear in the echo area. \"*scratch*\"
is the name of the buffer. However, if you type (buffer-file-name) in
" 3 0)) (43 (90.0 47.60907745361328 449.78125 60.90726852416992 "Getting Buffers
25
" 0 0) (89.99859619140625 77.48908233642578 449.4100036621094 176.46726989746094 "the ‘*scratch*’ buffer and evaluate that, nil will appear in the echo area.
nil is from the Latin word for ‘nothing’; in this case, it means that the
‘*scratch*’ buffer is not associated with any file. (In Lisp, nil is also used
to mean ‘false’ and is a synonym for the empty list, ().)
Incidentally, if you are in the ‘*scratch*’ buffer and want the value
returned by an expression to appear in the ‘*scratch*’ buffer itself rather
than in the echo area, type C-u C-x C-e instead of C-x C-e. This causes the
value returned to appear after the expression. The buffer will look like this:
" 1 0) (89.99822998046875 181.53762817382812 449.3982238769531 240.9072723388672 "(buffer-name)\"*scratch*\"
You cannot do this in Info since Info is read-only and it will not allow you
to change the contents of the buffer. But you can do this in any buffer you
can edit; and when you write code or documentation (such as this book),
this feature is very useful.
" 2 0) (89.99812316894531 257.54034423828125 228.2606201171875 271.90087890625 "2.2 Getting Buffers
" 3 0) (89.99639892578125 279.6890869140625 449.77862548828125 514.50732421875 "The buffer-name function returns the name of the buffer; to get the
buffer itself, a different function is needed: the current-buffer function. If
you use this function in code, what you get is the buffer itself.
A name and the object or entity to which the name refers are different
from each other. You are not your name. You are a person to whom others
refer by name. If you ask to speak to George and someone hands you a
card with the letters ‘G’, ‘e’, ‘o’, ‘r’, ‘g’, and ‘e’ written on it, you might be
amused, but you would not be satisfied. You do not want to speak to the
name, but to the person to whom the name refers. A buffer is similar: the
name of the scratch buffer is ‘*scratch*’, but the name is not the buffer.
To get a buffer itself, you need to use a function such as current-buffer.
However, there is a slight complication: if you evaluate current-buffer
in an expression on its own, as we will do here, what you see is a printed
representation of the name of the buffer without the contents of the buffer.
Emacs works this way for two reasons: the buffer may be thousands of lines
long—too long to be conveniently displayed; and, another buffer may have
the same contents but a different name, and it is important to distinguish
between them.
Here is an expression containing the function:
" 4 0) (89.99655151367188 519.4577026367188 449.4071044921875 630.787353515625 "(current-buffer)
If you evaluate the expression in the usual way, ‘#<buffer *info*>’ appears
in the echo area. The special format indicates that the buffer itself is being
returned, rather than just its name.
Incidentally, while you can type a number or symbol into a program, you
cannot do that with the printed representation of a buffer: the only way to
get a buffer itself is with a function such as current-buffer.
A related function is other-buffer. This returns the most recently se-
lected buffer other than the one you are in currently. If you have recently
" 5 0)) (44 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "26
Chapter 2: Practicing Evaluation
" 0 0) (89.99960327148438 77.48908233642578 449.38861083984375 117.30728912353516 "switched back and forth from the ‘*scratch*’ buffer, other-buffer will
return that buffer.
You can see this by evaluating the expression:
" 1 0) (89.99948120117188 122.85763549804688 449.3883972167969 158.7073211669922 "(other-buffer)
You should see ‘#<buffer *scratch*>’ appear in the echo area, or the name
of whatever other buffer you switched back from most recently1.
" 2 0) (89.99954223632812 177.2603759765625 242.77392578125 191.62091064453125 "2.3 Switching Buffers
" 3 0) (89.9981689453125 199.88909912109375 449.7664794921875 376.2673645019531 "The other-buffer function actually provides a buffer when it is used
as an argument to a function that requires one. We can see this by using
other-buffer and switch-to-buffer to switch to a different buffer.
But first, a brief introduction to the switch-to-buffer function. When
you switched back and forth from Info to the ‘*scratch*’ buffer to evaluate
(buffer-name), you most likely typed C-x b and then typed ‘*scratch*’2
when prompted in the minibuffer for the name of the buffer to which you
wanted to switch. The keystrokes, C-x b, cause the Lisp interpreter to eval-
uate the interactive function switch-to-buffer. As we said before, this is
how Emacs works: different keystrokes call or run different functions. For
example, C-f calls forward-char, M-e calls forward-sentence, and so on.
By writing switch-to-buffer in an expression, and giving it a buffer to
switch to, we can switch buffers just the way C-x b does.
Here is the Lisp expression:
" 4 0) (89.99703979492188 381.8177185058594 449.5504150390625 507.2898864746094 "(switch-to-buffer (other-buffer))
The symbol switch-to-buffer is the first element of the list, so the Lisp
interpreter will treat it as a function and carry out the instructions that
are attached to it.
But before doing that, the interpreter will note that
other-buffer is inside parentheses and work on that symbol first. other-
buffer is the first (and in this case, the only) element of this list, so the Lisp
interpreter calls or runs the function. It returns another buffer. Next, the
interpreter runs switch-to-buffer, passing to it, as an argument, the other
buffer, which is what Emacs will switch to. If you are reading this in Info,
try this now. Evaluate the expression. (To get back, type C-x b ⟨
" 5 0) (401.6280212402344 491.5119934082031 419.7480163574219 491.99200439453125 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (401.6400146484375 492.7224426269531 419.7401428222656 500.6925354003906 "RET
" 7 0) (401.6280212402344 500.0320129394531 419.7480163574219 500.51202392578125 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (419.2799987792969 488.1290588378906 434.0481262207031 506.9297790527344 "⟩.)3
" 9 0) (89.98799896240234 512.3919677734375 233.98800659179688 512.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (95.87995910644531 513.4552001953125 449.8567810058594 615.3016357421875 "1 Actually, by default, if the buffer from which you just switched is visible to you in
another window, other-buffer will choose the most recent buffer that you cannot see;
this is a subtlety that I often forget.
2 Or rather, to save typing, you probably typed just part of the name, such as *sc, and
then pressed your TAB key to cause it to expand to the full name; and then typed your
RET key.
3 Remember, this expression will move you to your most recent other buffer that you
cannot see. If you really want to go to your most recently selected buffer, even if you
can still see it, you need to evaluate the following more complex expression:
" 11 0) (111.60035705566406 621.3377075195312 355.89874267578125 630.3040771484375 "(switch-to-buffer (other-buffer (current-buffer) t))
" 12 0)) (45 (90.0 47.60907745361328 449.5959167480469 60.90726852416992 "Buffer Size and the Location of Point
27
" 0 0) (89.99728393554688 77.48908233642578 449.47625732421875 300.0672912597656 "In the programming examples in later sections of this document, you will
see the function set-buffer more often than switch-to-buffer. This is
because of a difference between computer programs and humans: humans
have eyes and expect to see the buffer on which they are working on their
computer terminals. This is so obvious, it almost goes without saying. How-
ever, programs do not have eyes. When a computer program works on a
buffer, that buffer does not need to be visible on the screen.
switch-to-buffer is designed for humans and does two different things:
it switches the buffer to which Emacs’ attention is directed; and it switches
the buffer displayed in the window to the new buffer. set-buffer, on the
other hand, does only one thing: it switches the attention of the computer
program to a different buffer. The buffer on the screen remains unchanged (of
course, normally nothing happens there until the command finishes running).
Also, we have just introduced another jargon term, the word call. When
you evaluate a list in which the first symbol is a function, you are calling
that function. The use of the term comes from the notion of the function as
an entity that can do something for you if you ‘call’ it—just as a plumber is
an entity who can fix a leak if you call him or her.
" 1 0) (89.99729919433594 320.7803955078125 382.8487243652344 335.14093017578125 "2.4 Buffer Size and the Location of Point
" 2 0) (89.99652099609375 344.0091247558594 449.4404602050781 408.18731689453125 "Finally, let’s look at several rather simple functions, buffer-size, point,
point-min, and point-max. These give information about the size of a buffer
and the location of point within it.
The function buffer-size tells you the size of the current buffer; that
is, the function returns a count of the number of characters in the buffer.
" 3 0) (89.99505615234375 414.2176818847656 449.3948669433594 528.54736328125 "(buffer-size)
You can evaluate this in the usual way, by positioning the cursor after the
expression and typing C-x C-e.
In Emacs, the current position of the cursor is called point. The expres-
sion (point) returns a number that tells you where the cursor is located as
a count of the number of characters from the beginning of the buffer up to
point.
You can see the character count for point in this buffer by evaluating the
following expression in the usual way:
" 4 0) (89.99472045898438 534.6976928710938 449.3069152832031 571.02734375 "(point)
As I write this, the value of point is 65724. The point function is frequently
used in some of the examples later in this book.
" 5 0) (89.98799896240234 583.6719970703125 233.98800659179688 584.1519775390625 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (105.0 588.4552001953125 449.8509216308594 630.308837890625 "In this case, the first argument to other-buffer tells it which buffer to skip—the
current one—and the second argument tells other-buffer it is OK to switch to a
visible buffer.
In regular use, switch-to-buffer takes you to an invisible window
since you would most likely use C-x o (other-window) to go to another visible buffer.
" 7 0)) (46 (90.0 47.60907745361328 449.4980163574219 60.90726852416992 "28
Chapter 2: Practicing Evaluation
" 0 0) (90.0001220703125 79.52906036376953 449.50830078125 104.8272476196289 "The value of point depends, of course, on its location within the buffer.
If you evaluate point in this spot, the number will be larger:
" 1 0) (89.99801635742188 109.77761840820312 449.4309997558594 230.82725524902344 "(point)
For me, the value of point in this location is 66043, which means that there
are 319 characters (including spaces) between the two expressions.
The function point-min is somewhat similar to point, but it returns the
value of the minimum permissible value of point in the current buffer. This
is the number 1 unless narrowing is in effect. (Narrowing is a mechanism
whereby you can restrict yourself, or a program, to operations on just a part
of a buffer. See Chapter 6, “Narrowing and Widening”, page 77.) Likewise,
the function point-max returns the value of the maximum permissible value
of point in the current buffer.
" 2 0) (89.99761199951172 247.2203369140625 176.9756317138672 261.58087158203125 "2.5 Exercise
" 3 0) (89.9976806640625 269.36907958984375 449.4519958496094 294.5472717285156 "Find a file with which you are working and move towards its middle.
Find its buffer name, file name, length, and your position in the file.
" 4 0)) (47 (90.0 47.60907745361328 449.7158508300781 60.90726852416992 "The defun Special Form
29
" 0 0) (89.99920654296875 75.14844512939453 408.7035217285156 92.38106536865234 "3 How To Write Function Definitions
" 1 0) (89.99887084960938 100.40906524658203 449.50750732421875 356.8272399902344 "When the Lisp interpreter evaluates a list, it looks to see whether the first
symbol on the list has a function definition attached to it; or, put another
way, whether the symbol points to a function definition.
If it does, the
computer carries out the instructions in the definition. A symbol that has a
function definition is called, simply, a function (although, properly speaking,
the definition is the function and the symbol refers to it.)
All functions are defined in terms of other functions, except for a few
primitive functions that are written in the C programming language. When
you write functions’ definitions, you will write them in Emacs Lisp and use
other functions as your building blocks. Some of the functions you will use
will themselves be written in Emacs Lisp (perhaps by you) and some will be
primitives written in C. The primitive functions are used exactly like those
written in Emacs Lisp and behave like them. They are written in C so we
can easily run GNU Emacs on any computer that has sufficient power and
can run C.
Let me re-emphasize this: when you write code in Emacs Lisp, you do
not distinguish between the use of functions written in C and the use of
functions written in Emacs Lisp. The difference is irrelevant.
I mention
the distinction only because it is interesting to know. Indeed, unless you
investigate, you won’t know whether an already-written function is written
in Emacs Lisp or C.
" 2 0) (89.99930572509766 371.66033935546875 285.83026123046875 386.0335693359375 "3.1 The defun Special Form
" 3 0) (89.99844360351562 393.8090515136719 449.5723876953125 630.787353515625 "In Lisp, a symbol such as mark-whole-buffer has code attached to it that
tells the computer what to do when the function is called. This code is called
the function definition and is created by evaluating a Lisp expression that
starts with the symbol defun (which is an abbreviation for define function).
Because defun does not evaluate its arguments in the usual way, it is called
a special form.
In subsequent sections, we will look at function definitions from the Emacs
source code, such as mark-whole-buffer. In this section, we will describe
a simple function definition so you can see how it looks.
This function
definition uses arithmetic because it makes for a simple example.
Some
people dislike examples using arithmetic; however, if you are such a person,
do not despair. Hardly any of the code we will study in the remainder of
this introduction involves arithmetic or mathematics. The examples mostly
involve text in one way or another.
A function definition has up to five parts following the word defun:
1. The name of the symbol to which the function definition should be
attached.
2. A list of the arguments that will be passed to the function. If no argu-
ments will be passed to the function, this is an empty list, ().
" 4 0)) (48 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "30
Chapter 3: How To Write Function Definitions
" 0 0) (95.8790512084961 77.48908233642578 449.5083923339844 170.10728454589844 "3. Documentation describing the function.
(Technically optional, but
strongly recommended.)
4. Optionally, an expression to make the function interactive so you can
use it by typing M-x and then the name of the function; or by typing an
appropriate key or keychord.
5. The code that instructs the computer what to do: the body of the
function definition.
" 1 0) (89.9984130859375 175.4090576171875 449.4312744140625 200.58726501464844 "It is helpful to think of the five parts of a function definition as being
organized in a template, with slots for each part:
" 2 0) (89.99749755859375 206.49517822265625 449.25555419921875 292.1471862792969 "(defun function-name (arguments...)
\"optional-documentation...\"
(interactive argument-passing-info)
; optional
body...)
As an example, here is the code for a function that multiplies its argument
by 7. (This example is not interactive. See Section 3.3, “Making a Function
Interactive”, page 33, for that information.)
" 3 0) (89.99642944335938 298.0575256347656 449.4833984375 630.7872314453125 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
This definition begins with a parenthesis and the symbol defun, followed
by the name of the function.
The name of the function is followed by a list that contains the arguments
that will be passed to the function. This list is called the argument list. In
this example, the list has only one element, the symbol, number. When the
function is used, the symbol will be bound to the value that is used as the
argument to the function.
Instead of choosing the word number for the name of the argument, I
could have picked any other name. For example, I could have chosen the
word multiplicand. I picked the word ‘number’ because it tells what kind
of value is intended for this slot; but I could just as well have chosen the
word ‘multiplicand’ to indicate the role that the value placed in this slot
will play in the workings of the function. I could have called it foogle, but
that would have been a bad choice because it would not tell humans what it
means. The choice of name is up to the programmer and should be chosen
to make the meaning of the function clear.
Indeed, you can choose any name you wish for a symbol in an argument
list, even the name of a symbol used in some other function: the name
you use in an argument list is private to that particular definition. In that
definition, the name refers to a different entity than any use of the same name
outside the function definition. Suppose you have a nick-name ‘Shorty’ in
your family; when your family members refer to ‘Shorty’, they mean you.
But outside your family, in a movie, for example, the name ‘Shorty’ refers to
someone else. Because a name in an argument list is private to the function
" 4 0)) (49 (90.0 47.60907745361328 449.6510314941406 60.90726852416992 "Install a Function Definition
31
" 0 0) (89.9986572265625 77.48908233642578 449.6072692871094 329.7073669433594 "definition, you can change the value of such a symbol inside the body of a
function without changing its value outside the function. The effect is similar
to that produced by a let expression. (See Section 3.6, “let”, page 36.)
The argument list is followed by the documentation string that describes
the function. This is what you see when you type C-h f and the name of a
function. Incidentally, when you write a documentation string like this, you
should make the first line a complete sentence since some commands, such as
apropos, print only the first line of a multi-line documentation string. Also,
you should not indent the second line of a documentation string, if you have
one, because that looks odd when you use C-h f (describe-function). The
documentation string is optional, but it is so useful, it should be included in
almost every function you write.
The third line of the example consists of the body of the function defini-
tion. (Most functions’ definitions, of course, are longer than this.) In this
function, the body is the list, (* 7 number), which says to multiply the value
of number by 7. (In Emacs Lisp, * is the function for multiplication, just as
+ is the function for addition.)
When you use the multiply-by-seven function, the argument number
evaluates to the actual number you want used. Here is an example that
shows how multiply-by-seven is used; but don’t try to evaluate this yet!
" 1 0) (89.99813842773438 336.6977233886719 449.4861755371094 509.4673767089844 "(multiply-by-seven 3)
The symbol number, specified in the function definition in the next section,
is given or “bound to” the value 3 in the actual use of the function. Note
that although number was inside parentheses in the function definition, the
argument passed to the multiply-by-seven function is not in parentheses.
The parentheses are written in the function definition so the computer can
figure out where the argument list ends and the rest of the function definition
begins.
If you evaluate this example, you are likely to get an error message. (Go
ahead, try it!) This is because we have written the function definition, but
not yet told the computer about the definition—we have not yet installed (or
‘loaded’) the function definition in Emacs. Installing a function is the process
that tells the Lisp interpreter the definition of the function. Installation is
described in the next section.
" 2 0) (89.99852752685547 533.6604614257812 318.361572265625 548.02099609375 "3.2 Install a Function Definition
" 3 0) (89.99853515625 557.7291870117188 449.4633483886719 630.7874145507812 "If you are reading this inside of Info in Emacs, you can try out the
multiply-by-seven function by first evaluating the function definition and
then evaluating (multiply-by-seven 3). A copy of the function definition
follows. Place the cursor after the last parenthesis of the function definition
and type C-x C-e. When you do this, multiply-by-seven will appear in the
echo area. (What this means is that when a function definition is evaluated,
" 4 0)) (50 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "32
Chapter 3: How To Write Function Definitions
" 0 0) (89.99884033203125 77.48908233642578 449.2569274902344 102.66727447509766 "the value it returns is the name of the defined function.) At the same time,
this action installs the function definition.
" 1 0) (89.99839782714844 108.33761596679688 449.6280212402344 244.03607177734375 "(defun multiply-by-seven (number)
\"Multiply NUMBER by seven.\"
(* 7 number))
By evaluating this defun, you have just installed multiply-by-seven in
Emacs. The function is now just as much a part of Emacs as forward-
word or any other editing function you use. (multiply-by-seven will stay
installed until you quit Emacs. To reload code automatically whenever you
start Emacs, see Section 3.5, “Installing Code Permanently”, page 36.)
You can see the effect of installing multiply-by-seven by evaluating the
following sample. Place the cursor after the following expression and type
C-x C-e. The number 21 will appear in the echo area.
" 2 0) (90.00173950195312 249.69760131835938 449.5650634765625 309.5472717285156 "(multiply-by-seven 3)
If you wish, you can read the documentation for the function by typing
C-h f (describe-function) and then the name of the function, multiply-
by-seven. When you do this, a ‘*Help*’ window will appear on your screen
that says:
" 3 0) (90.00132751464844 315.2176208496094 369.9828186035156 352.6361083984375 "multiply-by-seven:
Multiply NUMBER by seven.
(To return to a single window on your screen, type C-x 1.)
" 4 0) (90.00106811523438 368.0418395996094 317.6019287109375 381.1458435058594 "3.2.1 Change a Function Definition
" 5 0) (90.00045776367188 389.8490905761719 449.45574951171875 501.42730712890625 "If you want to change the code in multiply-by-seven, just rewrite it.
To install the new version in place of the old one, evaluate the function
definition again. This is how you modify code in Emacs. It is very simple.
As an example, you can change the multiply-by-seven function to add
the number to itself seven times instead of multiplying the number by seven.
It produces the same answer, but by a different path. At the same time, we
will add a comment to the code; a comment is text that the Lisp interpreter
ignores, but that a human reader may find useful or enlightening.
The
comment is that this is the “second version”.
" 6 0) (90.00033569335938 507.09527587890625 449.4554138183594 630.787353515625 "(defun multiply-by-seven (number)
; Second version.
\"Multiply NUMBER by seven.\"
(+ number number number number number number number))
The comment follows a semicolon, ‘;’. In Lisp, everything on a line that
follows a semicolon is a comment. The end of the line is the end of the
comment. To stretch a comment over two or more lines, begin each line
with a semicolon.
See Section 16.3, “Beginning a ‘.emacs’ File”, page 216, and section
“Comments” in The GNU Emacs Lisp Reference Manual, for more about
comments.
" 7 0)) (51 (90.0 47.60907745361328 449.6617126464844 60.90726852416992 "Make a Function Interactive
33
" 0 0) (90.00015258789062 77.48908233642578 449.4977111816406 152.9473114013672 "You can install this version of the multiply-by-seven function by eval-
uating it in the same way you evaluated the first function: place the cursor
after the last parenthesis and type C-x C-e.
In summary, this is how you write code in Emacs Lisp: you write a
function; install it; test it; and then make fixes or enhancements and install
it again.
" 1 0) (90.00015258789062 171.0203857421875 318.5445251464844 185.38092041015625 "3.3 Make a Function Interactive
" 2 0) (89.99545288085938 193.52911376953125 449.4504089355469 381.5473327636719 "You make a function interactive by placing a list that begins with the
special form interactive immediately after the documentation.
A user
can invoke an interactive function by typing M-x and then the name of the
function; or by typing the keys to which it is bound, for example, by typing
C-n for next-line or C-x h for mark-whole-buffer.
Interestingly, when you call an interactive function interactively, the value
returned is not automatically displayed in the echo area. This is because you
often call an interactive function for its side effects, such as moving forward
by a word or line, and not for the value returned. If the returned value
were displayed in the echo area each time you typed a key, it would be very
distracting.
Both the use of the special form interactive and one way to display a
value in the echo area can be illustrated by creating an interactive version
of multiply-by-seven.
Here is the code:
" 3 0) (89.9947509765625 386.97528076171875 449.7109375 490.1298828125 "(defun multiply-by-seven (number)
; Interactive version.
\"Multiply NUMBER by seven.\"
(interactive \"p\")
(message \"The result is %d\" (* 7 number)))
You can install this code by placing your cursor after it and typing C-x C-e.
The name of the function will appear in your echo area. Then, you can use
this code by typing C-u and a number and then typing M-x multiply-by-
seven and pressing ⟨
" 4 0) (188.98800659179688 474.35198974609375 207.10800170898438 474.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (189.0 475.56243896484375 207.10011291503906 483.53253173828125 "RET
" 6 0) (188.98800659179688 482.8719787597656 207.10800170898438 483.35198974609375 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (89.9998779296875 470.9690856933594 449.6286926269531 589.1560668945312 "⟩. The phrase ‘The result is ...’ followed by the
product will appear in the echo area.
Speaking more generally, you invoke a function like this in either of two
ways:
1. By typing a prefix argument that contains the number to be passed,
and then typing M-x and the name of the function, as with C-u 3 M-x
forward-sentence; or,
2. By typing whatever key or keychord the function is bound to, as with
C-u 3 M-e.
" 8 0) (89.99884796142578 593.6090698242188 449.2897033691406 630.7872924804688 "Both the examples just mentioned work identically to move point forward
three sentences. (Since multiply-by-seven is not bound to a key, it could
not be used as an example of key binding.)
" 9 0)) (52 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "34
Chapter 3: How To Write Function Definitions
" 0 0) (89.99887084960938 77.48908233642578 449.442626953125 134.2097930908203 "(See Section 16.7, “Some Keybindings”, page 220, to learn how to bind
a command to a key.)
A prefix argument is passed to an interactive function by typing the
⟨
" 1 0) (92.86800384521484 118.7919921875 118.18800354003906 119.2719955444336 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (92.87999725341797 120.00239562988281 118.16650390625 127.9725112915039 "META
" 3 0) (92.86800384521484 127.31201171875 118.18800354003906 127.7920150756836 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00018310546875 115.04907989501953 449.5415344238281 152.58726501464844 "⟩ key followed by a number, for example, M-3 M-e, or by typing C-
u and then a number, for example, C-u 3 M-e (if you type C-u without a
number, it defaults to 4).
" 5 0) (90.00042724609375 166.081787109375 340.1502380371094 179.1973419189453 "3.3.1 An Interactive multiply-by-seven
" 6 0) (90.00039672851562 187.2890625 449.4432067871094 224.46726989746094 "Let’s look at the use of the special form interactive and then at the
function message in the interactive version of multiply-by-seven. You will
recall that the function definition looks like this:
" 7 0) (90.00021362304688 229.53521728515625 449.639892578125 340.5072326660156 "(defun multiply-by-seven (number)
; Interactive version.
\"Multiply NUMBER by seven.\"
(interactive \"p\")
(message \"The result is %d\" (* 7 number)))
In this function, the expression, (interactive \"p\"), is a list of two ele-
ments. The \"p\" tells Emacs to pass the prefix argument to the function and
use its value for the argument of the function.
The argument will be a number. This means that the symbol number
will be bound to a number in the line:
" 8 0) (90.00032043457031 345.57757568359375 449.1166076660156 381.0671081542969 "(message \"The result is %d\" (* 7 number))
For example, if your prefix argument is 5, the Lisp interpreter will evaluate
the line as if it were:
" 9 0) (89.99880981445312 386.0174560546875 449.5517883300781 630.7871704101562 "(message \"The result is %d\" (* 7 5))
(If you are reading this in GNU Emacs, you can evaluate this expression
yourself.) First, the interpreter will evaluate the inner list, which is (* 7
5). This returns a value of 35. Next, it will evaluate the outer list, passing
the values of the second and subsequent elements of the list to the function
message.
As we have seen, message is an Emacs Lisp function especially designed
for sending a one line message to a user. (See Section 1.8.5, “The message
function”, page 16.) In summary, the message function prints its first argu-
ment in the echo area as is, except for occurrences of ‘%d’, ‘%s’, or ‘%c’. When
it sees one of these control sequences, the function looks to the second and
subsequent arguments and prints the value of the argument in the location
in the string where the control sequence is located.
In the interactive multiply-by-seven function, the control string is ‘%d’,
which requires a number, and the value returned by evaluating (* 7 5) is
the number 35. Consequently, the number 35 is printed in place of the ‘%d’
and the message is ‘The result is 35’.
(Note that when you call the function multiply-by-seven, the message
is printed without quotes, but when you call message, the text is printed
in double quotes. This is because the value returned by message is what
" 10 0)) (53 (90.0 47.60907745361328 449.60723876953125 60.90726852416992 "Different Options for interactive
35
" 0 0) (89.99957275390625 77.48908233642578 449.4103088378906 114.66727447509766 "appears in the echo area when you evaluate an expression whose first element
is message; but when embedded in a function, message prints the text as a
side effect without quotes.)
" 1 0) (89.99964904785156 140.54034423828125 353.6011047363281 154.91355895996094 "3.4 Different Options for interactive
" 2 0) (90.0 165.08905029296875 449.3779296875 208.12977600097656 "In the example, multiply-by-seven used \"p\" as the argument to
interactive. This argument told Emacs to interpret your typing either
C-u followed by a number or ⟨
" 3 0) (237.8280029296875 192.35198974609375 263.14801025390625 192.8319854736328 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (237.83999633789062 193.56239318847656 263.1264953613281 201.53250122070312 "META
" 5 0) (237.8280029296875 200.87200927734375 263.14801025390625 201.3520050048828 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99932861328125 188.60906982421875 449.7263488769531 262.0272521972656 "⟩ followed by a number as a command
to pass that number to the function as its argument. Emacs has more than
twenty characters predefined for use with interactive. In almost every
case, one of these options will enable you to pass the right information in-
teractively to a function. (See section “Code Characters for interactive”
in The GNU Emacs Lisp Reference Manual.)
" 7 0) (89.99850463867188 265.1689453125 449.4425048828125 302.3471374511719 "For example, the character ‘r’ causes Emacs to pass the beginning and
end of the region (the current values of point and mark) to the function as
two separate arguments. It is used as follows:
" 8 0) (89.99786376953125 309.6974792480469 449.4625549316406 400.7296447753906 "(interactive \"r\")
On the other hand, a ‘B’ tells Emacs to ask for the name of a buffer that
will be passed to the function. When it sees a ‘B’, Emacs will ask for the
name by prompting the user in the minibuffer, using a string that follows
the ‘B’, as in \"BAppend to buffer: \". Not only will Emacs prompt for the
name, but Emacs will complete the name if you type enough of it and press
⟨
" 9 0) (92.86800384521484 385.31201171875 110.62800598144531 385.7920227050781 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (92.87999725341797 386.5224304199219 110.6187744140625 394.4925231933594 "TAB
" 11 0) (92.86800384521484 393.9519958496094 110.62800598144531 394.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (89.9998779296875 381.92913818359375 449.7382507324219 535.5073852539062 "⟩.
A function with two or more arguments can have information passed
to each argument by adding parts to the string that follows interactive.
When you do this, the information is passed to each argument in the same
order it is specified in the interactive list.
In the string, each part is
separated from the next part by a ‘\\n’, which is a newline. For example,
you could follow \"BAppend to buffer: \" with a ‘\\n’) and an ‘r’. This would
cause Emacs to pass the values of point and mark to the function as well as
prompt you for the buffer—three arguments in all.
In this case, the function definition would look like the following, where
buffer, start, and end are the symbols to which interactive binds the
buffer and the current values of the beginning and ending of the region:
" 13 0) (111.60009765625 542.8552856445312 301.69366455078125 589.1441040039062 "(defun name-of-function (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
body-of-function...)
" 14 0) (89.99908447265625 593.6091918945312 449.36614990234375 630.7874145507812 "(The space after the colon in the prompt makes it look better when you
are prompted. The append-to-buffer function looks exactly like this. See
Section 4.4, “The Definition of append-to-buffer”, page 56.)
" 15 0)) (54 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "36
Chapter 3: How To Write Function Definitions
" 0 0) (89.9991455078125 77.48908233642578 449.42108154296875 164.46726989746094 "If a function does not have arguments, then interactive does not require
any. Such a function contains the simple expression (interactive). The
mark-whole-buffer function is like this.
Alternatively, if the special letter-codes are not right for your application,
you can pass your own arguments to interactive as a list.
See section
“Using Interactive” in The GNU Emacs Lisp Reference Manual, for more
information about this advanced technique.
" 1 0) (89.99888610839844 180.8603515625 299.9631652832031 195.22088623046875 "3.5 Install Code Permanently
" 2 0) (89.99822998046875 203.00909423828125 449.5183410644531 454.3872985839844 "When you install a function definition by evaluating it, it will stay in-
stalled until you quit Emacs.
The next time you start a new session of
Emacs, the function will not be installed unless you evaluate the function
definition again.
At some point, you may want to have code installed automatically when-
ever you start a new session of Emacs.
There are several ways of doing
this:
• If you have code that is just for yourself, you can put the code for the
function definition in your ‘.emacs’ initialization file. When you start
Emacs, your ‘.emacs’ file is automatically evaluated and all the function
definitions within it are installed. See Chapter 16, “Your ‘.emacs’ File”,
page 213.
• Alternatively, you can put the function definitions that you want in-
stalled in one or more files of their own and use the load function to
cause Emacs to evaluate and thereby install each of the functions in the
files. See Section 16.9, “Loading Files”, page 222.
• On the other hand, if you have code that your whole site will use,
it is usual to put it in a file called ‘site-init.el’ that is loaded when
Emacs is built. This makes the code available to everyone who uses your
machine. (See the ‘INSTALL’ file that is part of the Emacs distribution.)
" 3 0) (89.994384765625 458.0091247558594 449.3945007324219 566.9473876953125 "Finally, if you have code that everyone who uses Emacs may want, you
can post it on a computer network or send a copy to the Free Software Foun-
dation. (When you do this, please license the code and its documentation
under a license that permits other people to run, copy, study, modify, and
redistribute the code and which protects you from having your work taken
from you.) If you send a copy of your code to the Free Software Foundation,
and properly protect yourself and others, it may be included in the next
release of Emacs. In large part, this is how Emacs has grown over the past
years, by donations.
" 4 0) (89.99435424804688 583.46044921875 140.906005859375 597.8336791992188 "3.6 let
" 5 0) (89.99359130859375 605.4891357421875 449.3171691894531 630.787353515625 "The let expression is a special form in Lisp that you will need to use in
most function definitions.
" 6 0)) (55 (90.0 47.60907745361328 449.6617126464844 60.90726852416992 "The Parts of a let Expression
37
" 0 0) (89.99655151367188 77.48908233642578 449.54119873046875 534.3071899414062 "let is used to attach or bind a symbol to a value in such a way that
the Lisp interpreter will not confuse the variable with a variable of the same
name that is not part of the function.
To understand why the let special form is necessary, consider the situa-
tion in which you own a home that you generally refer to as ‘the house’, as
in the sentence, “The house needs painting.” If you are visiting a friend and
your host refers to ‘the house’, he is likely to be referring to his house, not
yours, that is, to a different house.
If your friend is referring to his house and you think he is referring to
your house, you may be in for some confusion. The same thing could happen
in Lisp if a variable that is used inside of one function has the same name
as a variable that is used inside of another function, and the two are not
intended to refer to the same value. The let special form prevents this kind
of confusion.
The let special form prevents confusion. let creates a name for a local
variable that overshadows any use of the same name outside the let ex-
pression. This is like understanding that whenever your host refers to ‘the
house’, he means his house, not yours. (Symbols used in argument lists work
the same way. See Section 3.1, “The defun Special Form”, page 29.)
Local variables created by a let expression retain their value only within
the let expression itself (and within expressions called within the let ex-
pression); the local variables have no effect outside the let expression.
Another way to think about let is that it is like a setq that is temporary
and local. The values set by let are automatically undone when the let is
finished. The setting only effects expressions that are inside the bounds of
the let expression. In computer science jargon, we would say “the binding
of a symbol is visible only in functions called in the let form; in Emacs Lisp,
scoping is dynamic, not lexical.”
let can create more than one variable at once.
Also, let gives each
variable it creates an initial value, either a value specified by you, or nil.
(In the jargon, this is called ‘binding the variable to the value’.) After let
has created and bound the variables, it executes the code in the body of the
let, and returns the value of the last expression in the body, as the value of
the whole let expression. (‘Execute’ is a jargon term that means to evaluate
a list; it comes from the use of the word meaning ‘to give practical effect to’
(Oxford English Dictionary). Since you evaluate an expression to perform
an action, ‘execute’ has evolved as a synonym to ‘evaluate’.)
" 1 0) (89.99635314941406 548.2816772460938 320.2282409667969 561.397216796875 "3.6.1 The Parts of a let Expression
" 2 0) (89.99591064453125 569.6089477539062 449.42822265625 630.7871704101562 "A let expression is a list of three parts. The first part is the symbol
let. The second part is a list, called a varlist, each element of which is
either a symbol by itself or a two-element list, the first element of which is
a symbol. The third part of the let expression is the body of the let. The
body usually consists of one or more lists.
" 3 0)) (56 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "38
Chapter 3: How To Write Function Definitions
" 0 0) (104.99932861328125 85.64905548095703 329.6063537597656 98.9472427368164 "A template for a let expression looks like this:
" 1 0) (111.59925842285156 110.13507843017578 204.64085388183594 119.10386657714844 "(let varlist body...)
" 2 0) (89.99923706054688 126.32892608642578 449.5193786621094 187.5071258544922 "The symbols in the varlist are the variables that are given initial values by
the let special form. Symbols by themselves are given the initial value of
nil; and each symbol that is the first element of a two-element list is bound
to the value that is returned when the Lisp interpreter evaluates the second
element.
" 3 0) (89.9986572265625 194.2489013671875 449.33294677734375 231.42710876464844 "Thus, a varlist might look like this: (thread (needles 3)). In this case,
in a let expression, Emacs binds the symbol thread to an initial value of
nil, and binds the symbol needles to an initial value of 3.
" 4 0) (89.99810791015625 238.28887939453125 449.45269775390625 263.4670715332031 "When you write a let expression, what you do is put the appropriate
expressions in the slots of the let expression template.
" 5 0) (89.99835205078125 270.3289794921875 449.3871765136719 295.5071716308594 "If the varlist is composed of two-element lists, as is often the case, the
template for the let expression looks like this:
" 6 0) (111.59841918945312 306.69512939453125 207.2140350341797 352.9839172363281 "(let ((variable value)
(variable value)
...)
body...)
" 7 0) (89.99833679199219 384.24176025390625 273.5873718261719 397.3573303222656 "3.6.2 Sample let Expression
" 8 0) (89.99783325195312 411.5690002441406 449.2343444824219 448.7471923828125 "The following expression creates and gives initial values to the two vari-
ables zebra and tiger. The body of the let expression is a list which calls
the message function.
" 9 0) (111.59782409667969 459.8175354003906 379.4499206542969 506.22393798828125 "(let ((zebra ’stripes)
(tiger ’fierce))
(message \"One kind of animal has %s and another is %s.\"
zebra tiger))
" 10 0) (104.99815368652344 513.6890258789062 387.94696044921875 526.9872436523438 "Here, the varlist is ((zebra ’stripes) (tiger ’fierce)).
" 11 0) (89.99758911132812 533.72900390625 449.4306640625 630.7872314453125 "The two variables are zebra and tiger. Each variable is the first element
of a two-element list and each value is the second element of its two-element
list. In the varlist, Emacs binds the variable zebra to the value stripes, and
binds the variable tiger to the value fierce. In this example, both values
are symbols preceded by a quote. The values could just as well have been
another list or a string. The body of the let follows after the list holding the
variables. In this example, the body is a list that uses the message function
to print a string in the echo area.
" 12 0)) (57 (90.0 47.60907745361328 449.7485656738281 60.90726852416992 "The if Special Form
39
" 0 0) (89.9990234375 80.12909698486328 449.4104309082031 117.42728424072266 "You may evaluate the example in the usual fashion, by placing the cur-
sor after the last parenthesis and typing C-x C-e. When you do this, the
following will appear in the echo area:
" 1 0) (89.99917602539062 122.97763061523438 449.27899169921875 182.8273162841797 "\"One kind of animal has stripes and another is fierce.\"
As we have seen before, the message function prints its first argument,
except for ‘%s’. In this example, the value of the variable zebra is printed
at the location of the first ‘%s’ and the value of the variable tiger is printed
at the location of the second ‘%s’.
" 2 0) (89.99952697753906 198.12188720703125 399.14581298828125 211.23744201660156 "3.6.3 Uninitialized Variables in a let Statement
" 3 0) (90.00033569335938 219.80914306640625 449.35638427734375 257.1073303222656 "If you do not bind the variables in a let statement to specific initial
values, they will automatically be bound to an initial value of nil, as in the
following expression:
" 4 0) (90.00006103515625 262.6576843261719 449.3996276855469 388.26739501953125 "(let ((birch 3)
pine
fir
(oak ’some))
(message
\"Here are %d variables with %s, %s, and %s value.\"
birch pine fir oak))
Here, the varlist is ((birch 3) pine fir (oak ’some)).
If you evaluate this expression in the usual way, the following will appear
in your echo area:
" 5 0) (89.99850463867188 393.8177490234375 449.52935791015625 528.0675048828125 "\"Here are 3 variables with nil, nil, and some value.\"
In this example, Emacs binds the symbol birch to the number 3, binds the
symbols pine and fir to nil, and binds the symbol oak to the value some.
Note that in the first part of the let, the variables pine and fir stand
alone as atoms that are not surrounded by parentheses; this is because they
are being bound to nil, the empty list. But oak is bound to some and so
is a part of the list (oak ’some). Similarly, birch is bound to the number
3 and so is in a list with that number. (Since a number evaluates to itself,
the number does not need to be quoted. Also, the number is printed in the
message using a ‘%d’ rather than a ‘%s’.) The four variables as a group are
put into a list to delimit them from the body of the let.
" 6 0) (89.99874877929688 546.9805297851562 263.7757263183594 561.353759765625 "3.7 The if Special Form
" 7 0) (89.9986572265625 569.6092529296875 449.37689208984375 630.7874755859375 "A third special form, in addition to defun and let, is the conditional if.
This form is used to instruct the computer to make decisions. You can write
function definitions without using if, but it is used often enough, and is
important enough, to be included here. It is used, for example, in the code
for the function beginning-of-buffer.
" 8 0)) (58 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "40
Chapter 3: How To Write Function Definitions
" 0 0) (89.9993896484375 77.48908233642578 449.3011169433594 126.66727447509766 "The basic idea behind an if, is that “if a test is true, then an expression
is evaluated.” If the test is not true, the expression is not evaluated. For
example, you might make a decision such as, “if it is warm and sunny, then
go to the beach!”
" 1 0) (90.00003051757812 133.2890625 449.541015625 182.46726989746094 "An if expression written in Lisp does not use the word ‘then’; the test
and the action are the second and third elements of the list whose first
element is if. Nonetheless, the test part of an if expression is often called
the if-part and the second argument is often called the then-part.
" 2 0) (89.99954223632812 189.08905029296875 449.38836669921875 238.2672576904297 "Also, when an if expression is written, the true-or-false-test is usually
written on the same line as the symbol if, but the action to carry out if the
test is true, the “then-part”, is written on the second and subsequent lines.
This makes the if expression easier to read.
" 3 0) (111.59953308105469 249.2152099609375 266.74188232421875 270.6639709472656 "(if true-or-false-test
action-to-carry-out-if-test-is-true)
" 4 0) (89.99954223632812 278.12908935546875 449.3883056640625 303.3072814941406 "The true-or-false-test will be an expression that is evaluated by the Lisp
interpreter.
" 5 0) (89.99847412109375 309.9290771484375 449.3443908691406 347.2272644042969 "Here is an example that you can evaluate in the usual manner. The test is
whether the number 5 is greater than the number 4. Since it is, the message
‘5 is greater than 4!’ will be printed.
" 6 0) (111.59870910644531 358.1752014160156 347.1021728515625 379.6239929199219 "(if (> 5 4)
; if-part
(message \"5 is greater than 4!\"))
; then-part
" 7 0) (89.99832153320312 387.569091796875 449.27825927734375 412.8672790527344 "(The function > tests whether its first argument is greater than its second
argument and returns true if it is.)
" 8 0) (89.99765014648438 419.4891052246094 449.45269775390625 480.66729736328125 "Of course, in actual use, the test in an if expression will not be fixed
for all time as it is by the expression (> 5 4). Instead, at least one of the
variables used in the test will be bound to a value that is not known ahead
of time. (If the value were known ahead of time, we would not need to run
the test!)
" 9 0) (89.99691772460938 487.28912353515625 449.77838134765625 548.3473510742188 "For example, the value may be bound to an argument of a function defi-
nition. In the following function definition, the character of the animal is a
value that is passed to the function. If the value bound to characteristic
is fierce, then the message, ‘It’s a tiger!’ will be printed; otherwise, nil
will be returned.
" 10 0) (111.59686279296875 559.4176635742188 383.8551025390625 630.6640625 "(defun type-of-animal (characteristic)
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger.\"
(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")))
" 11 0)) (59 (90.0 47.60907745361328 449.5629577636719 60.90726852416992 "The type-of-animal Function in Detail
41
" 0 0) (89.99929809570312 79.76905059814453 449.2897033691406 117.0672378540039 "If you are reading this inside of GNU Emacs, you can evaluate the function
definition in the usual way to install it in Emacs, and then you can evaluate
the following two expressions to see the results:
" 1 0) (111.59971618652344 122.25759887695312 224.23960876464844 131.22398376464844 "(type-of-animal ’fierce)
" 2 0) (111.5997085571289 147.21762084960938 219.56813049316406 156.1840057373047 "(type-of-animal ’zebra)
" 3 0) (89.99862670898438 170.24908447265625 449.1593322753906 207.4272918701172 "When you evaluate (type-of-animal ’fierce), you will see the following
message printed in the echo area: \"It’s a tiger!\"; and when you evaluate
(type-of-animal ’zebra) you will see nil printed in the echo area.
" 4 0) (89.9989013671875 221.5218505859375 374.209228515625 234.6374053955078 "3.7.1 The type-of-animal Function in Detail
" 5 0) (89.998779296875 242.9691162109375 449.4207763671875 308.5874328613281 "Let’s look at the type-of-animal function in detail.
The function definition for type-of-animal was written by filling the
slots of two templates, one for a function definition as a whole, and a second
for an if expression.
The template for every function that is not interactive is:
" 6 0) (104.99870300292969 313.8953857421875 416.442138671875 363.6674499511719 "(defun name-of-function (argument-list)
\"documentation...\"
body...)
The parts of the function that match this template look like this:
" 7 0) (89.99978637695312 368.9779052734375 449.4326477050781 504.7875671386719 "(defun type-of-animal (characteristic)
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger.\"
body: the if expression)
The name of function is type-of-animal; it is passed the value of one
argument.
The argument list is followed by a multi-line documentation
string. The documentation string is included in the example because it is a
good habit to write documentation string for every function definition. The
body of the function definition consists of the if expression.
The template for an if expression looks like this:
" 8 0) (105.00108337402344 509.97552490234375 429.5027160644531 547.3876342773438 "(if true-or-false-test
action-to-carry-out-if-the-test-returns-true)
In the type-of-animal function, the code for the if looks like this:
" 9 0) (105.00122833251953 552.5780029296875 316.1464538574219 589.86767578125 "(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")))
Here, the true-or-false-test is the expression:
" 10 0) (90.00041961669922 595.1780395507812 449.400390625 630.7876586914062 "(equal characteristic ’fierce)
In Lisp, equal is a function that determines whether its first argument is
equal to its second argument. The second argument is the quoted symbol
" 11 0)) (60 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "42
Chapter 3: How To Write Function Definitions
" 0 0) (89.99932861328125 77.48908233642578 449.8138427734375 102.66727447509766 "’fierce and the first argument is the value of the symbol characteristic—
in other words, the argument passed to this function.
" 1 0) (89.999267578125 110.00910186767578 449.5413513183594 171.0673065185547 "In the first exercise of type-of-animal, the argument fierce is passed to
type-of-animal. Since fierce is equal to fierce, the expression, (equal
characteristic ’fierce), returns a value of true. When this happens, the
if evaluates the second argument or then-part of the if: (message \"It’s
tiger!\").
" 2 0) (89.99838256835938 178.40911865234375 449.4090270996094 215.5873260498047 "On the other hand, in the second exercise of type-of-animal, the argu-
ment zebra is passed to type-of-animal. zebra is not equal to fierce, so
the then-part is not evaluated and nil is returned by the if expression.
" 3 0) (89.99838256835938 258.50042724609375 290.74395751953125 272.8609619140625 "3.8 If–then–else Expressions
" 4 0) (89.9981689453125 287.2491455078125 449.3325500488281 360.3073425292969 "An if expression may have an optional third argument, called the else-
part, for the case when the true-or-false-test returns false. When this hap-
pens, the second argument or then-part of the overall if expression is not
evaluated, but the third or else-part is evaluated. You might think of this
as the cloudy day alternative for the decision ‘if it is warm and sunny, then
go to the beach, else read a book!”.
" 5 0) (89.99774169921875 367.649169921875 449.4740905761719 416.8273620605469 "The word “else” is not written in the Lisp code; the else-part of an if
expression comes after the then-part. In the written Lisp, the else-part is
usually written to start on a line of its own and is indented less than the
then-part:
" 6 0) (111.59774017333984 428.37530517578125 300.1712341308594 462.3041076660156 "(if true-or-false-test
action-to-carry-out-if-the-test-returns-true
action-to-carry-out-if-the-test-returns-false)
" 7 0) (89.99734497070312 470.24920654296875 449.4627685546875 495.5473937988281 "For example, the following if expression prints the message ‘4 is not
greater than 5!’ when you evaluate it in the usual way:
" 8 0) (111.59687805175781 507.21533203125 347.1088562011719 541.024169921875 "(if (> 4 5)
; if-part
(message \"5 is greater than 4!\")
; then-part
(message \"4 is not greater than 5!\")) ; else-part
" 9 0) (89.99740600585938 549.0892333984375 449.3863220214844 598.2674560546875 "Note that the different levels of indentation make it easy to distinguish the
then-part from the else-part. (GNU Emacs has several commands that au-
tomatically indent if expressions correctly. See Section 1.1.3, “GNU Emacs
Helps You Type Lists”, page 3.)
" 10 0) (89.997314453125 605.4891967773438 449.3753356933594 630.7874145507812 "We can extend the type-of-animal function to include an else-part by
simply incorporating an additional part to the if expression.
" 11 0)) (61 (90.0 47.60907745361328 449.6175231933594 60.90726852416992 "Truth and Falsehood in Emacs Lisp
43
" 0 0) (89.99917602539062 79.52906036376953 449.3661804199219 128.70726013183594 "You can see the consequences of doing this if you evaluate the following
version of the type-of-animal function definition to install it and then
evaluate the two subsequent expressions to pass different arguments to the
function.
" 1 0) (111.59921264648438 133.77520751953125 383.85723876953125 229.86387634277344 "(defun type-of-animal (characteristic)
; Second version.
\"Print message in echo area depending on CHARACTERISTIC.
If the CHARACTERISTIC is the symbol ‘fierce’,
then warn of a tiger;
else say it’s not fierce.\"
(if (equal characteristic ’fierce)
(message \"It’s a tiger!\")
(message \"It’s not fierce!\")))
" 2 0) (111.5989761352539 246.33749389648438 224.23887634277344 255.3038787841797 "(type-of-animal ’fierce)
" 3 0) (111.5989761352539 271.2975158691406 219.56739807128906 280.2638854980469 "(type-of-animal ’zebra)
" 4 0) (89.9976806640625 294.0889892578125 449.4304504394531 381.06719970703125 "When you evaluate (type-of-animal ’fierce), you will see the following
message printed in the echo area: \"It’s a tiger!\"; but when you evaluate
(type-of-animal ’zebra), you will see \"It’s not fierce!\".
(Of course, if the characteristic were ferocious, the message \"It’s not
fierce!\" would be printed; and it would be misleading! When you write
code, you need to take into account the possibility that some such argument
will be tested by the if and write your program accordingly.)
" 5 0) (89.99810791015625 396.140380859375 370.0843200683594 410.50091552734375 "3.9 Truth and Falsehood in Emacs Lisp
" 6 0) (89.99664306640625 418.16900634765625 449.47314453125 630.7872924804688 "There is an important aspect to the truth test in an if expression. So
far, we have spoken of ‘true’ and ‘false’ as values of predicates as if they were
new kinds of Emacs Lisp objects. In fact, ‘false’ is just our old friend nil.
Anything else—anything at all—is ‘true’.
The expression that tests for truth is interpreted as true if the result of
evaluating it is a value that is not nil. In other words, the result of the test
is considered true if the value returned is a number such as 47, a string such
as \"hello\", or a symbol (other than nil) such as flowers, or a list, or even
a buffer!
Before illustrating a test for truth, we need an explanation of nil.
In Emacs Lisp, the symbol nil has two meanings. First, it means the
empty list. Second, it means false and is the value returned when a true-or-
false-test tests false. nil can be written as an empty list, (), or as nil. As
far as the Lisp interpreter is concerned, () and nil are the same. Humans,
however, tend to use nil for false and () for the empty list.
In Emacs Lisp, any value that is not nil—is not the empty list—is con-
sidered true. This means that if an evaluation returns something that is not
" 7 0)) (62 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "44
Chapter 3: How To Write Function Definitions
" 0 0) (89.99884033203125 77.48908233642578 449.50787353515625 227.1073455810547 "an empty list, an if expression will test true. For example, if a number is
put in the slot for the test, it will be evaluated and will return itself, since
that is what numbers do when evaluated. In this conditional, the if expres-
sion will test true. The expression tests false only when nil, an empty list,
is returned by evaluating the expression.
You can see this by evaluating the two expressions in the following ex-
amples.
In the first example, the number 4 is evaluated as the test in the if
expression and returns itself; consequently, the then-part of the expression
is evaluated and returned: ‘true’ appears in the echo area. In the second
example, the nil indicates false; consequently, the else-part of the expression
is evaluated and returned: ‘false’ appears in the echo area.
" 1 0) (111.59869384765625 232.53768920898438 153.8319549560547 266.4640197753906 "(if 4
’true
’false)
" 2 0) (89.99874877929688 274.5376281738281 449.2897033691406 360.4272155761719 "(if nil
’true
’false)
Incidentally, if some other useful value is not available for a test that
returns true, then the Lisp interpreter will return the symbol t for true. For
example, the expression (> 5 4) returns t when evaluated, as you can see
by evaluating it in the usual way:
" 3 0) (89.99907684326172 365.8575744628906 392.6931457519531 389.70721435546875 "(> 5 4)
On the other hand, this function returns nil if the test is false.
" 4 0) (111.59896850585938 395.1375732421875 144.47213745117188 404.10394287109375 "(> 4 5)
" 5 0) (89.99890899658203 422.7803039550781 230.6892547607422 437.1535339355469 "3.10 save-excursion
" 6 0) (89.99594116210938 445.2890319824219 449.5833740234375 630.7872314453125 "The save-excursion function is the fourth and final special form that
we will discuss in this chapter.
In Emacs Lisp programs used for editing, the save-excursion function
is very common. It saves the location of point and mark, executes the body
of the function, and then restores point and mark to their previous positions
if their locations were changed. Its primary purpose is to keep the user from
being surprised and disturbed by unexpected movement of point or mark.
Before discussing save-excursion, however, it may be useful first to
review what point and mark are in GNU Emacs. Point is the current location
of the cursor.
Wherever the cursor is, that is point.
More precisely, on
terminals where the cursor appears to be on top of a character, point is
immediately before the character. In Emacs Lisp, point is an integer. The
first character in a buffer is number one, the second is number two, and
so on. The function point returns the current position of the cursor as a
number. Each buffer has its own value for point.
" 7 0)) (63 (90.0 47.60907745361328 449.5309143066406 60.90726852416992 "Template for a save-excursion Expression
45
" 0 0) (89.999755859375 77.48908233642578 449.4543151855469 108.16980743408203 "The mark is another position in the buffer; its value can be set with a
command such as C-⟨
" 1 0) (190.9080047607422 92.75201416015625 207.5880126953125 93.23201751708984 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (190.9199981689453 93.96241760253906 207.4659423828125 101.93253326416016 "SPC
" 3 0) (190.9080047607422 101.3919677734375 207.5880126953125 101.8719711303711 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (89.99887084960938 89.00910186767578 449.5196533203125 168.04981994628906 "⟩ (set-mark-command). If a mark has been set, you
can use the command C-x C-x (exchange-point-and-mark) to cause the
cursor to jump to the mark and set the mark to be the previous position
of point. In addition, if you set another mark, the position of the previous
mark is saved in the mark ring. Many mark positions can be saved this way.
You can jump the cursor to a saved mark by typing C-u C-⟨
" 5 0) (371.14801025390625 152.6319580078125 387.8280029296875 153.11195373535156 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (371.1600036621094 153.84242248535156 387.7059631347656 161.81253051757812 "SPC
" 7 0) (371.14801025390625 161.1519775390625 387.8280029296875 161.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 8 1) (89.994873046875 148.88909912109375 449.956298828125 483.3072814941406 "⟩ one or more
times.
The part of the buffer between point and mark is called the region. Nu-
merous commands work on the region, including center-region, count-
lines-region, kill-region, and print-region.
The save-excursion special form saves the locations of point and mark
and restores those positions after the code within the body of the special form
is evaluated by the Lisp interpreter. Thus, if point were in the beginning
of a piece of text and some code moved point to the end of the buffer, the
save-excursion would put point back to where it was before, after the
expressions in the body of the function were evaluated.
In Emacs, a function frequently moves point as part of its internal work-
ings even though a user would not expect this. For example, count-lines-
region moves point. To prevent the user from being bothered by jumps that
are both unexpected and (from the user’s point of view) unnecessary, save-
excursion is often used to keep point and mark in the location expected by
the user. The use of save-excursion is good housekeeping.
To make sure the house stays clean, save-excursion restores the values
of point and mark even if something goes wrong in the code inside of it (or,
to be more precise and to use the proper jargon, “in case of abnormal exit”).
This feature is very helpful.
In addition to recording the values of point and mark, save-excursion
keeps track of the current buffer, and restores it, too. This means you can
write code that will change the buffer and have save-excursion switch you
back to the original buffer. This is how save-excursion is used in append-
to-buffer.
(See Section 4.4, “The Definition of append-to-buffer”,
page 56.)
" 9 0) (89.994873046875 495.3618469238281 403.0967712402344 508.4774169921875 "3.10.1 Template for a save-excursion Expression
" 10 0) (104.99459838867188 516.569091796875 370.936279296875 529.8673095703125 "The template for code using save-excursion is simple:
" 11 0) (89.99346923828125 534.9376831054688 449.4045715332031 630.7872924804688 "(save-excursion
body...)
The body of the function is one or more expressions that will be evaluated
in sequence by the Lisp interpreter. If there is more than one expression
in the body, the value of the last one will be returned as the value of the
save-excursion function. The other expressions in the body are evaluated
only for their side effects; and save-excursion itself is used only for its side
effect (which is restoring the positions of point and mark).
" 12 0)) (64 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "46
Chapter 3: How To Write Function Definitions
" 0 0) (89.99957275390625 79.52906036376953 449.2681884765625 104.8272476196289 "In more detail, the template for a save-excursion expression looks like
this:
" 1 0) (89.99939727783203 109.77761840820312 449.3226013183594 221.5872039794922 "(save-excursion
first-expression-in-body
second-expression-in-body
third-expression-in-body
...
last-expression-in-body)
An expression, of course, may be a symbol on its own or a list.
In Emacs Lisp code, a save-excursion expression often occurs within
the body of a let expression. It looks like this:
" 2 0) (111.59974670410156 226.6551513671875 191.0677947998047 260.4638977050781 "(let varlist
(save-excursion
body...))
" 3 0) (89.99969482421875 275.18023681640625 177.9246826171875 289.540771484375 "3.11 Review
" 4 0) (89.99923706054688 297.32904052734375 449.355712890625 334.5072326660156 "In the last few chapters we have introduced a fair number of functions
and special forms. Here they are described in brief, along with a few similar
functions that have not been mentioned yet.
" 5 0) (89.99917602539062 339.8526611328125 449.5627746582031 411.0760498046875 "eval-last-sexp
Evaluate the last symbolic expression before the current location
of point. The value is printed in the echo area unless the function
is invoked with an argument; in that case, the output is printed
in the current buffer. This command is normally bound to C-x
C-e.
" 6 0) (89.99933624267578 414.56903076171875 449.5079650878906 478.2672119140625 "defun
Define function.
This special form has up to five parts: the
name, a template for the arguments that will be passed to the
function, documentation, an optional interactive declaration,
and the body of the definition.
For example:
" 7 0) (89.99830627441406 483.69757080078125 449.49609375 630.7872314453125 "(defun back-to-indentation ()
\"Move point to first visible character on line.\"
(interactive)
(beginning-of-line 1)
(skip-chars-forward \" \\t\"))
interactive
Declare to the interpreter that the function can be used interac-
tively. This special form may be followed by a string with one
or more parts that pass the information to the arguments of the
function, in sequence. These parts may also tell the interpreter
to prompt for information. Parts of the string are separated by
newlines, ‘\\n’.
" 8 0)) (65 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "Review
47
" 0 0) (147.60000610351562 77.48908233642578 288.6217346191406 90.78726959228516 "Common code characters are:
" 1 0) (147.59974670410156 98.36908721923828 355.07952880859375 111.66727447509766 "b
The name of an existing buffer.
" 2 0) (147.59934997558594 119.12909698486328 341.30096435546875 132.4272918701172 "f
The name of an existing file.
" 3 0) (147.5989532470703 140.00909423828125 449.51861572265625 165.3072967529297 "p
The numeric prefix argument. (Note that this ‘p’ is
lower case.)
" 4 0) (147.59942626953125 172.76910400390625 449.55194091796875 210.0673065185547 "r
Point and the mark, as two numeric arguments,
smallest first. This is the only code letter that spec-
ifies two successive arguments rather than one.
" 5 0) (147.59896850585938 217.52911376953125 449.36614990234375 254.8273162841797 "See section “Code Characters for ‘interactive’” in The GNU
Emacs Lisp Reference Manual, for a complete list of code char-
acters.
" 6 0) (89.99897003173828 262.28912353515625 449.7151184082031 335.4673156738281 "let
Declare that a list of variables is for use within the body of the
let and give them an initial value, either nil or a specified
value; then evaluate the rest of the expressions in the body of
the let and return the value of the last one. Inside the body
of the let, the Lisp interpreter does not see the values of the
variables of the same names that are bound outside of the let.
" 7 0) (147.59890747070312 338.609130859375 209.08262634277344 351.9073181152344 "For example,
" 8 0) (169.19894409179688 359.377685546875 380.4963684082031 418.1440734863281 "(let ((foo (buffer-name))
(bar (buffer-size)))
(message
\"This buffer is %s and has %d characters.\"
foo bar))
" 9 0) (89.99915313720703 427.33282470703125 449.5732727050781 474.6673583984375 "save-excursion
Record the values of point and mark and the current buffer
before evaluating the body of this special form.
Restore the
values of point and mark and buffer afterward.
" 10 0) (147.59910583496094 477.9291687011719 209.08282470703125 491.22735595703125 "For example,
" 11 0) (169.1991424560547 498.6977233886719 399.27691650390625 544.984130859375 "(message \"We are %d characters into this buffer.\"
(- (point)
(save-excursion
(goto-char (point-min)) (point))))
" 12 0) (89.99880981445312 553.2891845703125 449.4642333984375 590.4674072265625 "if
Evaluate the first argument to the function; if it is true, evaluate
the second argument; else evaluate the third argument, if there
is one.
" 13 0) (147.59886169433594 593.6091918945312 449.3445739746094 630.7874145507812 "The if special form is called a conditional. There are other con-
ditionals in Emacs Lisp, but if is perhaps the most commonly
used.
" 14 0)) (66 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "48
Chapter 3: How To Write Function Definitions
" 0 0) (147.59933471679688 80.72907257080078 209.0830535888672 94.02725982666016 "For example,
" 1 0) (169.19937133789062 100.05758666992188 371.13720703125 158.8238983154297 "(if (string-equal
(number-to-string 21)
(substring (emacs-version) 10 12))
(message \"This is version 21 Emacs\")
(message \"This is not version 21 Emacs\"))
" 2 0) (89.99952697753906 165.3726348876953 449.58465576171875 357.9071960449219 "equal
eq
Test whether two objects are the same. equal uses one meaning
of the word ‘same’ and eq uses another: equal returns true if
the two objects have a similar structure and contents, such as
two copies of the same book. On the other hand, eq, returns
true if both arguments are actually the same object.
<
>
<=
>=
The < function tests whether its first argument is smaller than
its second argument. A corresponding function, >, tests whether
the first argument is greater than the second. Likewise, <= tests
whether the first argument is less than or equal to the second
and >= tests whether the first argument is greater than or equal
to the second. In all cases, both arguments must be numbers or
markers (markers indicate positions in buffers).
" 3 0) (90.000732421875 364.692626953125 449.51043701171875 552.7872314453125 "string<
string-lessp
string=
string-equal
The string-lessp function tests whether its first argument is
smaller than the second argument. A shorter, alternative name
for the same function (a defalias) is string<.
The arguments to string-lessp must be strings or symbols;
the ordering is lexicographic, so case is significant. The print
names of symbols are used instead of the symbols themselves.
An empty string, ‘\"\"’, a string with no characters in it, is smaller
than any string of characters.
string-equal provides the corresponding test for equality. Its
shorter, alternative name is string=. There are no string test
functions that correspond to >, >=, or <=.
" 4 0) (90.00051879882812 557.72900390625 449.6075134277344 630.7872314453125 "message
Print a message in the echo area. The first argument is a string
that can contain ‘%s’, ‘%d’, or ‘%c’ to print the value of arguments
that follow the string. The argument used by ‘%s’ must be a
string or a symbol; the argument used by ‘%d’ must be a number.
The argument used by ‘%c’ must be an ascii code number; it will
be printed as the character with that ascii code.
" 5 0)) (67 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "Review
49
" 0 0) (90.0 79.33271789550781 449.48699951171875 162.5472869873047 "setq
set
The setq function sets the value of its first argument to the
value of the second argument. The first argument is automati-
cally quoted by setq. It does the same for succeeding pairs of
arguments. Another function, set, takes only two arguments
and evaluates both of them before setting the value returned by
its first argument to the value returned by its second argument.
" 1 0) (90.00051879882812 174.4927520751953 449.47625732421875 197.9473114013672 "buffer-name
Without an argument, return the name of the buffer, as a string.
" 2 0) (90.0 204.2527618408203 449.4541320800781 239.5873260498047 "buffer-file-name
Without an argument, return the name of the file the buffer is
visiting.
" 3 0) (89.9998550415039 251.6527862548828 449.5303955078125 286.9873352050781 "current-buffer
Return the buffer in which Emacs is active; it may not be the
buffer that is visible on the screen.
" 4 0) (89.9993896484375 299.05279541015625 449.5411376953125 346.3873596191406 "other-buffer
Return the most recently selected buffer (other than the buffer
passed to other-buffer as an argument and other than the
current buffer).
" 5 0) (89.99929809570312 358.33282470703125 449.51898193359375 393.7961730957031 "switch-to-buffer
Select a buffer for Emacs to be active in and display it in the
current window so users can look at it. Usually bound to C-x b.
" 6 0) (89.99923706054688 405.7327880859375 449.5954284667969 441.1873474121094 "set-buffer
Switch Emacs’ attention to a buffer on which programs will run.
Don’t alter what the window is showing.
" 7 0) (89.99992370605469 453.1328125 407.3122253417969 476.58734130859375 "buffer-size
Return the number of characters in the current buffer.
" 8 0) (90.00003051757812 486.80914306640625 449.39996337890625 523.9873657226562 "point
Return the value of the current position of the cursor, as an
integer counting the number of characters from the beginning of
the buffer.
" 9 0) (90.00067138671875 536.052734375 449.4986267089844 571.3873291015625 "point-min
Return the minimum permissible value of point in the current
buffer. This is 1, unless narrowing is in effect.
" 10 0) (90.00077819824219 583.4527587890625 449.47662353515625 630.787353515625 "point-max
Return the value of the maximum permissible value of point in
the current buffer. This is the end of the buffer, unless narrowing
is in effect.
" 11 0)) (68 (90.0 47.60907745361328 449.44342041015625 60.90726852416992 "50
Chapter 3: How To Write Function Definitions
" 0 0) (89.99932861328125 94.10033416748047 191.3380126953125 108.46088409423828 "3.12 Exercises
" 1 0) (98.99920654296875 114.20905303955078 449.69317626953125 178.2672576904297 "• Write a non-interactive function that doubles the value of its argument,
a number. Make that function interactive.
• Write a function that tests whether the current value of fill-column
is greater than the argument passed to the function, and if so, prints an
appropriate message.
" 2 0)) (69 (90.0 47.60907745361328 449.6835632324219 60.90726852416992 "Finding More Information
51
" 0 0) (89.99990844726562 75.14844512939453 385.9106140136719 92.38106536865234 "4 A Few Buffer–Related Functions
" 1 0) (89.99786376953125 106.64917755126953 449.40869140625 191.70738220214844 "In this chapter we study in detail several of the functions used in GNU
Emacs. This is called a “walk-through”. These functions are used as ex-
amples of Lisp code, but are not imaginary examples; with the exception of
the first, simplified function definition, these functions show the actual code
used in GNU Emacs. You can learn a great deal from these definitions. The
functions described here are all related to buffers. Later, we will study other
functions.
" 2 0) (89.9979248046875 210.740478515625 304.238525390625 225.10101318359375 "4.1 Finding More Information
" 3 0) (89.99746704101562 233.60919189453125 449.29949951171875 288.64990234375 "In this walk-through, I will describe each new function as we come to it,
sometimes in detail and sometimes briefly. If you are interested, you can get
the full documentation of any Emacs Lisp function at any time by typing
C-h f and then the name of the function (and then ⟨
" 4 0) (348.2279968261719 272.75201416015625 366.3479919433594 273.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (348.239990234375 274.0824279785156 366.3401184082031 282.0525207519531 "RET
" 6 0) (348.2279968261719 281.3919677734375 366.3479919433594 281.8719787597656 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (89.999755859375 269.48907470703125 449.7926940917969 312.52978515625 "⟩). Similarly, you
can get the full documentation for a variable by typing C-h v and then the
name of the variable (and then ⟨
" 8 0) (244.42800903320312 296.75201416015625 262.5480041503906 297.2320251464844 "<image: None, width: 1, height: 1, bpc: 1>" 9 1) (244.44000244140625 297.9624328613281 262.54010009765625 305.9325256347656 "RET
" 10 0) (244.42800903320312 305.27203369140625 262.5480041503906 305.7520446777344 "<image: None, width: 1, height: 1, bpc: 1>" 11 1) (90.00039672851562 293.36907958984375 449.4324951171875 351.0498046875 "⟩).
In versions 20 and higher, when a function is written in Emacs Lisp,
describe-function will also tell you the location of the function definition.
If you move point over the file name and press the ⟨
" 12 0) (341.7480163574219 335.2720031738281 359.8680114746094 335.75201416015625 "<image: None, width: 1, height: 1, bpc: 1>" 13 1) (341.760009765625 336.482421875 359.8601379394531 344.4525146484375 "RET
" 14 0) (341.7480163574219 343.7919921875 359.8680114746094 344.2720031738281 "<image: None, width: 1, height: 1, bpc: 1>" 15 1) (89.99880981445312 331.5290832519531 449.82550048828125 478.60980224609375 "⟩ key, which is this
case means help-follow rather than ‘return’ or ‘enter’, Emacs will take you
directly to the function definition.
More generally, if you want to see a function in its original source file,
you can use the find-tags function to jump to it. find-tags works with
a wide variety of languages, not just Lisp, and C, and it works with non-
programming text as well. For example, find-tags will jump to the various
nodes in the Texinfo source file of this document.
The find-tags function depends on ‘tags tables’ that record the locations
of the functions, variables, and other items to which find-tags jumps.
To use the find-tags command, type M-. (i.e., type the ⟨
" 16 0) (381.1080017089844 462.7120056152344 406.4280090332031 463.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 17 1) (381.1199951171875 464.04241943359375 406.406494140625 472.01251220703125 "META
" 18 0) (381.1080017089844 471.35198974609375 406.4280090332031 471.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 19 1) (90.00018310546875 459.0890808105469 450.0108337402344 490.48980712890625 "⟩ key and
the period key at the same time, or else type the ⟨
" 20 0) (337.4280090332031 474.7120056152344 354.1080017089844 475.1920166015625 "<image: None, width: 1, height: 1, bpc: 1>" 21 1) (337.44000244140625 475.92242431640625 353.9859619140625 483.89251708984375 "ESC
" 22 0) (337.4280090332031 483.35198974609375 354.1080017089844 483.8320007324219 "<image: None, width: 1, height: 1, bpc: 1>" 23 1) (90.00003051757812 470.9690856933594 449.90167236328125 526.3698120117188 "⟩ key and then type
the period key), and then, at the prompt, type in the name of the function
whose source code you want to see, such as mark-whole-buffer, and then
type ⟨
" 24 0) (118.30799865722656 510.59197998046875 136.42799377441406 511.0719909667969 "<image: None, width: 1, height: 1, bpc: 1>" 25 1) (118.31999969482422 511.8024597167969 136.4201202392578 519.7725830078125 "RET
" 26 0) (118.30799865722656 519.1119995117188 136.42799377441406 519.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 27 1) (90.00003051757812 507.2091064453125 449.4978332519531 549.8897705078125 "⟩. Emacs will switch buffers and display the source code for the
function on your screen. To switch back to your current buffer, type C-x b
⟨
" 28 0) (92.86800384521484 534.4719848632812 110.98800659179688 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 29 1) (92.87999725341797 535.6824340820312 110.98011779785156 543.652587890625 "RET
" 30 0) (92.86800384521484 543.1119995117188 110.98800659179688 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 31 1) (110.5199966430664 531.089111328125 248.74658203125 550.2498168945312 "⟩. (On some keyboards, the ⟨
" 32 0) (248.0279998779297 534.4719848632812 273.3479919433594 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 33 1) (248.0399932861328 535.6824340820312 273.3265075683594 543.652587890625 "META
" 34 0) (248.0279998779297 543.1119995117188 273.3479919433594 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 35 1) (272.760009765625 530.7290649414062 354.5865783691406 550.2498168945312 "⟩ key is labelled ⟨
" 36 0) (353.8680114746094 534.4719848632812 371.02801513671875 534.9519653320312 "<image: None, width: 1, height: 1, bpc: 1>" 37 1) (353.8800048828125 535.6824340820312 370.9014587402344 543.652587890625 "ALT
" 38 0) (353.8680114746094 543.1119995117188 371.02801513671875 543.5919799804688 "<image: None, width: 1, height: 1, bpc: 1>" 39 1) (89.99786376953125 531.089111328125 450.0957946777344 630.787353515625 "⟩.)
Depending on how the initial default values of your copy of Emacs are
set, you may also need to specify the location of your ‘tags table’, which
is a file called ‘TAGS’. For example, if you are interested in Emacs sources,
the tags table you will most likely want, if it has already been created for
you, will be in a subdirectory of the ‘/usr/local/share/emacs/’ direc-
tory; thus you would use the M-x visit-tags-table command and spec-
ify a pathname such as ‘/usr/local/share/emacs/21.0.100/lisp/TAGS’
" 40 0)) (70 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "52
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.99884033203125 77.48908233642578 449.21343994140625 102.66727447509766 "or ‘/usr/local/src/emacs/lisp/TAGS’. If the tags table has not already
been created, you will have to create it yourself.
" 1 0) (89.9990234375 107.12909698486328 449.3988342285156 156.1873016357422 "To create a ‘TAGS’ file in a specific directory, switch to that directory
in Emacs using M-x cd command, or list the directory with C-x d (dired).
Then run the compile command, with etags *.el as the command to exe-
cute
" 2 0) (111.59941864013672 164.85763549804688 252.54220581054688 173.8240203857422 "M-x compile RET etags *.el RET
" 3 0) (89.99945068359375 178.52911376953125 449.1486511230469 203.8273162841797 "For more information, see Section 12.5, “Create Your Own ‘TAGS’ File”,
page 163.
" 4 0) (89.99884033203125 208.04913330078125 449.3875732421875 245.2273406982422 "After you become more familiar with Emacs Lisp, you will find that you
will frequently use find-tags to navigate your way around source code; and
you will create your own ‘TAGS’ tables.
" 5 0) (89.99884033203125 249.56903076171875 449.3661193847656 370.3872375488281 "Incidentally, the files that contain Lisp code are conventionally called
libraries. The metaphor is derived from that of a specialized library, such as
a law library or an engineering library, rather than a general library. Each
library, or file, contains functions that relate to a particular topic or activity,
such as ‘abbrev.el’ for handling abbreviations and other typing shortcuts,
and ‘help.el’ for on-line help. (Sometimes several libraries provide code
for a single activity, as the various ‘rmail...’ files provide code for reading
electronic mail.) In The GNU Emacs Manual, you will see sentences such as
“The C-h p command lets you search the standard Emacs Lisp libraries by
topic keywords.”
" 6 0) (89.99909973144531 401.1803283691406 426.8679504394531 415.5535583496094 "4.2 A Simplified beginning-of-buffer Definition
" 7 0) (89.99945068359375 426.9290466308594 449.3887634277344 488.1160583496094 "The beginning-of-buffer command is a good function to start with
since you are likely to be familiar with it and it is easy to understand. Used
as an interactive command, beginning-of-buffer moves the cursor to the
beginning of the buffer, leaving the mark at the previous position.
It is
generally bound to M-<.
" 8 0) (89.99887084960938 492.32904052734375 449.34490966796875 553.3872680664062 "In this section, we will discuss a shortened version of the function that
shows how it is most frequently used.
This shortened function works as
written, but it does not contain the code for a complex option. In another
section, we will describe the entire function. (See Section 5.3, “Complete
Definition of beginning-of-buffer”, page 69.)
" 9 0) (89.99856567382812 557.7290649414062 449.453125 630.7872924804688 "Before looking at the code, let’s consider what the function definition has
to contain: it must include an expression that makes the function interactive
so it can be called by typing M-x beginning-of-buffer or by typing a
keychord such as C-<; it must include code to leave a mark at the original
position in the buffer; and it must include code to move the cursor to the
beginning of the buffer.
" 10 0)) (71 (90.0 47.60907745361328 449.5094299316406 60.90726852416992 "A Simplified beginning-of-buffer Definition
53
" 0 0) (105.00076293945312 80.36908721923828 420.15325927734375 93.66727447509766 "Here is the complete text of the shortened version of the function:
" 1 0) (90.00039672851562 99.57760620117188 449.3782043457031 277.2670593261719 "(defun simplified-beginning-of-buffer ()
\"Move point to the beginning of the buffer;
leave mark at previous position.\"
(interactive)
(push-mark)
(goto-char (point-min)))
Like all function definitions, this definition has five parts following the
special form defun:
1. The name: in this example, simplified-beginning-of-buffer.
2. A list of the arguments: in this example, an empty list, (),
3. The documentation string.
4. The interactive expression.
5. The body.
" 2 0) (89.99948120117188 282.56884765625 449.48712158203125 385.3870544433594 "In this function definition, the argument list is empty; this means that this
function does not require any arguments. (When we look at the definition
for the complete function, we will see that it may be passed an optional
argument.)
The interactive expression tells Emacs that the function is intended to be
used interactively. In this example, interactive does not have an argument
because simplified-beginning-of-buffer does not require one.
The body of the function consists of the two lines:
" 3 0) (89.99844360351562 391.1773986816406 449.5838317871094 636.6495971679688 "(push-mark)
(goto-char (point-min))
The first of these lines is the expression, (push-mark). When this ex-
pression is evaluated by the Lisp interpreter, it sets a mark at the current
position of the cursor, wherever that may be. The position of this mark is
saved in the mark ring.
The next line is (goto-char (point-min)). This expression jumps the
cursor to the minimum point in the buffer, that is, to the beginning of the
buffer (or to the beginning of the accessible portion of the buffer if it is
narrowed. See Chapter 6, “Narrowing and Widening”, page 77.)
The push-mark command sets a mark at the place where the cursor was
located before it was moved to the beginning of the buffer by the (goto-
char (point-min)) expression. Consequently, you can, if you wish, go back
to where you were originally by typing C-x C-x.
That is all there is to the function definition!
When you are reading code such as this and come upon an unfamiliar
function, such as goto-char, you can find out what it does by using the
describe-function command. To use this command, type C-h f and then
type in the name of the function and press ⟨
" 4 0) (300.947998046875 620.8720092773438 319.0679931640625 621.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (300.9599914550781 622.0823974609375 319.06011962890625 630.0525512695312 "RET
" 6 0) (300.947998046875 629.3919677734375 319.0679931640625 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 7 1) (318.6000061035156 617.4890747070312 450.3489074707031 636.289794921875 "⟩. The describe-function
" 8 0)) (72 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "54
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.9993896484375 77.48908233642578 449.35546875 102.66727447509766 "command will print the function’s documentation string in a ‘*Help*’ win-
dow. For example, the documentation for goto-char is:
" 1 0) (89.99880981445312 108.81759643554688 449.3445739746094 188.9297637939453 "One arg, a number.
Set point to that number.
Beginning of buffer is position (point-min),
end is (point-max).
(The prompt for describe-function will offer you the symbol under or
preceding the cursor, so you can save typing by positioning the cursor right
over or after the function and then typing C-h f ⟨
" 2 0) (327.1080017089844 173.1519775390625 345.2279968261719 173.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 3 1) (327.1199951171875 174.36244201660156 345.2201232910156 182.33255004882812 "RET
" 4 0) (327.1080017089844 181.6719970703125 345.2279968261719 182.15199279785156 "<image: None, width: 1, height: 1, bpc: 1>" 5 1) (89.99908447265625 169.76904296875 449.6611022949219 233.94725036621094 "⟩.)
The end-of-buffer function definition is written in the same way as
the beginning-of-buffer definition except that the body of the function
contains the expression (goto-char (point-max)) in place of (goto-char
(point-min)).
" 6 0) (89.99909210205078 254.90032958984375 371.3376159667969 269.2735595703125 "4.3 The Definition of mark-whole-buffer
" 7 0) (89.999267578125 278.1290283203125 449.4877014160156 381.5472106933594 "The mark-whole-buffer function is no harder to understand than the
simplified-beginning-of-buffer function. In this case, however, we will
look at the complete function, not a shortened version.
The mark-whole-buffer function is not as commonly used as the
beginning-of-buffer function, but is useful nonetheless: it marks a whole
buffer as a region by putting point at the beginning and a mark at the end
of the buffer. It is generally bound to C-x h.
In GNU Emacs 20, the code for the complete function looks like this:
" 8 0) (90.00177001953125 387.69757080078125 449.4015808105469 487.6272277832031 "(defun mark-whole-buffer ()
\"Put point at beginning and mark at end of buffer.\"
(interactive)
(push-mark (point))
(push-mark (point-max))
(goto-char (point-min)))
Like all other functions, the mark-whole-buffer function fits into the
template for a function definition. The template looks like this:
" 9 0) (90.00222778320312 493.7751770019531 449.6968078613281 630.7872314453125 "(defun name-of-function (argument-list)
\"documentation...\"
(interactive-expression...)
body...)
Here is how the function works: the name of the function is mark-whole-
buffer; it is followed by an empty argument list, ‘()’, which means that the
function does not require arguments. The documentation comes next.
The next line is an (interactive) expression that tells Emacs that
the function will be used interactively.
These details are similar to the
simplified-beginning-of-buffer function described in the previous sec-
tion.
" 10 0)) (73 (90.0 47.60907745361328 449.6732482910156 60.90726852416992 "Body of mark-whole-buffer
55
" 0 0) (90.00057983398438 78.2418212890625 297.62017822265625 91.35738372802734 "4.3.1 Body of mark-whole-buffer
" 1 0) (90.00100708007812 100.16907501220703 449.3463134765625 125.4672622680664 "The body of the mark-whole-buffer function consists of three lines of
code:
" 2 0) (89.99725341796875 131.13760375976562 449.5634460449219 445.369873046875 "(push-mark (point))
(push-mark (point-max))
(goto-char (point-min))
The first of these lines is the expression, (push-mark (point)).
This line does exactly the same job as the first line of the body of
the simplified-beginning-of-buffer function, which is written (push-
mark). In both cases, the Lisp interpreter sets a mark at the current position
of the cursor.
I don’t know why the expression in mark-whole-buffer is written (push-
mark (point)) and the expression in beginning-of-buffer is written
(push-mark). Perhaps whoever wrote the code did not know that the ar-
guments for push-mark are optional and that if push-mark is not passed an
argument, the function automatically sets mark at the location of point by
default. Or perhaps the expression was written so as to parallel the struc-
ture of the next line. In any case, the line causes Emacs to determine the
position of point and set a mark there.
The next line of mark-whole-buffer is (push-mark (point-max). This
expression sets a mark at the point in the buffer that has the highest number.
This will be the end of the buffer (or, if the buffer is narrowed, the end of the
accessible portion of the buffer. See Chapter 6, “Narrowing and Widening”,
page 77, for more about narrowing.)
After this mark has been set, the
previous mark, the one set at point, is no longer set, but Emacs remembers
its position, just as all other recent marks are always remembered. This
means that you can, if you wish, go back to that position by typing C-u
C-⟨
" 3 0) (104.38800048828125 429.9519958496094 121.06800079345703 430.4320068359375 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (104.4000015258789 431.1624450683594 120.9459457397461 439.1325378417969 "SPC
" 5 0) (104.38800048828125 438.47198486328125 121.06800079345703 438.9519958496094 "<image: None, width: 1, height: 1, bpc: 1>" 6 1) (89.99981689453125 426.2090759277344 449.3128356933594 466.5072937011719 "⟩ twice.
(In GNU Emacs 21, the (push-mark (point-max) is slightly more com-
plicated than shown here. The line reads
" 7 0) (89.99786376953125 472.2976379394531 449.976318359375 630.787353515625 "(push-mark (point-max) nil t)
(The expression works nearly the same as before.
It sets a mark at the
highest numbered place in the buffer that it can. However, in this version,
push-mark has two additional arguments. The second argument to push-
mark is nil. This tells the function it should display a message that says
‘Mark set’ when it pushes the mark. The third argument is t. This tells
push-mark to activate the mark when Transient Mark mode is turned on.
Transient Mark mode highlights the currently active region. It is usually
turned off.)
Finally, the last line of the function is (goto-char (point-min))). This
is written exactly the same way as it is written in beginning-of-buffer.
The expression moves the cursor to the minimum point in the buffer, that is,
to the beginning of the buffer (or to the beginning of the accessible portion
" 8 0)) (74 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "56
Chapter 4: A Few Buffer–Related Functions
" 0 0) (89.99887084960938 77.48908233642578 449.39886474609375 114.66727447509766 "of the buffer). As a result of this, point is placed at the beginning of the
buffer and mark is set at the end of the buffer. The whole buffer is, therefore,
the region.
" 1 0) (89.99887084960938 141.5003662109375 363.90606689453125 155.8735809326172 "4.4 The Definition of append-to-buffer
" 2 0) (89.99874877929688 166.1690673828125 449.48590087890625 215.34727478027344 "The append-to-buffer command is very nearly as simple as the mark-
whole-buffer command. What it does is copy the region (that is, the part
of the buffer between point and mark) from the current buffer to a specified
buffer.
" 3 0) (89.99859619140625 218.60906982421875 450.0857238769531 303.6672668457031 "The append-to-buffer command uses the insert-buffer-substring
function to copy the region. insert-buffer-substring is described by its
name: it takes a string of characters from part of a buffer, a “substring”, and
inserts them into another buffer. Most of append-to-buffer is concerned
with setting up the conditions for insert-buffer-substring to work: the
code must specify both the buffer to which the text will go and the region
that will be copied. Here is the complete text of the function:
" 4 0) (111.59902954101562 311.2575988769531 360.5087585449219 345.06396484375 "(defun append-to-buffer (buffer start end)
\"Append to specified buffer the text of the region.
It is inserted into that buffer before its point.
" 5 0) (111.59835815429688 353.2575988769531 388.7680358886719 449.4641418457031 "When calling from a program, give three arguments:
a buffer or the name of one, and two character numbers
specifying the portion of the current buffer to be copied.\"
(interactive \"BAppend to buffer: \\nr\")
(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
" 6 0) (89.99880981445312 453.3292236328125 449.32196044921875 478.6274108886719 "The function can be understood by looking at it as a series of filled-in
templates.
" 7 0) (89.99908447265625 481.88922119140625 449.3765869140625 507.1874084472656 "The outermost template is for the function definition. In this function,
it looks like this (with several slots filled in):
" 8 0) (111.59933471679688 514.7777709960938 308.9515075683594 561.064208984375 "(defun append-to-buffer (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
body...)
" 9 0) (89.99948120117188 565.0491943359375 449.4534912109375 602.2274169921875 "The first line of the function includes its name and three arguments. The
arguments are the buffer to which the text will be copied, and the start
and end of the region in the current buffer that will be copied.
" 10 0) (89.99887084960938 605.4892578125 449.4425354003906 630.7874755859375 "The next part of the function is the documentation, which is clear and
complete.
" 11 0)) (75 (90.0 47.60907745361328 449.6504821777344 60.90726852416992 "The Body of append-to-buffer
57
" 0 0) (89.99981689453125 78.2418212890625 413.8818054199219 91.35738372802734 "4.4.1 The append-to-buffer Interactive Expression
" 1 0) (89.99908447265625 101.60907745361328 449.7373962402344 150.7872772216797 "Since the append-to-buffer function will be used interactively, the func-
tion must have an interactive expression. (For a review of interactive,
see Section 3.3, “Making a Function Interactive”, page 33.) The expression
reads as follows:
" 2 0) (89.99609375 158.01760864257812 449.4083251953125 323.5873107910156 "(interactive \"BAppend to buffer: \\nr\")
This expression has an argument inside of quotation marks and that argu-
ment has two parts, separated by ‘\\n’.
The first part is ‘BAppend to buffer: ’. Here, the ‘B’ tells Emacs to ask
for the name of the buffer that will be passed to the function. Emacs will
ask for the name by prompting the user in the minibuffer, using the string
following the ‘B’, which is the string ‘Append to buffer: ’.
Emacs then
binds the variable buffer in the function’s argument list to the specified
buffer.
The newline, ‘\\n’, separates the first part of the argument from the second
part. It is followed by an ‘r’ that tells Emacs to bind the two arguments
that follow the symbol buffer in the function’s argument list (that is, start
and end) to the values of point and mark.
" 3 0) (89.99641418457031 343.5618591308594 321.0094909667969 356.67742919921875 "4.4.2 The Body of append-to-buffer
" 4 0) (89.99420166015625 367.0491027832031 449.4703063964844 484.3872985839844 "The body of the append-to-buffer function begins with let.
As we have seen before (see Section 3.6, “let”, page 36), the purpose of
a let expression is to create and give initial values to one or more variables
that will only be used within the body of the let. This means that such
a variable will not be confused with any variable of the same name outside
the let expression.
We can see how the let expression fits into the function as a whole
by showing a template for append-to-buffer with the let expression in
outline:
" 5 0) (111.59420013427734 491.6176452636719 308.94635009765625 550.384033203125 "(defun append-to-buffer (buffer start end)
\"documentation...\"
(interactive \"BAppend to buffer: \\nr\")
(let ((variable value))
body...)
" 6 0) (104.99437713623047 554.0091552734375 291.63775634765625 567.307373046875 "The let expression has three elements:
" 7 0) (95.87387084960938 571.1691284179688 191.51376342773438 584.4673461914062 "1. The symbol let;
" 8 0) (95.87383270263672 588.3291015625 449.2298278808594 613.6273193359375 "2. A varlist containing, in this case, a single two-element list, (variable
value);
" 9 0) (95.87357330322266 617.4891357421875 265.2915954589844 630.787353515625 "3. The body of the let expression.
" 10 0)) (76 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "58
Chapter 4: A Few Buffer–Related Functions
" 0 0) (104.9993896484375 86.24909210205078 398.3338623046875 99.54727935791016 "In the append-to-buffer function, the varlist looks like this:
" 1 0) (111.59976196289062 111.21762084960938 228.67115783691406 120.18400573730469 "(oldbuf (current-buffer))
" 2 0) (89.99960327148438 128.00909423828125 449.46478271484375 177.1873016357422 "In this part of the let expression, the one variable, oldbuf, is bound to the
value returned by the (current-buffer) expression. The variable, oldbuf,
is used to keep track of the buffer in which you are working and from which
you will copy.
" 3 0) (89.99981689453125 184.52911376953125 449.464599609375 233.7073211669922 "The element or elements of a varlist are surrounded by a set of parentheses
so the Lisp interpreter can distinguish the varlist from the body of the let.
As a consequence, the two-element list within the varlist is surrounded by a
circumscribing set of parentheses. The line looks like this:
" 4 0) (111.60049438476562 245.37765502929688 261.50067138671875 266.8240051269531 "(let ((oldbuf (current-buffer)))
... )
" 5 0) (89.99920654296875 274.88909912109375 449.2578125 324.0672912597656 "The two parentheses before oldbuf might surprise you if you did not realize
that the first parenthesis before oldbuf marks the boundary of the varlist
and the second parenthesis marks the beginning of the two-element list,
(oldbuf (current-buffer)).
" 6 0) (89.99931335449219 357.60186767578125 351.45758056640625 370.7174377441406 "4.4.3 save-excursion in append-to-buffer
" 7 0) (89.99945068359375 385.40911865234375 449.45306396484375 410.7073059082031 "The body of the let expression in append-to-buffer consists of a save-
excursion expression.
" 8 0) (89.99969482421875 418.04913330078125 449.4207763671875 479.1073303222656 "The save-excursion function saves the locations of point and mark,
and restores them to those positions after the expressions in the body of the
save-excursion complete execution. In addition, save-excursion keeps
track of the original buffer, and restores it. This is how save-excursion is
used in append-to-buffer.
" 9 0) (90.00015258789062 486.56915283203125 449.4225158691406 547.7473754882812 "Incidentally, it is worth noting here that a Lisp function is normally for-
matted so that everything that is enclosed in a multi-line spread is indented
more to the right than the first symbol. In this function definition, the let
is indented more than the defun, and the save-excursion is indented more
than the let, like this:
" 10 0) (111.60150146484375 559.417724609375 200.54954528808594 630.6640625 "(defun ...
...
...
(let...
(save-excursion
...
" 11 0)) (77 (90.0 47.60907745361328 449.57415771484375 60.90726852416992 "save-excursion in append-to-buffer
59
" 0 0) (89.99896240234375 81.68909454345703 449.3990783691406 130.74729919433594 "This formatting convention makes it easy to see that the two lines in the
body of the save-excursion are enclosed by the parentheses associated
with save-excursion, just as the save-excursion itself is enclosed by the
parentheses associated with the let:
" 1 0) (111.59886169433594 137.85763549804688 341.7973327636719 184.1439666748047 "(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
" 2 0) (89.99932861328125 188.60906982421875 449.3766174316406 213.9072723388672 "The use of the save-excursion function can be viewed as a process of
filling in the slots of a template:
" 3 0) (111.59921264648438 221.01760864257812 226.0409698486328 279.7839050292969 "(save-excursion
first-expression-in-body
second-expression-in-body
...
last-expression-in-body)
" 4 0) (89.99874877929688 284.2490234375 449.3550109863281 309.4272155761719 "In this function, the body of the save-excursion contains only two expres-
sions. The body looks like this:
" 5 0) (89.99810791015625 316.5375671386719 449.7251281738281 498.5472412109375 "(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end)
When the append-to-buffer function is evaluated, the two expressions
in the body of the save-excursion are evaluated in sequence. The value of
the last expression is returned as the value of the save-excursion function;
the other expression is evaluated only for its side effects.
The first line in the body of the save-excursion uses the set-buffer
function to change the current buffer to the one specified in the first argument
to append-to-buffer. (Changing the buffer is the side effect; as we have
said before, in Lisp, a side effect is often the primary thing we want.) The
second line does the primary work of the function.
The set-buffer function changes Emacs’ attention to the buffer to which
the text will be copied and from which save-excursion will return.
The line looks like this:
" 6 0) (89.99884033203125 505.5376281738281 449.6275634765625 630.7872924804688 "(set-buffer (get-buffer-create buffer))
The innermost expression of this list is (get-buffer-create buffer).
This expression uses the get-buffer-create function, which either gets the
named buffer, or if it does not exist, creates one with the given name. This
means you can use append-to-buffer to put text into a buffer that did not
previously exist.
get-buffer-create also keeps set-buffer from getting an unnecessary
error: set-buffer needs a buffer to go to; if you were to specify a buffer that
does not exist, Emacs would baulk. Since get-buffer-create will create a
buffer if none exists, set-buffer is always provided with a buffer.
" 7 0)) (78 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "60
Chapter 4: A Few Buffer–Related Functions
" 0 0) (104.9993896484375 81.68909454345703 449.27874755859375 94.9872817993164 "The last line of append-to-buffer does the work of appending the text:
" 1 0) (89.99887084960938 102.21762084960938 449.83551025390625 231.90733337402344 "(insert-buffer-substring oldbuf start end)
The insert-buffer-substring function copies a string from the buffer
specified as its first argument and inserts the string into the present buffer.
In this case, the argument to insert-buffer-substring is the value of the
variable created and bound by the let, namely the value of oldbuf, which
was the current buffer when you gave the append-to-buffer command.
After insert-buffer-substring has done its work, save-excursion
will restore the action to the original buffer and append-to-buffer will
have done its job.
Written in skeletal form, the workings of the body look like this:
" 2 0) (111.5992431640625 239.0152587890625 392.71527099609375 285.3039855957031 "(let (bind-oldbuf-to-value-of-current-buffer)
(save-excursion
; Keep track of buffer.
change-buffer
insert-substring-from-oldbuf-into-buffer)
" 3 0) (111.59930419921875 301.29522705078125 337.39544677734375 322.7439880371094 "change-back-to-original-buffer-when-finished
let-the-local-meaning-of-oldbuf-disappear-when-finished
" 4 0) (89.99819946289062 338.72906494140625 449.51812744140625 451.8672790527344 "In summary, append-to-buffer works as follows: it saves the value of the
current buffer in the variable called oldbuf. It gets the new buffer, creating
one if need be, and switches Emacs to it. Using the value of oldbuf, it
inserts the region of text from the old buffer into the new buffer; and then
using save-excursion, it brings you back to your original buffer.
In looking at append-to-buffer, you have explored a fairly complex
function. It shows how to use let and save-excursion, and how to change
to and come back from another buffer. Many function definitions use let,
save-excursion, and set-buffer this way.
" 5 0) (89.99848937988281 476.9003601074219 169.8894805908203 491.2608947753906 "4.5 Review
" 6 0) (104.99848937988281 501.2090759277344 449.2343444824219 514.5072631835938 "Here is a brief summary of the various functions discussed in this chapter.
" 7 0) (89.99807739257812 525.252685546875 449.2018127441406 572.5960693359375 "describe-function
describe-variable
Print the documentation for a function or variable. Convention-
ally bound to C-h f and C-h v.
" 8 0) (89.9984130859375 581.609130859375 449.4854736328125 636.6498413085938 "find-tag
Find the file containing the source for a function or variable and
switch buffers to it, positioning point at the beginning of the
item. Conventionally bound to M-. (that’s a period following
the ⟨
" 9 0) (169.30799865722656 620.8720092773438 194.62799072265625 621.3519897460938 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (169.32000732421875 622.0823974609375 194.6065216064453 630.0525512695312 "META
" 11 0) (169.30799865722656 629.3919677734375 194.62799072265625 629.8719482421875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (194.0399932861328 617.1290893554688 224.3890838623047 636.289794921875 "⟩ key).
" 13 0)) (79 (90.0 47.60907745361328 449.8256530761719 60.90726852416992 "Exercises
61
" 0 0) (90.0 79.33271789550781 449.3671569824219 126.66727447509766 "save-excursion
Save the location of point and mark and restore their values after
the arguments to save-excursion have been evaluated. Also,
remember the current buffer and return to it.
" 1 0) (89.99972534179688 133.0927276611328 449.4967346191406 192.4272918701172 "push-mark
Set mark at a location and record the value of the previous mark
on the mark ring. The mark is a location in the buffer that will
keep its relative position even if text is added to or removed
from the buffer.
" 2 0) (89.9984359741211 198.8527374267578 449.5509033203125 246.1873016357422 "goto-char
Set point to the location specified by the value of the argument,
which can be a number, a marker, or an expression that returns
the number of a position, such as (point-min).
" 3 0) (89.99832153320312 252.6127471923828 449.38671875 288.0672912597656 "insert-buffer-substring
Copy a region of text from a buffer that is passed to the function
as an argument and insert the region into the current buffer.
" 4 0) (89.99722290039062 294.49273681640625 441.1276550292969 317.95611572265625 "mark-whole-buffer
Mark the whole buffer as a region. Normally bound to C-x h.
" 5 0) (89.9969482421875 324.37274169921875 449.5276184082031 371.7073059082031 "set-buffer
Switch the attention of Emacs to another buffer, but do not
change the window being displayed. Used when the program
rather than a human is to work on a different buffer.
" 6 0) (89.99609375 378.13275146484375 449.46087646484375 437.4673156738281 "get-buffer-create
get-buffer
Find a named buffer or create one if a buffer of that name does
not exist. The get-buffer function returns nil if the named
buffer does not exist.
" 7 0) (89.99528503417969 455.660400390625 183.29995727539062 470.02093505859375 "4.6 Exercises
" 8 0) (98.99493408203125 475.7691345214844 449.3077697753906 550.6928100585938 "• Write your own simplified-end-of-buffer function definition; then
test it to see whether it works.
• Use if and get-buffer to write a function that prints a message telling
you whether a buffer exists.
• Using find-tag, find the source for the copy-to-buffer function.
" 9 0)) (80 (90.0 47.60907745361328 449.46527099609375 60.90726852416992 "62
Chapter 4: A Few Buffer–Related Functions
" 0 0)) (81 (90.0 47.60907745361328 449.6177673339844 60.90726852416992 "The Definition of copy-to-buffer
63
" 0 0) (90.0001220703125 75.14844512939453 384.7303466796875 92.38106536865234 "5 A Few More Complex Functions
" 1 0) (89.9990234375 107.36908721923828 449.5304260253906 180.4272918701172 "In this chapter, we build on what we have learned in previous chapters by
looking at more complex functions. The copy-to-buffer function illustrates
use of two save-excursion expressions in one definition, while the insert-
buffer function illustrates use of an asterisk in an interactive expression,
use of or, and the important distinction between a name and the object to
which the name refers.
" 2 0) (89.99909210205078 200.06036376953125 349.16363525390625 214.43357849121094 "5.1 The Definition of copy-to-buffer
" 3 0) (89.99795532226562 223.049072265625 449.5188903808594 322.8672790527344 "After understanding how append-to-buffer works, it is easy to under-
stand copy-to-buffer.
This function copies text into a buffer, but in-
stead of adding to the second buffer, it replaces the previous text in the
second buffer.
The code for the copy-to-buffer function is almost the
same as the code for append-to-buffer, except that erase-buffer and
a second save-excursion are used. (See Section 4.4, “The Definition of
append-to-buffer”, page 56, for the description of append-to-buffer.)
The body of copy-to-buffer looks like this
" 4 0) (89.998291015625 328.6576232910156 449.4534606933594 553.6273803710938 "...
(interactive \"BCopy to buffer: \\nr\")
(let ((oldbuf (current-buffer)))
(save-excursion
(set-buffer (get-buffer-create buffer))
(erase-buffer)
(save-excursion
(insert-buffer-substring oldbuf start end)))))
This code is similar to the code in append-to-buffer: it is only after
changing to the buffer to which the text will be copied that the definition
for this function diverges from the definition for append-to-buffer: the
copy-to-buffer function erases the buffer’s former contents. (This is what
is meant by ‘replacement’; to replace text, Emacs erases the previous text
and then inserts new text.) After erasing the previous contents of the buffer,
save-excursion is used for a second time and the new text is inserted.
Why is save-excursion used twice? Consider again what the function
does.
In outline, the body of copy-to-buffer looks like this:
" 5 0) (111.599365234375 559.415283203125 368.859130859375 630.6640625 "(let (bind-oldbuf-to-value-of-current-buffer)
(save-excursion
; First use of save-excursion.
change-buffer
(erase-buffer)
(save-excursion
; Second use of save-excursion.
insert-substring-from-oldbuf-into-buffer)))
" 6 0)) (82 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "64
Chapter 5: A Few More Complex Functions
" 0 0) (89.99850463867188 77.48908233642578 449.857421875 198.3072967529297 "The first use of save-excursion returns Emacs to the buffer from which
the text is being copied. That is clear, and is just like its use in append-
to-buffer.
Why the second use?
The reason is that insert-buffer-
substring always leaves point at the end of the region being inserted. The
second save-excursion causes Emacs to leave point at the beginning of the
text being inserted. In most circumstances, users prefer to find point at the
beginning of inserted text. (Of course, the copy-to-buffer function returns
the user to the original buffer when done—but if the user then switches to
the copied-to buffer, point will go to the beginning of the text. Thus, this
use of a second save-excursion is a little nicety.)
" 1 0) (89.99812316894531 224.06036376953125 341.7313537597656 238.43357849121094 "5.2 The Definition of insert-buffer
" 2 0) (89.9962158203125 248.48907470703125 449.5498352050781 337.8672790527344 "insert-buffer is yet another buffer-related function.
This command
copies another buffer into the current buffer. It is the reverse of append-
to-buffer or copy-to-buffer, since they copy a region of text from the
current buffer to another buffer.
In addition, this code illustrates the use of interactive with a buffer
that might be read-only and the important distinction between the name of
an object and the object actually referred to.
" 3 0) (104.99609375 341.00909423828125 184.80690002441406 354.3072814941406 "Here is the code:
" 4 0) (111.59607696533203 361.6576232910156 341.5971374511719 547.0241088867188 "(defun insert-buffer (buffer)
\"Insert after point the contents of BUFFER.
Puts mark after the inserted text.
BUFFER may be a buffer or a buffer name.\"
(interactive \"*bInsert buffer: \")
(or (bufferp buffer)
(setq buffer (get-buffer buffer)))
(let (start end newmark)
(save-excursion
(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
(insert-buffer-substring buffer start end)
(setq newmark (point)))
(push-mark newmark)))
" 5 0) (89.99786376953125 551.7291259765625 449.3534240722656 577.02734375 "As with other function definitions, you can use a template to see an
outline of the function:
" 6 0) (111.59786987304688 584.2577514648438 276.1382141113281 630.6640625 "(defun insert-buffer (buffer)
\"documentation...\"
(interactive \"*bInsert buffer: \")
body...)
" 7 0)) (83 (90.0 47.60907745361328 449.5639343261719 60.90726852416992 "The Body of the insert-buffer Function
65
" 0 0) (90.00027465820312 78.2418212890625 410.762451171875 91.35738372802734 "5.2.1 The Interactive Expression in insert-buffer
" 1 0) (89.99972534179688 101.48908233642578 449.36712646484375 126.78726959228516 "In insert-buffer, the argument to the interactive declaration has
two parts, an asterisk, ‘*’, and ‘bInsert buffer: ’.
" 2 0) (89.99920654296875 146.40179443359375 216.149658203125 159.5057830810547 "A Read-only Buffer
" 3 0) (89.99893188476562 169.6490478515625 449.48577880859375 242.82725524902344 "The asterisk is for the situation when the buffer is a read-only buffer—
a buffer that cannot be modified. If insert-buffer is called on a buffer
that is read-only, a message to this effect is printed in the echo area and
the terminal may beep or blink at you; you will not be permitted to insert
anything into current buffer. The asterisk does not need to be followed by a
newline to separate it from the next argument.
" 4 0) (89.99984741210938 262.4417724609375 290.81427001953125 275.5573425292969 "‘b’ in an Interactive Expression
" 5 0) (89.998291015625 285.68902587890625 449.85748291015625 406.6272277832031 "The next argument in the interactive expression starts with a lower case
‘b’. (This is different from the code for append-to-buffer, which uses an
upper-case ‘B’.
See Section 4.4, “The Definition of append-to-buffer”,
page 56.) The lower-case ‘b’ tells the Lisp interpreter that the argument for
insert-buffer should be an existing buffer or else its name. (The upper-
case ‘B’ option provides for the possibility that the buffer does not exist.)
Emacs will prompt you for the name of the buffer, offering you a default
buffer, with name completion enabled.
If the buffer does not exist, you
receive a message that says “No match”; your terminal may beep at you as
well.
" 6 0) (89.998291015625 426.3617858886719 387.6724853515625 439.47735595703125 "5.2.2 The Body of the insert-buffer Function
" 7 0) (89.997802734375 449.6090393066406 449.5071105957031 538.8673095703125 "The body of the insert-buffer function has two major parts: an or
expression and a let expression. The purpose of the or expression is to
ensure that the argument buffer is bound to a buffer and not just the name
of a buffer. The body of the let expression contains the code which copies
the other buffer into the current buffer.
In outline, the two expressions fit into the insert-buffer function like
this:
" 8 0) (111.59844207763672 545.8576049804688 276.1387634277344 630.6640014648438 "(defun insert-buffer (buffer)
\"documentation...\"
(interactive \"*bInsert buffer: \")
(or ...
...
(let (varlist)
body-of-let... )
" 9 0)) (84 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "66
Chapter 5: A Few More Complex Functions
" 0 0) (89.99993896484375 77.48908233642578 449.58526611328125 141.0673065185547 "To understand how the or expression ensures that the argument buffer
is bound to a buffer and not to the name of a buffer, it is first necessary to
understand the or function.
Before doing this, let me rewrite this part of the function using if so that
you can see what is done in a manner that will be familiar.
" 1 0) (89.99993896484375 156.0018310546875 399.27911376953125 169.1173858642578 "5.2.3 insert-buffer With an if Instead of an or
" 2 0) (89.99954223632812 177.6890869140625 449.4432678222656 279.7873229980469 "The job to be done is to make sure the value of buffer is a buffer itself
and not the name of a buffer. If the value is the name, then the buffer itself
must be got.
You can imagine yourself at a conference where an usher is wandering
around holding a list with your name on it and looking for you: the usher is
“bound” to your name, not to you; but when the usher finds you and takes
your arm, the usher becomes “bound” to you.
In Lisp, you might describe this situation like this:
" 3 0) (90.00009155273438 285.2176818847656 449.4981994628906 360.3073425292969 "(if (not (holding-on-to-guest))
(find-and-take-arm-of-guest))
We want to do the same thing with a buffer—if we do not have the buffer
itself, we want to get it.
Using a predicate called bufferp that tells us whether we have a buffer
(rather than its name), we can write the code like this:
" 4 0) (90.00030517578125 365.85528564453125 449.466064453125 527.107421875 "(if (not (bufferp buffer))
; if-part
(setq buffer (get-buffer buffer)))
; then-part
Here, the true-or-false-test of the if expression is (not (bufferp buffer));
and the then-part is the expression (setq buffer (get-buffer buffer)).
In the test, the function bufferp returns true if its argument is a buffer—
but false if its argument is the name of the buffer. (The last character of
the function name bufferp is the character ‘p’; as we saw earlier, such use
of ‘p’ is a convention that indicates that the function is a predicate, which is
a term that means that the function will determine whether some property
is true or false. See Section 1.8.4, “Using the Wrong Type Object as an
Argument”, page 14.)
The function not precedes the expression (bufferp buffer), so the true-
or-false-test looks like this:
" 5 0) (89.99822998046875 532.6577758789062 449.35491943359375 630.7874145507812 "(not (bufferp buffer))
not is a function that returns true if its argument is false and false if its
argument is true. So if (bufferp buffer) returns true, the not expression
returns false and vice-versa: what is “not true” is false and what is “not
false” is true.
Using this test, the if expression works as follows: when the value of
the variable buffer is actually a buffer rather then its name, the true-or-
false-test returns false and the if expression does not evaluate the then-part.
" 6 0)) (85 (90.0 47.60907745361328 449.7704772949219 60.90726852416992 "The or in the Body
67
" 0 0) (89.999755859375 77.48908233642578 449.2685241699219 102.66727447509766 "This is fine, since we do not need to do anything to the variable buffer if it
really is a buffer.
" 1 0) (89.99874877929688 108.68909454345703 449.5626525878906 193.74729919433594 "On the other hand, when the value of buffer is not a buffer itself, but
the name of a buffer, the true-or-false-test returns true and the then-part
of the expression is evaluated. In this case, the then-part is (setq buffer
(get-buffer buffer)). This expression uses the get-buffer function to
return an actual buffer itself, given its name. The setq then sets the variable
buffer to the value of the buffer itself, replacing its previous value (which
was the name of the buffer).
" 2 0) (89.9990234375 222.96185302734375 252.7234344482422 236.07740783691406 "5.2.4 The or in the Body
" 3 0) (89.99700927734375 249.4490966796875 449.4409484863281 310.6272888183594 "The purpose of the or expression in the insert-buffer function is to
ensure that the argument buffer is bound to a buffer and not just to the
name of a buffer. The previous section shows how the job could have been
done using an if expression. However, the insert-buffer function actually
uses or. To understand this, it is necessary to understand how or works.
" 4 0) (89.99600219726562 316.52911376953125 449.34100341796875 365.7073059082031 "An or function can have any number of arguments. It evaluates each
argument in turn and returns the value of the first of its arguments that is
not nil. Also, and this is a crucial feature of or, it does not evaluate any
subsequent arguments after returning the first non-nil value.
" 5 0) (104.99609375 371.84912109375 263.3631896972656 385.1473083496094 "The or expression looks like this:
" 6 0) (111.59611511230469 395.3776550292969 290.0478820800781 416.82403564453125 "(or (bufferp buffer)
(setq buffer (get-buffer buffer)))
" 7 0) (89.99453735351562 423.5691223144531 449.4162902832031 496.6273193359375 "The first argument to or is the expression (bufferp buffer). This expres-
sion returns true (a non-nil value) if the buffer is actually a buffer, and
not just the name of a buffer.
In the or expression, if this is the case,
the or expression returns this true value and does not evaluate the next
expression—and this is fine with us, since we do not want to do anything to
the value of buffer if it really is a buffer.
" 8 0) (89.99395751953125 502.5291748046875 449.535888671875 575.58740234375 "On the other hand, if the value of (bufferp buffer) is nil, which it will
be if the value of buffer is the name of a buffer, the Lisp interpreter evaluates
the next element of the or expression. This is the expression (setq buffer
(get-buffer buffer)). This expression returns a non-nil value, which is
the value to which it sets the variable buffer—and this value is a buffer
itself, not the name of a buffer.
" 9 0) (89.99322509765625 581.609130859375 449.42596435546875 630.787353515625 "The result of all this is that the symbol buffer is always bound to a buffer
itself rather than to the name of a buffer. All this is necessary because the
set-buffer function in a following line only works with a buffer itself, not
with the name to a buffer.
" 10 0)) (86 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "68
Chapter 5: A Few More Complex Functions
" 0 0) (90.00039672851562 80.48908233642578 449.2470397949219 105.66727447509766 "Incidentally, using or, the situation with the usher would be written like
this:
" 1 0) (111.60039520263672 111.57760620117188 369.3045349121094 120.54399108886719 "(or (holding-on-to-guest) (find-and-take-arm-of-guest))
" 2 0) (89.99978637695312 137.16180419921875 361.75616455078125 150.27735900878906 "5.2.5 The let Expression in insert-buffer
" 3 0) (89.99856567382812 159.20904541015625 449.4969787597656 271.1472473144531 "After ensuring that the variable buffer refers to a buffer itself and not
just to the name of a buffer, the insert-buffer function continues with a
let expression. This specifies three local variables, start, end, and newmark
and binds them to the initial value nil. These variables are used inside the
remainder of the let and temporarily hide any other occurrence of variables
of the same name in Emacs until the end of the let.
The body of the let contains two save-excursion expressions. First, we
will look at the inner save-excursion expression in detail. The expression
looks like this:
" 4 0) (89.99755859375 277.0575866699219 449.5391845703125 463.8672180175781 "(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
The expression (set-buffer buffer) changes Emacs’ attention from the
current buffer to the one from which the text will copied. In that buffer,
the variables start and end are set to the beginning and end of the buffer,
using the commands point-min and point-max. Note that we have here an
illustration of how setq is able to set two variables in the same expression.
The first argument of setq is set to the value of its second, and its third
argument is set to the value of its fourth.
After the body of the inner save-excursion is evaluated, the save-
excursion restores the original buffer, but start and end remain set to the
values of the beginning and end of the buffer from which the text will be
copied.
The outer save-excursion expression looks like this:
" 5 0) (89.99526977539062 469.7775573730469 449.42938232421875 630.7872314453125 "(save-excursion
(inner-save-excursion-expression
(go-to-new-buffer-and-set-start-and-end)
(insert-buffer-substring buffer start end)
(setq newmark (point)))
The insert-buffer-substring function copies the text into the current
buffer from the region indicated by start and end in buffer. Since the
whole of the second buffer lies between start and end, the whole of the
second buffer is copied into the buffer you are editing. Next, the value of
point, which will be at the end of the inserted text, is recorded in the variable
newmark.
After the body of the outer save-excursion is evaluated, point and mark
are relocated to their original places.
" 6 0)) (87 (90.0 47.60907745361328 449.73797607421875 60.90726852416992 "Optional Arguments
69
" 0 0) (89.9996337890625 77.48908233642578 449.650146484375 156.0497589111328 "However, it is convenient to locate a mark at the end of the newly inserted
text and locate point at its beginning. The newmark variable records the end
of the inserted text. In the last line of the let expression, the (push-mark
newmark) expression function sets a mark to this location. (The previous
location of the mark is still accessible; it is recorded on the mark ring and
you can go back to it with C-u C-⟨
" 1 0) (254.8679962158203 140.6319580078125 271.5480041503906 141.11195373535156 "<image: None, width: 1, height: 1, bpc: 1>" 2 1) (254.8800048828125 141.84242248535156 271.42596435546875 149.81253051757812 "SPC
" 3 0) (254.8679962158203 149.1519775390625 271.5480041503906 149.63197326660156 "<image: None, width: 1, height: 1, bpc: 1>" 4 1) (90.00015258789062 137.2491455078125 449.7162170410156 174.42735290527344 "⟩.) Meanwhile, point is located at the
beginning of the inserted text, which is where it was before you called the
insert function.
" 5 0) (105.00015258789062 180.80914306640625 299.9017028808594 194.1073455810547 "The whole let expression looks like this:
" 6 0) (111.599609375 204.57766723632812 332.24017333984375 300.7839050292969 "(let (start end newmark)
(save-excursion
(save-excursion
(set-buffer buffer)
(setq start (point-min) end (point-max)))
(insert-buffer-substring buffer start end)
(setq newmark (point)))
(push-mark newmark))
" 7 0) (90.00018310546875 307.64898681640625 449.41094970703125 356.8271789550781 "Like the append-to-buffer function, the insert-buffer function uses
let, save-excursion, and set-buffer. In addition, the function illustrates
one way to use or. All these functions are building blocks that we will find
and use again and again.
" 8 0) (90.00017547607422 395.4202880859375 426.1179504394531 409.79351806640625 "5.3 Complete Definition of beginning-of-buffer
" 9 0) (90.00003051757812 423.0890197753906 449.3235778808594 460.2672119140625 "The basic structure of the beginning-of-buffer function has already
been discussed. (See Section 4.2, “A Simplified beginning-of-buffer Def-
inition”, page 52.) This section describes the complex part of the definition.
" 10 0) (89.99850463867188 466.4090270996094 449.6725769042969 599.3472900390625 "As previously described, when invoked without an argument, beginning-
of-buffer moves the cursor to the beginning of the buffer, leaving the mark
at the previous position. However, when the command is invoked with a
number between one and ten, the function considers that number to be a
fraction of the length of the buffer, measured in tenths, and Emacs moves
the cursor that fraction of the way from the beginning of the buffer. Thus,
you can either call this function with the key command M-<, which will move
the cursor to the beginning of the buffer, or with a key command such as
C-u 7 M-< which will move the cursor to a point 70% of the way through the
buffer. If a number bigger than ten is used for the argument, it moves to
the end of the buffer.
" 11 0) (89.99862670898438 605.489013671875 449.34417724609375 630.7872314453125 "The beginning-of-buffer function can be called with or without an
argument. The use of the argument is optional.
" 12 0)) (88 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "70
Chapter 5: A Few More Complex Functions
" 0 0) (90.00021362304688 78.2418212890625 259.23736572265625 91.34580993652344 "5.3.1 Optional Arguments
" 1 0) (89.9998779296875 104.12909698486328 449.5845642089844 153.3072967529297 "Unless told otherwise, Lisp expects that a function with an argument in
its function definition will be called with a value for that argument. If that
does not happen, you get an error and a message that says ‘Wrong number
of arguments’.
" 2 0) (89.99942016601562 158.60906982421875 449.5632629394531 219.7872772216797 "However, optional arguments are a feature of Lisp: a keyword may be
used to tell the Lisp interpreter that an argument is optional. The keyword
is &optional. (The ‘&’ in front of ‘optional’ is part of the keyword.) In a
function definition, if an argument follows the keyword &optional, a value
does not need to be passed to that argument when the function is called.
" 3 0) (90.00006103515625 225.20904541015625 449.2474060058594 250.5072479248047 "The first line of the function definition of beginning-of-buffer therefore
looks like this:
" 4 0) (111.60009002685547 260.1376037597656 308.9436340332031 269.1039733886719 "(defun beginning-of-buffer (&optional arg)
" 5 0) (104.99986267089844 275.12908935546875 318.5670166015625 288.4272766113281 "In outline, the whole function looks like this:
" 6 0) (111.59992980957031 298.0576477050781 308.9434814453125 406.6239929199219 "(defun beginning-of-buffer (&optional arg)
\"documentation...\"
(interactive \"P\")
(push-mark)
(goto-char
(if-there-is-an-argument
figure-out-where-to-go
else-go-to
(point-min))))
" 7 0) (89.99911499023438 412.7690734863281 449.50860595703125 461.947265625 "The function is similar to the simplified-beginning-of-buffer func-
tion except that the interactive expression has \"P\" as an argument and
the goto-char function is followed by an if-then-else expression that figures
out where to put the cursor if there is an argument.
" 8 0) (89.9998779296875 467.24908447265625 449.541259765625 510.4097900390625 "The \"P\" in the interactive expression tells Emacs to pass a prefix
argument, if there is one, to the function. A prefix argument is made by
typing the ⟨
" 9 0) (146.86801147460938 494.6319885253906 172.18801879882812 495.11199951171875 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (146.8800048828125 495.8424377441406 172.16651916503906 503.8125305175781 "META
" 11 0) (146.86801147460938 503.1520080566406 172.18801879882812 503.63201904296875 "<image: None, width: 1, height: 1, bpc: 1>" 12 1) (90.00054931640625 490.8890686035156 449.60711669921875 516.4360961914062 "⟩ key followed by a number, or by typing C-u and then a
number (if you don’t type a number, C-u defaults to 4).
" 13 0) (89.99868774414062 521.84912109375 449.5188293457031 630.787353515625 "The true-or-false-test of the if expression is simple: it is simply the
argument arg. If arg has a value that is not nil, which will be the case if
beginning-of-buffer is called with an argument, then this true-or-false-
test will return true and the then-part of the if expression will be evaluated.
On the other hand, if beginning-of-buffer is not called with an argument,
the value of arg will be nil and the else-part of the if expression will be
evaluated. The else-part is simply point-min, and when this is the outcome,
the whole goto-char expression is (goto-char (point-min)), which is how
we saw the beginning-of-buffer function in its simplified form.
" 14 0)) (89 (90.0 47.60907745361328 449.6610107421875 60.90726852416992 "What happens in a large buffer
71
" 0 0) (89.99935913085938 78.2418212890625 379.2123718261719 91.35738372802734 "5.3.2 beginning-of-buffer with an Argument
" 1 0) (89.99972534179688 100.16907501220703 449.3883972167969 149.34727478027344 "When beginning-of-buffer is called with an argument, an expression is
evaluated which calculates what value to pass to goto-char. This expression
is rather complicated at first sight. It includes an inner if expression and
much arithmetic. It looks like this:
" 2 0) (90.0003662109375 155.13754272460938 449.4223937988281 290.2270812988281 "(if (> (buffer-size) 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg) (/ (buffer-size) 10))
(/
(+ 10
(*
(buffer-size) (prefix-numeric-value arg))) 10))
Like other complex-looking expressions, the conditional expression within
beginning-of-buffer can be disentangled by looking at it as parts of a
template, in this case, the template for an if-then-else expression. In skeletal
form, the expression looks like this:
" 3 0) (90.00009155273438 296.01495361328125 449.466796875 443.8271179199219 "(if (buffer-is-large
divide-buffer-size-by-10-and-multiply-by-arg
else-use-alternate-calculation
The true-or-false-test of this inner if expression checks the size of the
buffer. The reason for this is that the old Version 18 Emacs used numbers
that are no bigger than eight million or so and in the computation that
followed, the programmer feared that Emacs might try to use over-large
numbers if the buffer were large.
The term ‘overflow’, mentioned in the
comment, means numbers that are over large. Version 21 Emacs uses larger
numbers, but this code has not been touched, if only because people now
look at buffers that are far, far larger than ever before.
There are two cases: if the buffer is large and if it is not.
" 4 0) (90.00003051757812 459.481689453125 291.9230041503906 472.585693359375 "What happens in a large buffer
" 5 0) (90.0006103515625 481.5289306640625 449.33489990234375 533.587158203125 "In beginning-of-buffer, the inner if expression tests whether the size
of the buffer is greater than 10,000 characters. To do this, it uses the >
function and the buffer-size function.
The line looks like this:
" 6 0) (89.99990844726562 539.3775024414062 449.3666687011719 575.587158203125 "(if (> (buffer-size) 10000)
When the buffer is large, the then-part of the if expression is evaluated. It
reads like this (after formatting for easy reading):
" 7 0) (89.9999771118164 581.3775024414062 442.1563720703125 630.7871704101562 "(*
(prefix-numeric-value arg)
(/ (buffer-size) 10))
This expression is a multiplication, with two arguments to the function *.
" 8 0)) (90 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "72
Chapter 5: A Few More Complex Functions
" 0 0) (89.9993896484375 77.48908233642578 449.4656066894531 138.5472869873047 "The first argument is (prefix-numeric-value arg). When \"P\" is used
as the argument for interactive, the value passed to the function as its
argument is passed a “raw prefix argument”, and not a number. (It is a
number in a list.) To perform the arithmetic, a conversion is necessary, and
prefix-numeric-value does the job.
" 1 0) (89.99932861328125 143.12908935546875 449.3666076660156 192.3072967529297 "The second argument is (/ (buffer-size) 10). This expression divides
the numeric value of the buffer by ten. This produces a number that tells
how many characters make up one tenth of the buffer size. (In Lisp, / is
used for division, just as * is used for multiplication.)
" 2 0) (89.99911499023438 196.88909912109375 449.3331298828125 222.0673065185547 "In the multiplication expression as a whole, this amount is multiplied by
the value of the prefix argument—the multiplication looks like this:
" 3 0) (111.59896850585938 230.9752197265625 320.8189697265625 252.4239959716797 "(* numeric-value-of-prefix-arg
number-of-characters-in-one-tenth-of-the-buffer)
" 4 0) (89.99862670898438 257.60906982421875 449.3546142578125 282.9072570800781 "If, for example, the prefix argument is ‘7’, the one-tenth value will be mul-
tiplied by 7 to give a position 70% of the way through the buffer.
" 5 0) (89.998291015625 287.48907470703125 449.2565612792969 312.6672668457031 "The result of all this is that if the buffer is large, the goto-char expression
reads like this:
" 6 0) (111.59825897216797 321.5777282714844 299.4787292480469 343.02410888671875 "(goto-char (* (prefix-numeric-value arg)
(/ (buffer-size) 10)))
" 7 0) (104.99807739257812 348.2091979980469 289.9832458496094 361.50738525390625 "This puts the cursor where we want it.
" 8 0) (89.99833679199219 386.4019470214844 294.0572814941406 399.5059509277344 "What happens in a small buffer
" 9 0) (89.99761962890625 411.4491882324219 449.4306335449219 472.50738525390625 "If the buffer contains fewer than 10,000 characters, a slightly different
computation is performed.
You might think this is not necessary, since
the first computation could do the job.
However, in a small buffer, the
first method may not put the cursor on exactly the desired line; the second
method does a better job.
" 10 0) (104.99754333496094 477.2091979980469 220.85206604003906 490.50738525390625 "The code looks like this:
" 11 0) (111.59766387939453 499.2977294921875 388.8701477050781 508.26409912109375 "(/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
" 12 0) (89.9962158203125 513.3292236328125 449.4185485839844 550.5074462890625 "This is code in which you figure out what happens by discovering how the
functions are embedded in parentheses. It is easier to read if you reformat
it with each expression indented more deeply than its enclosing expression:
" 13 0) (120.95587158203125 559.4177856445312 276.04156494140625 630.6641845703125 "(/
(+ 10
(*
(buffer-size)
(prefix-numeric-value arg)))
10))
" 14 0)) (91 (90.0 47.60907745361328 449.5965576171875 60.90726852416992 "The Complete beginning-of-buffer
73
" 0 0) (89.99990844726562 80.00910186767578 449.55206298828125 117.18729400634766 "Looking at parentheses, we see that the innermost operation is (prefix-
numeric-value arg), which converts the raw argument to a number. This
number is multiplied by the buffer size in the following expression:
" 1 0) (89.99945068359375 122.61764526367188 449.4430847167969 220.7473602294922 "(* (buffer-size) (prefix-numeric-value arg)
This multiplication creates a number that may be larger than the size of
the buffer—seven times larger if the argument is 7, for example.
Ten is
then added to this number and finally the large number is divided by ten to
provide a value that is one character larger than the percentage position in
the buffer.
The number that results from all this is passed to goto-char and the
cursor is moved to that point.
" 2 0) (90.000244140625 235.44189453125 351.8075256347656 248.5574493408203 "5.3.3 The Complete beginning-of-buffer
" 3 0) (105.00023651123047 257.129150390625 414.5348205566406 270.4273376464844 "Here is the complete text of the beginning-of-buffer function:
" 4 0) (111.59982299804688 275.8576965332031 323.009033203125 396.9041748046875 "(defun beginning-of-buffer (&optional arg)
\"Move point to the beginning of the buffer;
leave mark at previous position.
With arg N, put point N/10 of the way
from the true beginning.
Don’t use this in Lisp programs!
\\(goto-char (point-min)) is faster
and does not set the mark.\"
(interactive \"P\")
(push-mark)
" 5 0) (120.96048736572266 401.497802734375 323.555908203125 472.6241760253906 "(goto-char
(if arg
(if (> (buffer-size) 10000)
;; Avoid overflow for large buffer sizes!
(* (prefix-numeric-value arg)
(/ (buffer-size) 10))
" 6 0) (90.00030517578125 477.2178039550781 449.400146484375 589.5075073242188 "(/ (+ 10 (* (buffer-size)
(prefix-numeric-value arg)))
10))
(point-min)))
(if arg (forward-line 1)))
Except for two small points, the previous discussion shows how this function
works. The first point deals with a detail in the documentation string, and
the second point concerns the last line of the function.
In the documentation string, there is reference to an expression:
" 7 0) (90.00033569335938 594.9378662109375 449.37799072265625 630.7875366210938 "\\(goto-char (point-min))
A ‘\\\\u2019 is used before the first parenthesis of this expression. This ‘\\\\u2019 tells
the Lisp interpreter that the expression should be printed as shown in the
" 8 0)) (92 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "74
Chapter 5: A Few More Complex Functions
" 0 0) (90.00021362304688 77.48908233642578 449.34564208984375 141.5472869873047 "documentation rather than evaluated as a symbolic expression, which is what
it looks like.
Finally, the last line of the beginning-of-buffer command says to move
point to the beginning of the next line if the command is invoked with an
argument:
" 1 0) (90.00003051757812 147.45761108398438 449.4874267578125 219.4272918701172 "(if arg (forward-line 1)))
This puts the cursor at the beginning of the first line after the appropriate
tenths position in the buffer. This is a flourish that means that the cursor is
always located at least the requested tenths of the way through the buffer,
which is a nicety that is, perhaps, not necessary, but which, if it did not
occur, would be sure to draw complaints.
" 2 0) (89.99974060058594 239.30035400390625 169.89073181152344 253.660888671875 "5.4 Review
" 3 0) (104.99974060058594 262.2890625 437.1813049316406 275.5872497558594 "Here is a brief summary of some of the topics covered in this chapter.
" 4 0) (90.00003051757812 281.96905517578125 449.48760986328125 343.0272521972656 "or
Evaluate each argument in sequence, and return the value of
the first argument that is not nil; if none return a value that
is not nil, return nil. In brief, return the first true value of
the arguments; return a true value if one or any of the other are
true.
" 5 0) (90.00080108642578 349.4090576171875 449.5203552246094 398.5872497558594 "and
Evaluate each argument in sequence, and if any are nil, return
nil; if none are nil, return the value of the last argument. In
brief, return a true value only if all the arguments are true;
return a true value if one and each of the others is true.
" 6 0) (90.00076293945312 406.81268310546875 449.488037109375 454.1472473144531 "&optional
A keyword used to indicate that an argument to a function defi-
nition is optional; this means that the function can be evaluated
without the argument, if desired.
" 7 0) (90.00105285644531 462.252685546875 449.7936706542969 497.7072448730469 "prefix-numeric-value
Convert the ‘raw prefix argument’ produced by (interactive
\"P\") to a numeric value.
" 8 0) (90.00175476074219 505.81268310546875 449.7944641113281 577.0272827148438 "forward-line
Move point forward to the beginning of the next line, or if the
argument is greater than one, forward that many lines.
If it
can’t move as far forward as it is supposed to, forward-line
goes forward as far as it can and then returns a count of the
number of additional lines it was supposed to move but couldn’t.
" 9 0) (90.00173950195312 585.252685546875 373.3979187011719 608.707275390625 "erase-buffer
Delete the entire contents of the current buffer.
" 10 0) (90.00173950195312 615.0890502929688 424.12506103515625 628.3872680664062 "bufferp
Return t if its argument is a buffer; otherwise return nil.
" 11 0)) (93 (90.0 47.60907745361328 449.6620178222656 60.90726852416992 "optional Argument Exercise
75
" 0 0) (90.0003662109375 77.30034637451172 318.1007385253906 91.67356872558594 "5.5 optional Argument Exercise
" 1 0) (90.000244140625 99.32910919189453 449.43304443359375 148.50730895996094 "Write an interactive function with an optional argument that tests
whether its argument, a number, is greater or less than the value of fill-
column, and tells you which, in a message. However, if you do not pass an
argument to the function, use 56 as a default value.
" 2 0)) (94 (90.0 47.60907745361328 449.4870910644531 60.90726852416992 "76
Chapter 5: A Few More Complex Functions
" 0 0)) (95 (90.0 47.60907745361328 449.5958557128906 60.90726852416992 "The save-restriction Special Form
77
" 0 0) (89.99920654296875 75.14844512939453 324.1742858886719 92.38106536865234 "6 Narrowing and Widening
" 1 0) (89.9981689453125 117.92908477783203 449.35504150390625 155.10728454589844 "Narrowing is a feature of Emacs that makes it possible for you to focus
on a specific part of a buffer, and work without accidentally changing other
parts. Narrowing is normally disabled since it can confuse novices.
" 2 0) (89.99758911132812 158.72906494140625 449.4089660644531 255.67608642578125 "With narrowing, the rest of a buffer is made invisible, as if it weren’t
there. This is an advantage if, for example, you want to replace a word in
one part of a buffer but not in another: you narrow to the part you want
and the replacement is carried out only in that section, not in the rest of
the buffer. Searches will only work within a narrowed region, not outside of
one, so if you are fixing a part of a document, you can keep yourself from
accidentally finding parts you do not need to fix by narrowing just to the
region you want. (The key binding for narrow-to-region is C-x n n.)
" 3 0) (89.99505615234375 259.2890625 449.5495300292969 344.3560791015625 "However, narrowing does make the rest of the buffer invisible, which can
scare people who inadvertently invoke narrowing and think they have deleted
a part of their file. Moreover, the undo command (which is usually bound
to C-x u) does not turn off narrowing (nor should it), so people can become
quite desperate if they do not know that they can return the rest of a buffer
to visibility with the widen command. (The key binding for widen is C-x n
w.)
" 4 0) (89.99188232421875 347.84906005859375 449.5561218261719 456.7872619628906 "Narrowing is just as useful to the Lisp interpreter as to a human. Often,
an Emacs Lisp function is designed to work on just part of a buffer; or
conversely, an Emacs Lisp function needs to work on all of a buffer that
has been narrowed.
The what-line function, for example, removes the
narrowing from a buffer, if it has any narrowing and when it has finished its
job, restores the narrowing to what it was. On the other hand, the count-
lines function, which is called by what-line, uses narrowing to restrict
itself to just that portion of the buffer in which it is interested and then
restores the previous situation.
" 5 0) (89.99147033691406 484.8203430175781 366.9673156738281 499.1935729980469 "6.1 The save-restriction Special Form
" 6 0) (89.99102783203125 509.84906005859375 449.4242248535156 630.7872924804688 "In Emacs Lisp, you can use the save-restriction special form to keep
track of whatever narrowing is in effect, if any. When the Lisp interpreter
meets with save-restriction, it executes the code in the body of the save-
restriction expression, and then undoes any changes to narrowing that the
code caused. If, for example, the buffer is narrowed and the code that follows
save-restriction gets rid of the narrowing, save-restriction returns the
buffer to its narrowed region afterwards. In the what-line command, any
narrowing the buffer may have is undone by the widen command that im-
mediately follows the save-restriction command. Any original narrowing
is restored just before the completion of the function.
" 7 0)) (96 (90.0 47.60907745361328 449.7270202636719 60.90726852416992 "78
Chapter 6: Narrowing and Widening
" 0 0) (104.999755859375 80.60907745361328 390.3377380371094 93.90726470947266 "The template for a save-restriction expression is simple:
" 1 0) (89.99880981445312 99.81759643554688 449.5189208984375 223.6272430419922 "(save-restriction
body... )
The body of the save-restriction is one or more expressions that will be
evaluated in sequence by the Lisp interpreter.
Finally, a point to note: when you use both save-excursion and save-
restriction, one right after the other, you should use save-excursion out-
ermost. If you write them in reverse order, you may fail to record narrowing
in the buffer to which Emacs switches after calling save-excursion. Thus,
when written together, save-excursion and save-restriction should be
written like this:
" 2 0) (89.99862670898438 229.53756713867188 449.7917785644531 318.0671691894531 "(save-excursion
(save-restriction
body...))
In other circumstances, when not written together, the save-excursion
and save-restriction special forms must be written in the order appro-
priate to the function.
For example,
" 3 0) (120.95866394042969 323.9776306152344 200.5467071533203 370.384033203125 "(save-restriction
(widen)
(save-excursion
body...))
" 4 0) (89.99861145019531 389.42041015625 185.49827575683594 403.79364013671875 "6.2 what-line
" 5 0) (89.99871826171875 412.5291442871094 449.74725341796875 449.70733642578125 "The what-line command tells you the number of the line in which the
cursor is located. The function illustrates the use of the save-restriction
and save-excursion commands. Here is the text of the function in full:
" 6 0) (89.99655151367188 455.7377014160156 449.4836730957031 630.7874145507812 "(defun what-line ()
\"Print the current line number (in the buffer) of point.\"
(interactive)
(save-restriction
(widen)
(save-excursion
(beginning-of-line)
(message \"Line %d\"
(1+ (count-lines 1 (point)))))))
The function has a documentation line and is interactive, as you would
expect. The next two lines use the functions save-restriction and widen.
The save-restriction special form notes whatever narrowing is in ef-
fect, if any, in the current buffer and restores that narrowing after the code
in the body of the save-restriction has been evaluated.
" 7 0)) (97 (90.0 47.60907745361328 449.6940612792969 60.90726852416992 "Exercise with Narrowing
79
" 0 0) (89.99636840820312 77.48908233642578 449.9323425292969 288.1872253417969 "The save-restriction special form is followed by widen. This function
undoes any narrowing the current buffer may have had when what-line
was called.
(The narrowing that was there is the narrowing that save-
restriction remembers.)
This widening makes it possible for the line
counting commands to count from the beginning of the buffer. Otherwise,
they would have been limited to counting within the accessible region. Any
original narrowing is restored just before the completion of the function by
the save-restriction special form.
The call to widen is followed by save-excursion, which saves the loca-
tion of the cursor (i.e., of point) and of the mark, and restores them after
the code in the body of the save-excursion uses the beginning-of-line
function to move point.
(Note that the (widen) expression comes between the save-restriction
and save-excursion special forms.
When you write the two save- ...
expressions in sequence, write save-excursion outermost.)
The last two lines of the what-line function are functions to count the
number of lines in the buffer and then print the number in the echo area.
" 1 0) (89.99569702148438 293.1376037597656 449.43963623046875 403.02734375 "(message \"Line %d\"
(1+ (count-lines 1 (point)))))))
The message function prints a one-line message at the bottom of the
Emacs screen. The first argument is inside of quotation marks and is printed
as a string of characters. However, it may contain ‘%d’, ‘%s’, or ‘%c’ to print
arguments that follow the string. ‘%d’ prints the argument as a decimal, so
the message will say something such as ‘Line 243’.
The number that is printed in place of the ‘%d’ is computed by the last
line of the function:
" 2 0) (89.99578857421875 408.0976867675781 449.48358154296875 517.1473999023438 "(1+ (count-lines 1 (point)))
What this does is count the lines from the first position of the buffer, indi-
cated by the 1, up to (point), and then add one to that number. (The 1+
function adds one to its argument.) We add one to it because line 2 has only
one line before it, and count-lines counts only the lines before the current
line.
After count-lines has done its job, and the message has been printed in
the echo area, the save-excursion restores point and mark to their original
positions; and save-restriction restores the original narrowing, if any.
" 3 0) (89.99539184570312 533.5404663085938 293.41778564453125 547.9010009765625 "6.3 Exercise with Narrowing
" 4 0) (89.99453735351562 555.689208984375 449.53631591796875 616.7474365234375 "Write a function that will display the first 60 characters of the current
buffer, even if you have narrowed the buffer to its latter half so that the first
line is inaccessible. Restore point, mark, and narrowing. For this exercise,
you need to use save-restriction, widen, goto-char, point-min, buffer-
substring, message, and other functions, a whole potpourri.
" 5 0)) (98 (90.0 47.60907745361328 449.7270202636719 60.90726852416992 "80
Chapter 6: Narrowing and Widening
" 0 0)) (99 (90.0 47.60907745361328 449.8250427246094 60.90726852416992 "car and cdr
81
" 0 0) (89.9993896484375 75.14844512939453 434.5227966308594 92.39627838134766 "7 car, cdr, cons: Fundamental Functions
" 1 0) (89.99911499023438 124.28907012939453 449.2903747558594 161.46726989746094 "In Lisp, car, cdr, and cons are fundamental functions. The cons function
is used to construct lists, and the car and cdr functions are used to take
them apart.
" 2 0) (89.9986572265625 166.2890625 449.32257080078125 203.46726989746094 "In the walk through of the copy-region-as-kill function, we will see
cons as well as two variants on cdr, namely, setcdr and nthcdr.
(See
Section 8.5, “copy-region-as-kill”, page 102.)
" 3 0) (89.9974365234375 208.2890625 449.4090881347656 353.1072692871094 "The name of the cons function is not unreasonable: it is an abbreviation
of the word ‘construct’. The origins of the names for car and cdr, on the
other hand, are esoteric: car is an acronym from the phrase ‘Contents of
the Address part of the Register’; and cdr (pronounced ‘could-er’) is an
acronym from the phrase ‘Contents of the Decrement part of the Register’.
These phrases refer to specific pieces of hardware on the very early computer
on which the original Lisp was developed. Besides being obsolete, the phrases
have been completely irrelevant for more than 25 years to anyone thinking
about Lisp. Nonetheless, although a few brave scholars have begun to use
more reasonable names for these functions, the old terms are still in use. In
particular, since the terms are used in the Emacs Lisp source code, we will
use them in this introduction.
" 4 0) (89.99783325195312 386.18035888671875 199.543701171875 400.5535888671875 "7.1 car and cdr
" 5 0) (89.99740600585938 412.5291748046875 449.451904296875 437.7073669433594 "The car of a list is, quite simply, the first item in the list. Thus the car
of the list (rose violet daisy buttercup) is rose.
" 6 0) (89.99795532226562 442.649169921875 449.2989807128906 467.9473571777344 "If you are reading this in Info in GNU Emacs, you can see this by evalu-
ating the following:
" 7 0) (111.59794616699219 477.09771728515625 280.5611877441406 486.0640869140625 "(car ’(rose violet daisy buttercup))
" 8 0) (89.998046875 491.3691711425781 406.93951416015625 504.6673583984375 "After evaluating the expression, rose will appear in the echo area.
" 9 0) (89.9986572265625 509.4891357421875 449.4852600097656 534.787353515625 "Clearly, a more reasonable name for the car function would be first
and this is often suggested.
" 10 0) (89.9981689453125 539.609130859375 449.37591552734375 576.787353515625 "car does not remove the first item from the list; it only reports what it
is. After car has been applied to a list, the list is still the same as it was. In
the jargon, car is ‘non-destructive’. This feature turns out to be important.
" 11 0) (89.99746704101562 581.609130859375 449.451904296875 630.787353515625 "The cdr of a list is the rest of the list, that is, the cdr function returns
the part of the list that follows the first item. Thus, while the car of the
list ’(rose violet daisy buttercup) is rose, the rest of the list, the value
returned by the cdr function, is (violet daisy buttercup).
" 12 0)) (100 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "82
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (105.00006103515625 80.72907257080078 399.5671081542969 94.02725982666016 "You can see this by evaluating the following in the usual way:
" 1 0) (89.99603271484375 100.17758178710938 449.50537109375 379.5072326660156 "(cdr ’(rose violet daisy buttercup))
When you evaluate this, (violet daisy buttercup) will appear in the echo
area.
Like car, cdr does not remove any elements from the list—it just returns
a report of what the second and subsequent elements are.
Incidentally, in the example, the list of flowers is quoted. If it were not, the
Lisp interpreter would try to evaluate the list by calling rose as a function.
In this example, we do not want to do that.
Clearly, a more reasonable name for cdr would be rest.
(There is a lesson here: when you name new functions, consider very
carefully what you are doing, since you may be stuck with the names for far
longer than you expect. The reason this document perpetuates these names
is that the Emacs Lisp source code uses them, and if I did not use them,
you would have a hard time reading the code; but do, please, try to avoid
using these terms yourself. The people who come after you will be grateful
to you.)
When car and cdr are applied to a list made up of symbols, such as the
list (pine fir oak maple), the element of the list returned by the function
car is the symbol pine without any parentheses around it. pine is the first
element in the list. However, the cdr of the list is a list itself, (fir oak
maple), as you can see by evaluating the following expressions in the usual
way:
" 2 0) (111.59603118896484 385.6575927734375 238.39585876464844 394.62396240234375 "(car ’(pine fir oak maple))
" 3 0) (89.99554443359375 410.6175842285156 449.4280090332031 471.1872253417969 "(cdr ’(pine fir oak maple))
On the other hand, in a list of lists, the first element is itself a list. car
returns this first element as a list. For example, the following list contains
three sub-lists, a list of carnivores, a list of herbivores and a list of sea
mammals:
" 4 0) (89.995849609375 477.33758544921875 449.592041015625 550.9873046875 "(car ’((lion tiger cheetah)
(gazelle antelope zebra)
(whale dolphin seal)))
In this example, the first element or car of the list is the list of carnivores,
(lion tiger cheetah), and the rest of the list is ((gazelle antelope
zebra) (whale dolphin seal)).
" 5 0) (89.99578857421875 557.1376342773438 449.3960266113281 630.7872924804688 "(cdr ’((lion tiger cheetah)
(gazelle antelope zebra)
(whale dolphin seal)))
It is worth saying again that car and cdr are non-destructive—that is,
they do not modify or change lists to which they are applied. This is very
important for how they are used.
" 6 0)) (101 (90.0 47.60907745361328 449.8796691894531 60.90726852416992 "cons
83
" 0 0) (89.99908447265625 77.48908233642578 449.39910888671875 198.3072967529297 "Also, in the first chapter, in the discussion about atoms, I said that in
Lisp, “certain kinds of atom, such as an array, can be separated into parts;
but the mechanism for doing this is different from the mechanism for splitting
a list. As far as Lisp is concerned, the atoms of a list are unsplittable.”
(See Section 1.1.1, “Lisp Atoms”, page 1.) The car and cdr functions are
used for splitting lists and are considered fundamental to Lisp. Since they
cannot split or gain access to the parts of an array, an array is considered an
atom. Conversely, the other fundamental function, cons, can put together
or construct a list, but not an array. (Arrays are handled by array-specific
functions. See section “Arrays” in The GNU Emacs Lisp Reference Manual.)
" 1 0) (89.99948120117188 215.660400390625 148.34246826171875 230.0336151123047 "7.2 cons
" 2 0) (89.99945068359375 238.04913330078125 449.1919250488281 275.2273254394531 "The cons function constructs lists; it is the inverse of car and cdr. For
example, cons can be used to make a four element list from the three element
list, (fir oak maple):
" 3 0) (89.99906921386719 280.4175720214844 268.2425537109375 304.1472473144531 "(cons ’pine ’(fir oak maple))
After evaluating this list, you will see
" 4 0) (89.997802734375 309.4576110839844 449.58367919921875 426.0127258300781 "(pine fir oak maple)
appear in the echo area. cons puts a new element at the beginning of a list;
it attaches or pushes elements onto the list.
cons must have a list to attach to.1 You cannot start from absolutely
nothing. If you are building a list, you need to provide at least an empty
list at the beginning. Here is a series of cons expressions that build up a list
of flowers. If you are reading this in Info in GNU Emacs, you can evaluate
each of the expressions in the usual way; the value is printed in this text
after ‘⇒’, which you may read as ‘evaluates to’.
" 5 0) (111.59840393066406 424.1776428222656 205.56089782714844 451.36981201171875 "(cons ’buttercup ())
⇒ (buttercup)
" 6 0) (111.59838104248047 453.6976623535156 233.4697723388672 480.88983154296875 "(cons ’daisy ’(buttercup))
⇒ (daisy buttercup)
" 7 0) (111.59847259521484 483.3376770019531 266.4187927246094 510.52984619140625 "(cons ’violet ’(daisy buttercup))
⇒ (violet daisy buttercup)
" 8 0) (89.99783325195312 512.8577270507812 449.4844665527344 585.0673828125 "(cons ’rose ’(violet daisy buttercup))
⇒ (rose violet daisy buttercup)
In the first example, the empty list is shown as () and a list made up
of buttercup followed by the empty list is constructed. As you can see,
the empty list is not shown in the list that was constructed. All that you
see is (buttercup). The empty list is not counted as an element of a list
" 9 0) (89.98799896240234 594.5919799804688 233.98800659179688 595.0719604492188 "<image: None, width: 1, height: 1, bpc: 1>" 10 1) (95.87999725341797 595.5352172851562 449.7353515625 630.3015747070312 "1 Actually, you can cons an element to an atom to produce a dotted pair. Dotted pairs
are not discussed here; see section “Dotted Pair Notation” in The GNU Emacs Lisp
Reference Manual.
" 11 0)) (102 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "84
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (89.99978637695312 77.48908233642578 449.4430236816406 153.9072723388672 "because there is nothing in an empty list. Generally speaking, an empty list
is invisible.
The second example, (cons ’daisy ’(buttercup)) constructs a new,
two element list by putting daisy in front of buttercup; and the third
example constructs a three element list by putting violet in front of daisy
and buttercup.
" 1 0) (90.00016021728516 171.601806640625 342.6677551269531 184.7173614501953 "7.2.1 Find the Length of a List: length
" 2 0) (90.00006103515625 194.24908447265625 449.4648132324219 219.4272918701172 "You can find out how many elements there are in a list by using the Lisp
function length, as in the following examples:
" 3 0) (111.59971618652344 225.93765258789062 209.98521423339844 253.0098419189453 "(length ’(buttercup))
⇒ 1
" 4 0) (111.59981536865234 255.45761108398438 238.2627410888672 282.6497802734375 "(length ’(daisy buttercup))
⇒ 2
" 5 0) (90.00047302246094 284.9775695800781 449.4336242675781 361.9871826171875 "(length (cons ’violet ’(daisy buttercup)))
⇒ 3
In the third example, the cons function is used to construct a three element
list which is then passed to the length function as its argument.
We can also use length to count the number of elements in an empty
list:
" 6 0) (90.00161743164062 368.3775329589844 449.4566650390625 445.1471862792969 "(length ())
⇒ 0
As you would expect, the number of elements in an empty list is zero.
An interesting experiment is to find out what happens if you try to find
the length of no list at all; that is, if you try to call length without giving
it an argument, not even an empty list:
" 7 0) (90.0020751953125 451.65753173828125 353.7944641113281 476.5871887207031 "(length )
What you see, if you evaluate this, is the error message
" 8 0) (90.00070190429688 482.9775390625 449.422607421875 630.7872314453125 "Wrong number of arguments: #<subr length>, 0
This means that the function receives the wrong number of arguments, zero,
when it expects some other number of arguments. In this case, one argument
is expected, the argument being a list whose length the function is measuring.
(Note that one list is one argument, even if the list has many elements inside
it.)
The part of the error message that says ‘#<subr length>’ is the name of
the function. This is written with a special notation, ‘#<subr’, that indicates
that the function length is one of the primitive functions written in C rather
than in Emacs Lisp. (‘subr’ is an abbreviation for ‘subroutine’.) See section
“What Is a Function?” in The GNU Emacs Lisp Reference Manual, for more
about subroutines.
" 9 0)) (103 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "nthcdr
85
" 0 0) (90.0 77.30034637451172 163.20565795898438 91.67356872558594 "7.3 nthcdr
" 1 0) (89.99871826171875 99.80908966064453 450.03179931640625 237.42735290527344 "The nthcdr function is associated with the cdr function. What it does
is take the cdr of a list repeatedly.
If you take the cdr of the list (pine fir oak maple), you will be returned
the list (fir oak maple).
If you repeat this on what was returned, you
will be returned the list (oak maple). (Of course, repeated cdring on the
original list will just give you the original cdr since the function does not
change the list. You need to evaluate the cdr of the cdr and so on.) If you
continue this, eventually you will be returned an empty list, which in this
case, instead of being shown as () is shown as nil.
For review, here is a series of repeated cdrs, the text following the ‘⇒’
shows what is returned.
" 2 0) (111.59909057617188 242.85769653320312 238.39891052246094 269.92987060546875 "(cdr ’(pine fir oak maple))
⇒(fir oak maple)
" 3 0) (111.59908294677734 272.3777770996094 214.7930145263672 299.5699462890625 "(cdr ’(fir oak maple))
⇒ (oak maple)
" 4 0) (111.59908294677734 301.8977355957031 196.09861755371094 329.08990478515625 "(cdr ’(oak maple))
⇒(maple)
" 5 0) (111.59907531738281 331.5377197265625 177.16415405273438 358.7298889160156 "(cdr ’(maple))
⇒ nil
" 6 0) (111.5990982055664 361.0577392578125 163.3294219970703 388.2499084472656 "(cdr ’nil)
⇒ nil
" 7 0) (89.99932861328125 390.69775390625 449.2679443359375 440.107421875 "(cdr ())
⇒ nil
You can also do several cdrs without printing the values in between, like
this:
" 8 0) (89.9970703125 445.41778564453125 449.45233154296875 603.907470703125 "(cdr (cdr ’(pine fir oak maple)))
⇒ (oak maple)
In this example, the Lisp interpreter evaluates the innermost list first. The
innermost list is quoted, so it just passes the list as it is to the innermost cdr.
This cdr passes a list made up of the second and subsequent elements of the
list to the outermost cdr, which produces a list composed of the third and
subsequent elements of the original list. In this example, the cdr function is
repeated and returns a list that consists of the original list without its first
two elements.
The nthcdr function does the same as repeating the call to cdr. In the
following example, the argument 2 is passed to the function nthcdr, along
with the list, and the value returned is the list without its first two items,
which is exactly the same as repeating cdr twice on the list:
" 9 0) (111.59686279296875 609.2178344726562 261.8825988769531 636.4099731445312 "(nthcdr 2 ’(pine fir oak maple))
⇒ (oak maple)
" 10 0)) (104 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "86
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (89.99990844726562 84.92908477783203 449.3125915527344 110.2272720336914 "Using the original four element list, we can see what happens when various
numeric arguments are passed to nthcdr, including 0, 1, and 5:
" 1 0) (111.60033416748047 120.45520782470703 261.8860778808594 160.12977600097656 ";; Leave the list as it was.
(nthcdr 0 ’(pine fir oak maple))
⇒ (pine fir oak maple)
" 2 0) (111.60026550292969 162.57513427734375 288.8662109375 202.1297149658203 ";; Return a copy without the first element.
(nthcdr 1 ’(pine fir oak maple))
⇒ (fir oak maple)
" 3 0) (111.60029602050781 204.5750732421875 322.9229736328125 244.24964904785156 ";; Return a copy of the list without three elements.
(nthcdr 3 ’(pine fir oak maple))
⇒ (maple)
" 4 0) (111.60054779052734 246.57501220703125 286.4632263183594 286.24957275390625 ";; Return a copy lacking all four elements.
(nthcdr 4 ’(pine fir oak maple))
⇒ nil
" 5 0) (111.60079193115234 288.574951171875 267.28466796875 328.24951171875 ";; Return a copy lacking all elements.
(nthcdr 5 ’(pine fir oak maple))
⇒ nil
" 6 0) (90.00125122070312 359.06005859375 140.91290283203125 373.43328857421875 "7.4 nth
" 7 0) (90.00137329101562 386.48876953125 449.30267333984375 423.7869567871094 "The nthcdr function takes the cdr of a list repeatedly. The nth function
takes the car of the result returned by nthcdr. It returns the Nth element
of the list.
" 8 0) (90.00167846679688 429.80877685546875 449.346435546875 455.1069641113281 "Thus, if it were not defined in C for speed, the definition of nth would
be:
" 9 0) (111.60151672363281 465.4573059082031 412.1624755859375 511.7436828613281 "(defun nth (n list)
\"Returns the Nth element of LIST.
N counts from zero.
If LIST is not that long, nil is returned.\"
(car (nthcdr n list)))
" 10 0) (90.00147247314453 519.0887451171875 449.281005859375 544.386962890625 "(Originally, nth was defined in Emacs Lisp in ‘subr.el’, but its definition
was redone in C in the 1980s.)
" 11 0) (90.00204467773438 550.4088134765625 449.4012145996094 575.5870361328125 "The nth function returns a single element of a list. This can be very
convenient.
" 12 0) (90.00192260742188 581.6087646484375 449.3797302246094 630.7869873046875 "Note that the elements are numbered from zero, not one.
That is to
say, the first element of a list, its car is the zeroth element. This is called
‘zero-based’ counting and often bothers people who are accustomed to the
first element in a list being number one, which is ‘one-based’.
" 13 0)) (105 (90.0 47.60907745361328 449.857666015625 60.90726852416992 "setcdr
87
" 0 0) (105.0 80.84906768798828 166.4837188720703 94.14725494384766 "For example:
" 1 0) (111.60000610351562 100.29757690429688 252.4142303466797 127.48975372314453 "(nth 0 ’(\"one\" \"two\" \"three\"))
⇒ \"one\"
" 2 0) (90.00054931640625 137.61758422851562 449.31256103515625 198.90721130371094 "(nth 1 ’(\"one\" \"two\" \"three\"))
⇒ \"two\"
It is worth mentioning that nth, like nthcdr and cdr, does not change
the original list—the function is non-destructive. This is in sharp contrast
to the setcar and setcdr functions.
" 3 0) (90.0003662109375 220.22027587890625 163.20602416992188 234.59349060058594 "7.5 setcar
" 4 0) (90.00042724609375 243.5689697265625 449.44384765625 331.8671569824219 "As you might guess from their names, the setcar and setcdr functions
set the car or the cdr of a list to a new value. They actually change the
original list, unlike car and cdr which leave the original list as it was. One
way to find out how this works is to experiment. We will start with the
setcar function.
First, we can make a list and then set the value of a variable to the list,
using the setq function. Here is a list of animals:
" 5 0) (89.99884033203125 338.13751220703125 449.4419250488281 437.8271484375 "(setq animals ’(antelope giraffe lion tiger))
If you are reading this in Info inside of GNU Emacs, you can evaluate this
expression in the usual fashion, by positioning the cursor after the expression
and typing C-x C-e.
(I’m doing this right here as I write this.
This is
one of the advantages of having the interpreter built into the computing
environment.)
When we evaluate the variable animals, we see that it is bound to the
list (antelope giraffe lion tiger):
" 6 0) (89.997314453125 443.9775085449219 449.5286865234375 544.2672119140625 "animals
⇒ (antelope giraffe lion tiger)
Put another way, the variable animals points to the list (antelope giraffe
lion tiger).
Next, evaluate the function setcar while passing it two arguments, the
variable animals and the quoted symbol hippopotamus; this is done by
writing the three element list (setcar animals ’hippopotamus) and then
evaluating it in the usual fashion:
" 7 0) (89.9971923828125 550.5375366210938 449.12408447265625 587.2271728515625 "(setcar animals ’hippopotamus)
After evaluating this expression, evaluate the variable animals again. You
will see that the list of animals has changed:
" 8 0) (89.99752807617188 593.4974975585938 420.6189880371094 630.7871704101562 "animals
⇒ (hippopotamus giraffe lion tiger)
The first element on the list, antelope is replaced by hippopotamus.
" 9 0)) (106 (90.0 47.60907745361328 449.3889465332031 60.90726852416992 "88
Chapter 7: car, cdr, cons: Fundamental Functions
" 0 0) (90.00006103515625 77.48908233642578 449.4975891113281 102.66727447509766 "So we can see that setcar did not add a new element to the list as cons
would have; it replaced giraffe with hippopotamus; it changed the list.
" 1 0) (90.0001220703125 119.18035125732422 163.20578002929688 133.55357360839844 "7.6 setcdr
" 2 0) (89.999755859375 141.2091064453125 449.41064453125 204.4272918701172 "The setcdr function is similar to the setcar function, except that the
function replaces the second and subsequent elements of a list rather than
the first element.
To see how this works, set the value of the variable to a list of domesti-
cated animals by evaluating the following expression:
" 3 0) (89.99969482421875 209.49765014648438 449.4212951660156 244.86729431152344 "(setq domesticated-animals ’(horse cow sheep goat))
If you now evaluate the list, you will be returned the list (horse cow sheep
goat):
" 4 0) (89.9986572265625 249.93765258789062 449.322509765625 310.8672790527344 "domesticated-animals
⇒ (horse cow sheep goat)
Next, evaluate setcdr with two arguments, the name of the variable
which has a list as its value, and the list to which the cdr of the first list
will be set;
" 5 0) (89.9986572265625 315.9376525878906 449.27886962890625 375.18731689453125 "(setcdr domesticated-animals ’(cat dog))
If you evaluate this expression, the list (cat dog) will appear in the echo
area. This is the value returned by the function. The result we are inter-
ested in is the “side effect”, which we can see by evaluating the variable
domesticated-animals:
" 6 0) (89.99832153320312 380.1376647949219 449.5284118652344 428.2274169921875 "domesticated-animals
⇒ (horse cat dog)
Indeed, the list is changed from (horse cow sheep goat) to (horse cat
dog). The cdr of the list is changed from (cow sheep goat) to (cat dog).
" 7 0) (89.99771118164062 444.6205139160156 176.97572326660156 458.9810485839844 "7.7 Exercise
" 8 0) (89.99710083007812 466.76922607421875 449.5281982421875 515.8274536132812 "Construct a list of four birds by evaluating several expressions with cons.
Find out what happens when you cons a list onto itself. Replace the first
element of the list of four birds with a fish. Replace the rest of that list with
a list of other fish.
" 9 0)) (107 (90.0 47.60907745361328 449.80364990234375 60.90726852416992 "zap-to-char
89
" 0 0) (90.0 75.14844512939453 325.3755187988281 92.38106536865234 "8 Cutting and Storing Text
" 1 0) (89.99948120117188 112.28907012939453 449.3558349609375 264.6672058105469 "Whenever you cut or clip text out of a buffer with a ‘kill’ command in
GNU Emacs, it is stored in a list and you can bring it back with a ‘yank’
command.
(The use of the word ‘kill’ in Emacs for processes which specifically do
not destroy the values of the entities is an unfortunate historical accident.
A much more appropriate word would be ‘clip’ since that is what the kill
commands do; they clip text out of a buffer and put it into storage from
which it can be brought back. I have often been tempted to replace globally
all occurrences of ‘kill’ in the Emacs sources with ‘clip’ and all occurrences
of ‘killed’ with ‘clipped’.)
When text is cut out of a buffer, it is stored on a list. Successive pieces
of text are stored on the list successively, so the list might look like this:
" 2 0) (90.00041198730469 271.4175720214844 440.9891357421875 296.7072448730469 "(\"a piece of text\" \"previous piece\")
The function cons can be used to add a piece of text to the list, like this:
" 3 0) (111.60003662109375 303.4576110839844 318.2345886230469 324.9039611816406 "(cons \"another piece\"
’(\"a piece of text\" \"previous piece\"))
" 4 0) (89.999755859375 329.0090637207031 449.3665771484375 354.3072509765625 "If you evaluate this expression, a list of three elements will appear in the
echo area:
" 5 0) (89.99966430664062 361.0576171875 449.464599609375 422.1072692871094 "(\"another piece\" \"a piece of text\" \"previous piece\")
With the car and nthcdr functions, you can retrieve whichever piece of
text you want. For example, in the following code, nthcdr 1 ... returns
the list with the first item removed; and the car returns the first element of
that remainder—the second element of the original list:
" 6 0) (89.99789428710938 428.9776306152344 449.49700927734375 630.787353515625 "(car (nthcdr 1 ’(\"another piece\"
\"a piece of text\"
\"previous piece\")))
⇒ \"a piece of text\"
The actual functions in Emacs are more complex than this, of course.
The code for cutting and retrieving text has to be written so that Emacs
can figure out which element in the list you want—the first, second, third,
or whatever. In addition, when you get to the end of the list, Emacs should
give you the first element of the list, rather than nothing at all.
The list that holds the pieces of text is called the kill ring. This chapter
leads up to a description of the kill ring and how it is used by first tracing how
the zap-to-char function works. This function uses (or ‘calls’) a function
that invokes a function that manipulates the kill ring. Thus, before reaching
the mountains, we climb the foothills.
A subsequent chapter describes how text that is cut from the buffer is
retrieved. See Chapter 10, “Yanking Text Back”, page 117.
" 7 0))))

(provide 'baleen)
;;; baleen.el ends here

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-24 20:53         ` dalanicolai
  2023-02-24 21:19           ` dalanicolai
@ 2023-02-25 10:51           ` Eli Zaretskii
  2023-02-25 13:17             ` dalanicolai
  1 sibling, 1 reply; 14+ messages in thread
From: Eli Zaretskii @ 2023-02-25 10:51 UTC (permalink / raw)
  To: dalanicolai; +Cc: emacs-devel

> From: dalanicolai <dalanicolai@gmail.com>
> Date: Fri, 24 Feb 2023 21:53:35 +0100
> Cc: emacs-devel@gnu.org
> 
> B.t.w if someone want to have a look, I'll attach a smaller file here where
> I have just removed about 200 pages of the book text data, so that it is
> the file is much smaller, but there is still enough date to clearly show the
> 'undesired' behavior.
> 
> So now, Emacs will not 'hang', but there will still be a clear difference in time it
> takes to update the buffer (between when window margins are displayed,
> and when they are not).

Your code overwhelms redisplay with an inconceivably huge number of
overlays that are left from the previous iteration.  This one-line
change makes the code work reasonably fast:

(defun baleen-update2 ()
  ;; (let ((query (minibuffer-contents)))
  ;;   (with-current-buffer (get-buffer-create "*baleen*")
  ;;     (erase-buffer)
  ;;     (baleen-render (baleen-filter test2 query)))))
  (let* ((query (minibuffer-contents))
         (query-length (length query)))
    (if (> (length previous-query) query-length)
        (with-current-buffer (get-buffer-create "*baleen*")
          (erase-buffer)
          (baleen-render (cdr (alist-get query baleen-results nil nil #'string=))))
      (let* ((parent-results (unless (< query-length 2)
                               (alist-get (substring query 0 -1) baleen-results nil nil #'string=)))
             (current-results (if parent-results
                                  (baleen-filter parent-results query)
                                (unless (string-empty-p query) (baleen-filter test2 query)))))
        (when current-results
          (with-current-buffer (get-buffer-create "*baleen*")
	    (remove-overlays) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            (erase-buffer)
            (baleen-render current-results))
          (cl-pushnew (cons query current-results) baleen-results :test #'string= :key #'car))

        (setq previous-query query)))))



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-25 10:51           ` Eli Zaretskii
@ 2023-02-25 13:17             ` dalanicolai
  2023-02-25 13:42               ` Eli Zaretskii
  0 siblings, 1 reply; 14+ messages in thread
From: dalanicolai @ 2023-02-25 13:17 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel

[-- Attachment #1: Type: text/plain, Size: 2643 bytes --]

This is great! Indeed, it works perfectly now.
I think using the margins is just much more elegant.

Although, I might have read about this behavior somewhere,
obviously, it was not clear to me that `erase-buffer` does not
remove the overlays. Maybe a warning/reminder about this could
 be added in the 'erase-buffer' docstring? What do you think?
I would be happy to create a patch for that (if desired).

Anyway, thanks a lot again Eli, for having a look at it.
Obviously, I really appreciate it.


On Sat, 25 Feb 2023 at 11:51, Eli Zaretskii <eliz@gnu.org> wrote:

> > From: dalanicolai <dalanicolai@gmail.com>
> > Date: Fri, 24 Feb 2023 21:53:35 +0100
> > Cc: emacs-devel@gnu.org
> >
> > B.t.w if someone want to have a look, I'll attach a smaller file here
> where
> > I have just removed about 200 pages of the book text data, so that it is
> > the file is much smaller, but there is still enough date to clearly show
> the
> > 'undesired' behavior.
> >
> > So now, Emacs will not 'hang', but there will still be a clear
> difference in time it
> > takes to update the buffer (between when window margins are displayed,
> > and when they are not).
>
> Your code overwhelms redisplay with an inconceivably huge number of
> overlays that are left from the previous iteration.  This one-line
> change makes the code work reasonably fast:
>
> (defun baleen-update2 ()
>   ;; (let ((query (minibuffer-contents)))
>   ;;   (with-current-buffer (get-buffer-create "*baleen*")
>   ;;     (erase-buffer)
>   ;;     (baleen-render (baleen-filter test2 query)))))
>   (let* ((query (minibuffer-contents))
>          (query-length (length query)))
>     (if (> (length previous-query) query-length)
>         (with-current-buffer (get-buffer-create "*baleen*")
>           (erase-buffer)
>           (baleen-render (cdr (alist-get query baleen-results nil nil
> #'string=))))
>       (let* ((parent-results (unless (< query-length 2)
>                                (alist-get (substring query 0 -1)
> baleen-results nil nil #'string=)))
>              (current-results (if parent-results
>                                   (baleen-filter parent-results query)
>                                 (unless (string-empty-p query)
> (baleen-filter test2 query)))))
>         (when current-results
>           (with-current-buffer (get-buffer-create "*baleen*")
>             (remove-overlays) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>             (erase-buffer)
>             (baleen-render current-results))
>           (cl-pushnew (cons query current-results) baleen-results :test
> #'string= :key #'car))
>
>         (setq previous-query query)))))
>

[-- Attachment #2: Type: text/html, Size: 3655 bytes --]

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-25 13:17             ` dalanicolai
@ 2023-02-25 13:42               ` Eli Zaretskii
  2023-03-06 22:51                 ` dalanicolai
  0 siblings, 1 reply; 14+ messages in thread
From: Eli Zaretskii @ 2023-02-25 13:42 UTC (permalink / raw)
  To: dalanicolai; +Cc: emacs-devel

> From: dalanicolai <dalanicolai@gmail.com>
> Date: Sat, 25 Feb 2023 14:17:24 +0100
> Cc: emacs-devel@gnu.org
> 
> This is great! Indeed, it works perfectly now.
> I think using the margins is just much more elegant.
> 
> Although, I might have read about this behavior somewhere,
> obviously, it was not clear to me that `erase-buffer` does not
> remove the overlays. Maybe a warning/reminder about this could
>  be added in the 'erase-buffer' docstring? What do you think?
> I would be happy to create a patch for that (if desired).

This is not related to erasing a buffer, it is related to deleting
text "covered" by the overlay.  What happens in that case depends on
the 'evaporate' property of the overlay, which is already described in
the ELisp manual, see the node "Overlay Properties" there.



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: displaying margins leads to Emacs hanging
  2023-02-25 13:42               ` Eli Zaretskii
@ 2023-03-06 22:51                 ` dalanicolai
  0 siblings, 0 replies; 14+ messages in thread
From: dalanicolai @ 2023-03-06 22:51 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: emacs-devel

[-- Attachment #1: Type: text/plain, Size: 1194 bytes --]

Somehow, annoyingly, I missed this last message earlier.
But I'd still prefer to thank you for your instructive answers.

Indeed, I have read about the evaporate property before,
but I have not used it before, so that I forgot about it.
I'm more or less sure that it will stick this time...

On Sat, 25 Feb 2023 at 14:42, Eli Zaretskii <eliz@gnu.org> wrote:

> > From: dalanicolai <dalanicolai@gmail.com>
> > Date: Sat, 25 Feb 2023 14:17:24 +0100
> > Cc: emacs-devel@gnu.org
> >
> > This is great! Indeed, it works perfectly now.
> > I think using the margins is just much more elegant.
> >
> > Although, I might have read about this behavior somewhere,
> > obviously, it was not clear to me that `erase-buffer` does not
> > remove the overlays. Maybe a warning/reminder about this could
> >  be added in the 'erase-buffer' docstring? What do you think?
> > I would be happy to create a patch for that (if desired).
>
> This is not related to erasing a buffer, it is related to deleting
> text "covered" by the overlay.  What happens in that case depends on
> the 'evaporate' property of the overlay, which is already described in
> the ELisp manual, see the node "Overlay Properties" there.
>

[-- Attachment #2: Type: text/html, Size: 1791 bytes --]

^ permalink raw reply	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2023-03-06 22:51 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-02-24 19:29 displaying margins leads to Emacs hanging dalanicolai
2023-02-24 19:41 ` Eli Zaretskii
2023-02-24 20:26   ` dalanicolai
2023-02-24 20:29     ` Eli Zaretskii
2023-02-24 20:41       ` dalanicolai
2023-02-24 20:53         ` dalanicolai
2023-02-24 21:19           ` dalanicolai
2023-02-24 21:43             ` dalanicolai
2023-02-25 10:51           ` Eli Zaretskii
2023-02-25 13:17             ` dalanicolai
2023-02-25 13:42               ` Eli Zaretskii
2023-03-06 22:51                 ` dalanicolai
2023-02-24 21:25         ` Eli Zaretskii
2023-02-24 21:41           ` dalanicolai

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).