subr.el 193 KB
Newer Older
1
;;; subr.el --- basic lisp subroutines for Emacs  -*- coding: utf-8; lexical-binding:t -*-
Eric S. Raymond's avatar
Eric S. Raymond committed
2

3
;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2014 Free Software
4
;; Foundation, Inc.
David Lawrence's avatar
David Lawrence committed
5

6
;; Maintainer: emacs-devel@gnu.org
Pavel Janík's avatar
Pavel Janík committed
7
;; Keywords: internal
8
;; Package: emacs
Pavel Janík's avatar
Pavel Janík committed
9

David Lawrence's avatar
David Lawrence committed
10 11
;; This file is part of GNU Emacs.

12
;; GNU Emacs is free software: you can redistribute it and/or modify
David Lawrence's avatar
David Lawrence committed
13
;; it under the terms of the GNU General Public License as published by
14 15
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
David Lawrence's avatar
David Lawrence committed
16 17 18 19 20 21 22

;; GNU Emacs 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
23
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
David Lawrence's avatar
David Lawrence committed
24

25 26
;;; Commentary:

Eric S. Raymond's avatar
Eric S. Raymond committed
27
;;; Code:
28

29 30 31
;; Beware: while this file has tag `utf-8', before it's compiled, it gets
;; loaded as "raw-text", so non-ASCII chars won't work right during bootstrap.

32
(defmacro declare-function (_fn _file &optional _arglist _fileonly)
33
  "Tell the byte-compiler that function FN is defined, in FILE.
Juanma Barranquero's avatar
Juanma Barranquero committed
34 35
Optional ARGLIST is the argument list used by the function.
The FILE argument is not used by the byte-compiler, but by the
36
`check-declare' package, which checks that FILE contains a
Juanma Barranquero's avatar
Juanma Barranquero committed
37 38
definition for FN.  ARGLIST is used by both the byte-compiler
and `check-declare' to check for consistency.
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

FILE can be either a Lisp file (in which case the \".el\"
extension is optional), or a C file.  C files are expanded
relative to the Emacs \"src/\" directory.  Lisp files are
searched for using `locate-library', and if that fails they are
expanded relative to the location of the file containing the
declaration.  A FILE with an \"ext:\" prefix is an external file.
`check-declare' will check such files if they are found, and skip
them without error if they are not.

FILEONLY non-nil means that `check-declare' will only check that
FILE exists, not that it defines FN.  This is intended for
function-definitions that `check-declare' does not recognize, e.g.
`defstruct'.

To specify a value for FILEONLY without passing an argument list,
55
set ARGLIST to t.  This is necessary because nil means an
56 57 58
empty argument list, rather than an unspecified one.

Note that for the purposes of `check-declare', this statement
Glenn Morris's avatar
Glenn Morris committed
59
must be the first non-whitespace on a line.
60

Glenn Morris's avatar
Glenn Morris committed
61
For more information, see Info node `(elisp)Declaring Functions'."
62 63
  ;; Does nothing - byte-compile-declare-function does the work.
  nil)
Eli Zaretskii's avatar
Eli Zaretskii committed
64

65

66
;;;; Basic Lisp macros.
67

Stefan Monnier's avatar
Stefan Monnier committed
68 69
(defalias 'not 'null)

Kenichi Handa's avatar
Kenichi Handa committed
70
(defmacro noreturn (form)
Luc Teirlinck's avatar
Luc Teirlinck committed
71 72
  "Evaluate FORM, expecting it not to return.
If FORM does return, signal an error."
73
  (declare (debug t))
Kenichi Handa's avatar
Kenichi Handa committed
74 75 76 77
  `(prog1 ,form
     (error "Form marked with `noreturn' did return")))

(defmacro 1value (form)
Luc Teirlinck's avatar
Luc Teirlinck committed
78 79 80
  "Evaluate FORM, expecting a constant return value.
This is the global do-nothing version.  There is also `testcover-1value'
that complains if FORM ever does return differing values."
81
  (declare (debug t))
Kenichi Handa's avatar
Kenichi Handa committed
82 83
  form)

84 85
(defmacro def-edebug-spec (symbol spec)
  "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
Glenn Morris's avatar
Glenn Morris committed
86 87 88 89
Both SYMBOL and SPEC are unevaluated.  The SPEC can be:
0 (instrument no arguments); t (instrument all arguments);
a symbol (naming a function with an Edebug specification); or a list.
The elements of the list describe the argument types; see
90
Info node `(elisp)Specification List' for details."
91 92
  `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))

93 94 95 96 97
(defmacro lambda (&rest cdr)
  "Return a lambda expression.
A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
self-quoting; the result of evaluating the lambda expression is the
expression itself.  The lambda expression may then be treated as a
Richard M. Stallman's avatar
Richard M. Stallman committed
98
function, i.e., stored as the function value of a symbol, passed to
99
`funcall' or `mapcar', etc.
Richard M. Stallman's avatar
Richard M. Stallman committed
100

101
ARGS should take the same form as an argument list for a `defun'.
Richard M. Stallman's avatar
Richard M. Stallman committed
102 103 104
DOCSTRING is an optional documentation string.
 If present, it should describe how to call the function.
 But documentation strings are usually not useful in nameless functions.
105 106
INTERACTIVE should be a call to the function `interactive', which see.
It may also be omitted.
107 108 109
BODY should be a list of Lisp expressions.

\(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
110 111 112 113 114
  (declare (doc-string 2) (indent defun)
           (debug (&define lambda-list
                           [&optional stringp]
                           [&optional ("interactive" interactive)]
                           def-body)))
115 116 117 118
  ;; Note that this definition should not use backquotes; subr.el should not
  ;; depend on backquote.el.
  (list 'function (cons 'lambda cdr)))

119 120 121 122 123 124 125 126 127
(defmacro setq-local (var val)
  "Set variable VAR to value VAL in current buffer."
  ;; Can't use backquote here, it's too early in the bootstrap.
  (list 'set (list 'make-local-variable (list 'quote var)) val))

(defmacro defvar-local (var val &optional docstring)
  "Define VAR as a buffer-local variable with default value VAL.
Like `defvar' but additionally marks the variable as being automatically
buffer-local wherever it is set."
128
  (declare (debug defvar) (doc-string 3))
129 130 131 132
  ;; Can't use backquote here, it's too early in the bootstrap.
  (list 'progn (list 'defvar var val docstring)
        (list 'make-variable-buffer-local (list 'quote var))))

133 134 135 136 137 138
(defun apply-partially (fun &rest args)
  "Return a function that is a partial application of FUN to ARGS.
ARGS is a list of the first N arguments to pass to FUN.
The result is a new function which does the same as FUN, except that
the first N arguments are fixed at the values with which this function
was called."
139
  `(closure (t) (&rest args)
140 141
            (apply ',fun ,@(mapcar (lambda (arg) `',arg) args) args)))

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
(defmacro push (newelt place)
  "Add NEWELT to the list stored in the generalized variable PLACE.
This is morally equivalent to (setf PLACE (cons NEWELT PLACE)),
except that PLACE is only evaluated once (after NEWELT)."
  (declare (debug (form gv-place)))
  (if (symbolp place)
      ;; Important special case, to avoid triggering GV too early in
      ;; the bootstrap.
      (list 'setq place
            (list 'cons newelt place))
    (require 'macroexp)
    (macroexp-let2 macroexp-copyable-p v newelt
      (gv-letplace (getter setter) place
        (funcall setter `(cons ,v ,getter))))))

(defmacro pop (place)
  "Return the first element of PLACE's value, and remove it from the list.
PLACE must be a generalized variable whose value is a list.
Richard M. Stallman's avatar
Richard M. Stallman committed
160 161
If the value is nil, `pop' returns nil but does not actually
change the list."
162
  (declare (debug (gv-place)))
163 164 165 166 167 168 169 170 171 172
  ;; We use `car-safe' here instead of `car' because the behavior is the same
  ;; (if it's not a cons cell, the `cdr' would have signaled an error already),
  ;; but `car-safe' is total, so the byte-compiler can safely remove it if the
  ;; result is not used.
  `(car-safe
    ,(if (symbolp place)
         ;; So we can use `pop' in the bootstrap before `gv' can be used.
         (list 'prog1 place (list 'setq place (list 'cdr place)))
       (gv-letplace (getter setter) place
         `(prog1 ,getter ,(funcall setter `(cdr ,getter)))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
173

174
(defmacro when (cond &rest body)
Kim F. Storm's avatar
Kim F. Storm committed
175 176 177 178
  "If COND yields non-nil, do BODY, else return nil.
When COND yields non-nil, eval BODY forms sequentially and return
value of last one, or nil if there are none.

Juanma Barranquero's avatar
Juanma Barranquero committed
179
\(fn COND BODY...)"
180
  (declare (indent 1) (debug t))
181
  (list 'if cond (cons 'progn body)))
182

183
(defmacro unless (cond &rest body)
Kim F. Storm's avatar
Kim F. Storm committed
184 185 186 187
  "If COND yields nil, do BODY, else return nil.
When COND yields nil, eval BODY forms sequentially and return
value of last one, or nil if there are none.

Juanma Barranquero's avatar
Juanma Barranquero committed
188
\(fn COND BODY...)"
189
  (declare (indent 1) (debug t))
190
  (cons 'if (cons cond (cons nil body))))
191

192
(defmacro dolist (spec &rest body)
193
  "Loop over a list.
194
Evaluate BODY with VAR bound to each car from LIST, in turn.
195 196
Then evaluate RESULT to get return value, default nil.

Markus Rost's avatar
Markus Rost committed
197
\(fn (VAR LIST [RESULT]) BODY...)"
198
  (declare (indent 1) (debug ((symbolp form &optional form) body)))
199 200 201
  ;; It would be cleaner to create an uninterned symbol,
  ;; but that uses a lot more space when many functions in many files
  ;; use dolist.
202
  ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
203
  (let ((temp '--dolist-tail--))
204 205 206 207 208 209 210 211 212 213
    ;; This is not a reliable test, but it does not matter because both
    ;; semantics are acceptable, tho one is slightly faster with dynamic
    ;; scoping and the other is slightly faster (and has cleaner semantics)
    ;; with lexical scoping.
    (if lexical-binding
        `(let ((,temp ,(nth 1 spec)))
           (while ,temp
             (let ((,(car spec) (car ,temp)))
               ,@body
               (setq ,temp (cdr ,temp))))
214
           ,@(cdr (cdr spec)))
215 216 217 218 219 220 221 222
      `(let ((,temp ,(nth 1 spec))
             ,(car spec))
         (while ,temp
           (setq ,(car spec) (car ,temp))
           ,@body
           (setq ,temp (cdr ,temp)))
         ,@(if (cdr (cdr spec))
               `((setq ,(car spec) nil) ,@(cdr (cdr spec))))))))
223

224
(defmacro dotimes (spec &rest body)
225
  "Loop a certain number of times.
226 227
Evaluate BODY with VAR bound to successive integers running from 0,
inclusive, to COUNT, exclusive.  Then evaluate RESULT to get
228 229
the return value (nil if RESULT is omitted).

Markus Rost's avatar
Markus Rost committed
230
\(fn (VAR COUNT [RESULT]) BODY...)"
231
  (declare (indent 1) (debug dolist))
232 233 234
  ;; It would be cleaner to create an uninterned symbol,
  ;; but that uses a lot more space when many functions in many files
  ;; use dotimes.
235
  ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
236
  (let ((temp '--dotimes-limit--)
237 238
	(start 0)
	(end (nth 1 spec)))
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    ;; This is not a reliable test, but it does not matter because both
    ;; semantics are acceptable, tho one is slightly faster with dynamic
    ;; scoping and the other has cleaner semantics.
    (if lexical-binding
        (let ((counter '--dotimes-counter--))
          `(let ((,temp ,end)
                 (,counter ,start))
             (while (< ,counter ,temp)
               (let ((,(car spec) ,counter))
                 ,@body)
               (setq ,counter (1+ ,counter)))
             ,@(if (cddr spec)
                   ;; FIXME: This let often leads to "unused var" warnings.
                   `((let ((,(car spec) ,counter)) ,@(cddr spec))))))
      `(let ((,temp ,end)
             (,(car spec) ,start))
         (while (< ,(car spec) ,temp)
           ,@body
           (setq ,(car spec) (1+ ,(car spec))))
         ,@(cdr (cdr spec))))))
259

260
(defmacro declare (&rest _specs)
261 262 263 264 265 266 267
  "Do not evaluate any arguments, and return nil.
If a `declare' form appears as the first form in the body of a
`defun' or `defmacro' form, SPECS specifies various additional
information about the function or macro; these go into effect
during the evaluation of the `defun' or `defmacro' form.

The possible values of SPECS are specified by
268 269 270
`defun-declarations-alist' and `macro-declarations-alist'.

For more information, see info node `(elisp)Declare Form'."
Stefan Monnier's avatar
Stefan Monnier committed
271
  ;; FIXME: edebug spec should pay attention to defun-declarations-alist.
272
  nil)
273 274 275

(defmacro ignore-errors (&rest body)
  "Execute BODY; if an error occurs, return nil.
276 277 278
Otherwise, return result of last form in BODY.
See also `with-demoted-errors' that does something similar
without silencing all errors."
279
  (declare (debug t) (indent 0))
280
  `(condition-case nil (progn ,@body) (error nil)))
281 282 283

;;;; Basic Lisp functions.

284
(defun ignore (&rest _ignore)
285 286 287 288 289
  "Do nothing and return nil.
This function accepts any number of arguments, but ignores them."
  (interactive)
  nil)

290
;; Signal a compile-error if the first arg is missing.
291 292 293 294
(defun error (&rest args)
  "Signal an error, making error message by passing all args to `format'.
In Emacs, the convention is that error messages start with a capital
letter but *do not* end with a period.  Please follow this convention
295
for the sake of consistency."
296
  (declare (advertised-calling-convention (string &rest args) "23.1"))
297
  (signal 'error (list (apply 'format args))))
298

299 300 301 302 303 304 305 306
(defun user-error (format &rest args)
  "Signal a pilot error, making error message by passing all args to `format'.
In Emacs, the convention is that error messages start with a capital
letter but *do not* end with a period.  Please follow this convention
for the sake of consistency.
This is just like `error' except that `user-error's are expected to be the
result of an incorrect manipulation on the part of the user, rather than the
result of an actual problem."
307
  (signal 'user-error (list (apply #'format format args))))
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
(defun define-error (name message &optional parent)
  "Define NAME as a new error signal.
MESSAGE is a string that will be output to the echo area if such an error
is signaled without being caught by a `condition-case'.
PARENT is either a signal or a list of signals from which it inherits.
Defaults to `error'."
  (unless parent (setq parent 'error))
  (let ((conditions
         (if (consp parent)
             (apply #'nconc
                    (mapcar (lambda (parent)
                              (cons parent
                                    (or (get parent 'error-conditions)
                                        (error "Unknown signal `%s'" parent))))
                            parent))
           (cons parent (get parent 'error-conditions)))))
    (put name 'error-conditions
         (delete-dups (copy-sequence (cons name conditions))))
    (when message (put name 'error-message message))))

329 330 331 332 333 334 335 336
;; We put this here instead of in frame.el so that it's defined even on
;; systems where frame.el isn't loaded.
(defun frame-configuration-p (object)
  "Return non-nil if OBJECT seems to be a frame configuration.
Any list whose car is `frame-configuration' is assumed to be a frame
configuration."
  (and (consp object)
       (eq (car object) 'frame-configuration)))
337

338 339

;;;; List functions.
Kenichi Handa's avatar
Kenichi Handa committed
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
(defsubst caar (x)
  "Return the car of the car of X."
  (car (car x)))

(defsubst cadr (x)
  "Return the car of the cdr of X."
  (car (cdr x)))

(defsubst cdar (x)
  "Return the cdr of the car of X."
  (cdr (car x)))

(defsubst cddr (x)
  "Return the cdr of the cdr of X."
  (cdr (cdr x)))
Richard M. Stallman's avatar
Richard M. Stallman committed
356

357 358 359 360 361
(defun last (list &optional n)
  "Return the last link of LIST.  Its car is the last element.
If LIST is nil, return nil.
If N is non-nil, return the Nth-to-last link of LIST.
If N is bigger than the length of LIST, return LIST."
362
  (if n
363
      (and (>= n 0)
364
           (let ((m (safe-length list)))
365 366
             (if (< n m) (nthcdr (- m n) list) list)))
    (and list
367
         (nthcdr (1- (safe-length list)) list))))
368

369
(defun butlast (list &optional n)
370 371 372
  "Return a copy of LIST with the last N elements removed.
If N is omitted or nil, the last element is removed from the
copy."
373 374
  (if (and n (<= n 0)) list
    (nbutlast (copy-sequence list) n)))
375

376
(defun nbutlast (list &optional n)
377 378
  "Modifies LIST to remove the last N elements.
If N is omitted or nil, remove the last element."
379
  (let ((m (length list)))
380 381 382
    (or n (setq n 1))
    (and (< n m)
	 (progn
383 384
	   (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
	   list))))
385

386 387 388 389 390 391 392
(defun zerop (number)
  "Return t if NUMBER is zero."
  ;; Used to be in C, but it's pointless since (= 0 n) is faster anyway because
  ;; = has a byte-code.
  (declare (compiler-macro (lambda (_) `(= 0 ,number))))
  (= 0 number))

Kenichi Handa's avatar
Kenichi Handa committed
393 394 395 396 397 398 399 400 401 402 403
(defun delete-dups (list)
  "Destructively remove `equal' duplicates from LIST.
Store the result in LIST and return it.  LIST must be a proper list.
Of several `equal' occurrences of an element in LIST, the first
one is kept."
  (let ((tail list))
    (while tail
      (setcdr tail (delete (car tail) (cdr tail)))
      (setq tail (cdr tail))))
  list)

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
;; See http://lists.gnu.org/archive/html/emacs-devel/2013-05/msg00204.html
(defun delete-consecutive-dups (list &optional circular)
  "Destructively remove `equal' consecutive duplicates from LIST.
First and last elements are considered consecutive if CIRCULAR is
non-nil."
  (let ((tail list) last)
    (while (consp tail)
      (if (equal (car tail) (cadr tail))
	  (setcdr tail (cddr tail))
	(setq last (car tail)
	      tail (cdr tail))))
    (if (and circular
	     (cdr list)
	     (equal last (car list)))
	(nbutlast list)
      list)))

421
(defun number-sequence (from &optional to inc)
422
  "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
Kenichi Handa's avatar
Kenichi Handa committed
423
INC is the increment used between numbers in the sequence and defaults to 1.
Juanma Barranquero's avatar
Juanma Barranquero committed
424
So, the Nth element of the list is (+ FROM (* N INC)) where N counts from
Kenichi Handa's avatar
Kenichi Handa committed
425
zero.  TO is only included if there is an N for which TO = FROM + N * INC.
Juanma Barranquero's avatar
Juanma Barranquero committed
426
If TO is nil or numerically equal to FROM, return (FROM).
Kenichi Handa's avatar
Kenichi Handa committed
427 428 429 430 431 432 433 434 435
If INC is positive and TO is less than FROM, or INC is negative
and TO is larger than FROM, return nil.
If INC is zero and TO is neither nil nor numerically equal to
FROM, signal an error.

This function is primarily designed for integer arguments.
Nevertheless, FROM, TO and INC can be integer or float.  However,
floating point arithmetic is inexact.  For instance, depending on
the machine, it may quite well happen that
Juanma Barranquero's avatar
Juanma Barranquero committed
436 437
\(number-sequence 0.4 0.6 0.2) returns the one element list (0.4),
whereas (number-sequence 0.4 0.8 0.2) returns a list with three
Kenichi Handa's avatar
Kenichi Handa committed
438 439
elements.  Thus, if some of the arguments are floats and one wants
to make sure that TO is included, one may have to explicitly write
Juanma Barranquero's avatar
Juanma Barranquero committed
440
TO as (+ FROM (* N INC)) or use a variable whose value was
Kenichi Handa's avatar
Kenichi Handa committed
441 442 443 444
computed with this exact expression.  Alternatively, you can,
of course, also replace TO with a slightly larger value
\(or a slightly more negative value if INC is negative)."
  (if (or (not to) (= from to))
445 446
      (list from)
    (or inc (setq inc 1))
Kenichi Handa's avatar
Kenichi Handa committed
447 448 449 450 451 452 453 454 455 456 457
    (when (zerop inc) (error "The increment can not be zero"))
    (let (seq (n 0) (next from))
      (if (> inc 0)
          (while (<= next to)
            (setq seq (cons next seq)
                  n (1+ n)
                  next (+ from (* n inc))))
        (while (>= next to)
          (setq seq (cons next seq)
                n (1+ n)
                next (+ from (* n inc)))))
458
      (nreverse seq))))
459

460 461 462
(defun copy-tree (tree &optional vecp)
  "Make a copy of TREE.
If TREE is a cons cell, this recursively copies both its car and its cdr.
463
Contrast to `copy-sequence', which copies only along the cdrs.  With second
464 465
argument VECP, this copies vectors as well as conses."
  (if (consp tree)
466 467 468 469 470 471 472
      (let (result)
	(while (consp tree)
	  (let ((newcar (car tree)))
	    (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
		(setq newcar (copy-tree (car tree) vecp)))
	    (push newcar result))
	  (setq tree (cdr tree)))
473
	(nconc (nreverse result) tree))
474 475 476
    (if (and vecp (vectorp tree))
	(let ((i (length (setq tree (copy-sequence tree)))))
	  (while (>= (setq i (1- i)) 0)
477 478 479
	    (aset tree i (copy-tree (aref tree i) vecp)))
	  tree)
      tree)))
480 481

;;;; Various list-search functions.
482

483 484
(defun assoc-default (key alist &optional test default)
  "Find object KEY in a pseudo-alist ALIST.
485 486 487 488 489 490 491
ALIST is a list of conses or objects.  Each element
 (or the element's car, if it is a cons) is compared with KEY by
 calling TEST, with two arguments: (i) the element or its car,
 and (ii) KEY.
If that is non-nil, the element matches; then `assoc-default'
 returns the element's cdr, if it is a cons, or DEFAULT if the
 element is not a cons.
492 493 494 495 496 497 498 499 500 501

If no element matches, the value is nil.
If TEST is omitted or nil, `equal' is used."
  (let (found (tail alist) value)
    (while (and tail (not found))
      (let ((elt (car tail)))
	(when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
	  (setq found t value (if (consp elt) (cdr elt) default))))
      (setq tail (cdr tail)))
    value))
502 503 504 505 506

(defun assoc-ignore-case (key alist)
  "Like `assoc', but ignores differences in case and text representation.
KEY must be a string.  Upper-case and lower-case letters are treated as equal.
Unibyte strings are converted to multibyte for comparison."
507
  (declare (obsolete assoc-string "22.1"))
Kenichi Handa's avatar
Kenichi Handa committed
508
  (assoc-string key alist t))
509 510 511

(defun assoc-ignore-representation (key alist)
  "Like `assoc', but ignores differences in text representation.
Juanma Barranquero's avatar
Juanma Barranquero committed
512
KEY must be a string.
513
Unibyte strings are converted to multibyte for comparison."
514
  (declare (obsolete assoc-string "22.1"))
Kenichi Handa's avatar
Kenichi Handa committed
515
  (assoc-string key alist nil))
516 517

(defun member-ignore-case (elt list)
Glenn Morris's avatar
Glenn Morris committed
518
  "Like `member', but ignore differences in case and text representation.
519
ELT must be a string.  Upper-case and lower-case letters are treated as equal.
520 521 522 523 524
Unibyte strings are converted to multibyte for comparison.
Non-strings in LIST are ignored."
  (while (and list
	      (not (and (stringp (car list))
			(eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
525 526
    (setq list (cdr list)))
  list)
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
(defun assq-delete-all (key alist)
  "Delete from ALIST all elements whose car is `eq' to KEY.
Return the modified alist.
Elements of ALIST that are not conses are ignored."
  (while (and (consp (car alist))
	      (eq (car (car alist)) key))
    (setq alist (cdr alist)))
  (let ((tail alist) tail-cdr)
    (while (setq tail-cdr (cdr tail))
      (if (and (consp (car tail-cdr))
	       (eq (car (car tail-cdr)) key))
	  (setcdr tail (cdr tail-cdr))
	(setq tail tail-cdr))))
  alist)

(defun rassq-delete-all (value alist)
  "Delete from ALIST all elements whose cdr is `eq' to VALUE.
Return the modified alist.
Elements of ALIST that are not conses are ignored."
  (while (and (consp (car alist))
	      (eq (cdr (car alist)) value))
    (setq alist (cdr alist)))
  (let ((tail alist) tail-cdr)
    (while (setq tail-cdr (cdr tail))
      (if (and (consp (car tail-cdr))
	       (eq (cdr (car tail-cdr)) value))
	  (setcdr tail (cdr tail-cdr))
	(setq tail tail-cdr))))
  alist)

558 559 560 561 562 563 564 565 566
(defun alist-get (key alist &optional default remove)
  "Get the value associated to KEY in ALIST.
DEFAULT is the value to return if KEY is not found in ALIST.
REMOVE, if non-nil, means that when setting this element, we should
remove the entry if the new value is `eql' to DEFAULT."
  (ignore remove) ;;Silence byte-compiler.
  (let ((x (assq key alist)))
    (if x (cdr x) default)))

567 568 569 570 571 572 573 574 575 576
(defun remove (elt seq)
  "Return a copy of SEQ with all occurrences of ELT removed.
SEQ must be a list, vector, or string.  The comparison is done with `equal'."
  (if (nlistp seq)
      ;; If SEQ isn't a list, there's no need to copy SEQ because
      ;; `delete' will return a new object.
      (delete elt seq)
    (delete elt (copy-sequence seq))))

(defun remq (elt list)
577
  "Return LIST with all occurrences of ELT removed.
578 579
The comparison is done with `eq'.  Contrary to `delq', this does not use
side-effects, and the argument LIST is not modified."
580
  (while (and (eq elt (car list)) (setq list (cdr list))))
581 582 583
  (if (memq elt list)
      (delq elt (copy-sequence list))
    list))
584 585

;;;; Keymap support.
David Lawrence's avatar
David Lawrence committed
586

587 588 589 590 591 592 593
(defun kbd (keys)
  "Convert KEYS to the internal Emacs key representation.
KEYS should be a string constant in the format used for
saving keyboard macros (see `edmacro-mode')."
  ;; Don't use a defalias, since the `pure' property is only true for
  ;; the calling convention of `kbd'.
  (read-kbd-macro keys))
594
(put 'kbd 'pure t)
595

David Lawrence's avatar
David Lawrence committed
596
(defun undefined ()
597
  "Beep to tell the user this binding is undefined."
David Lawrence's avatar
David Lawrence committed
598
  (interactive)
599 600 601 602 603 604 605 606 607
  (ding)
  (message "%s is undefined" (key-description (this-single-command-keys)))
  (setq defining-kbd-macro nil)
  (force-mode-line-update)
  ;; If this is a down-mouse event, don't reset prefix-arg;
  ;; pass it to the command run by the up event.
  (setq prefix-arg
        (when (memq 'down (event-modifiers last-command-event))
          current-prefix-arg)))
David Lawrence's avatar
David Lawrence committed
608

609 610
;; Prevent the \{...} documentation construct
;; from mentioning keys that run this command.
David Lawrence's avatar
David Lawrence committed
611 612 613 614 615 616
(put 'undefined 'suppress-keymap t)

(defun suppress-keymap (map &optional nodigits)
  "Make MAP override all normally self-inserting keys to be undefined.
Normally, as an exception, digits and minus-sign are set to make prefix args,
but optional second arg NODIGITS non-nil treats them like other chars."
617
  (define-key map [remap self-insert-command] 'undefined)
David Lawrence's avatar
David Lawrence committed
618 619 620 621 622 623 624 625 626
  (or nodigits
      (let (loop)
	(define-key map "-" 'negative-argument)
	;; Make plain numbers do numeric args.
	(setq loop ?0)
	(while (<= loop ?9)
	  (define-key map (char-to-string loop) 'digit-argument)
	  (setq loop (1+ loop))))))

627 628 629 630 631 632 633 634 635 636 637 638 639 640
(defun make-composed-keymap (maps &optional parent)
  "Construct a new keymap composed of MAPS and inheriting from PARENT.
When looking up a key in the returned map, the key is looked in each
keymap of MAPS in turn until a binding is found.
If no binding is found in MAPS, the lookup continues in PARENT, if non-nil.
As always with keymap inheritance, a nil binding in MAPS overrides
any corresponding binding in PARENT, but it does not override corresponding
bindings in other keymaps of MAPS.
MAPS can be a list of keymaps or a single keymap.
PARENT if non-nil should be a keymap."
  `(keymap
    ,@(if (keymapp maps) (list maps) maps)
    ,@parent))

641
(defun define-key-after (keymap key definition &optional after)
642 643 644
  "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
This is like `define-key' except that the binding for KEY is placed
just after the binding for the event AFTER, instead of at the beginning
645 646 647
of the map.  Note that AFTER must be an event type (like KEY), NOT a command
\(like DEFINITION).

648
If AFTER is t or omitted, the new binding goes at the end of the keymap.
649
AFTER should be a single event type--a symbol or a character, not a sequence.
650

651
Bindings are always added before any inherited map.
652

653 654
The order of bindings in a keymap only matters when it is used as
a menu, so this function is not useful for non-menu keymaps."
655
  (unless after (setq after t))
656 657
  (or (keymapp keymap)
      (signal 'wrong-type-argument (list 'keymapp keymap)))
658 659 660 661 662 663 664
  (setq key
	(if (<= (length key) 1) (aref key 0)
	  (setq keymap (lookup-key keymap
				   (apply 'vector
					  (butlast (mapcar 'identity key)))))
	  (aref key (1- (length key)))))
  (let ((tail keymap) done inserted)
665 666
    (while (and (not done) tail)
      ;; Delete any earlier bindings for the same key.
667
      (if (eq (car-safe (car (cdr tail))) key)
668
	  (setcdr tail (cdr (cdr tail))))
669 670
      ;; If we hit an included map, go down that one.
      (if (keymapp (car tail)) (setq tail (car tail)))
671 672
      ;; When we reach AFTER's binding, insert the new binding after.
      ;; If we reach an inherited keymap, insert just before that.
673
      ;; If we reach the end of this keymap, insert at the end.
674 675
      (if (or (and (eq (car-safe (car tail)) after)
		   (not (eq after t)))
676 677
	      (eq (car (cdr tail)) 'keymap)
	      (null (cdr tail)))
678
	  (progn
679 680 681 682 683 684 685
	    ;; Stop the scan only if we find a parent keymap.
	    ;; Keep going past the inserted element
	    ;; so we can delete any duplications that come later.
	    (if (eq (car (cdr tail)) 'keymap)
		(setq done t))
	    ;; Don't insert more than once.
	    (or inserted
686
		(setcdr tail (cons (cons key definition) (cdr tail))))
687
	    (setq inserted t)))
688 689
      (setq tail (cdr tail)))))

690
(defun map-keymap-sorted (function keymap)
691 692
  "Implement `map-keymap' with sorting.
Don't call this function; it is for internal use only."
693 694 695 696 697 698 699 700 701 702 703 704 705 706
  (let (list)
    (map-keymap (lambda (a b) (push (cons a b) list))
                keymap)
    (setq list (sort list
                     (lambda (a b)
                       (setq a (car a) b (car b))
                       (if (integerp a)
                           (if (integerp b) (< a b)
                             t)
                         (if (integerp b) t
                           ;; string< also accepts symbols.
                           (string< a b))))))
    (dolist (p list)
      (funcall function (car p) (cdr p)))))
707

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
(defun keymap--menu-item-binding (val)
  "Return the binding part of a menu-item."
  (cond
   ((not (consp val)) val)              ;Not a menu-item.
   ((eq 'menu-item (car val))
    (let* ((binding (nth 2 val))
           (plist (nthcdr 3 val))
           (filter (plist-get plist :filter)))
      (if filter (funcall filter binding)
        binding)))
   ((and (consp (cdr val)) (stringp (cadr val)))
    (cddr val))
   ((stringp (car val))
    (cdr val))
   (t val)))                            ;Not a menu-item either.

(defun keymap--menu-item-with-binding (item binding)
  "Build a menu-item like ITEM but with its binding changed to BINDING."
  (cond
727
   ((not (consp item)) binding)		;Not a menu-item.
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
   ((eq 'menu-item (car item))
    (setq item (copy-sequence item))
    (let ((tail (nthcdr 2 item)))
      (setcar tail binding)
      ;; Remove any potential filter.
      (if (plist-get (cdr tail) :filter)
          (setcdr tail (plist-put (cdr tail) :filter nil))))
    item)
   ((and (consp (cdr item)) (stringp (cadr item)))
    (cons (car item) (cons (cadr item) binding)))
   (t (cons (car item) binding))))

(defun keymap--merge-bindings (val1 val2)
  "Merge bindings VAL1 and VAL2."
  (let ((map1 (keymap--menu-item-binding val1))
        (map2 (keymap--menu-item-binding val2)))
    (if (not (and (keymapp map1) (keymapp map2)))
        ;; There's nothing to merge: val1 takes precedence.
        val1
      (let ((map (list 'keymap map1 map2))
            (item (if (keymapp val1) (if (keymapp val2) nil val2) val1)))
        (keymap--menu-item-with-binding item map)))))

751
(defun keymap-canonicalize (map)
752 753 754 755 756 757 758 759 760 761
  "Return a simpler equivalent keymap.
This resolves inheritance and redefinitions.  The returned keymap
should behave identically to a copy of KEYMAP w.r.t `lookup-key'
and use in active keymaps and menus.
Subkeymaps may be modified but are not canonicalized."
  ;; FIXME: Problem with the difference between a nil binding
  ;; that hides a binding in an inherited map and a nil binding that's ignored
  ;; to let some further binding visible.  Currently a nil binding hides all.
  ;; FIXME: we may want to carefully (re)order elements in case they're
  ;; menu-entries.
762
  (let ((bindings ())
763 764
        (ranges ())
	(prompt (keymap-prompt map)))
765
    (while (keymapp map)
766
      (setq map (map-keymap ;; -internal
767 768 769 770 771 772
                 (lambda (key item)
                   (if (consp key)
                       ;; Treat char-ranges specially.
                       (push (cons key item) ranges)
                     (push (cons key item) bindings)))
                 map)))
773
    ;; Create the new map.
774
    (setq map (funcall (if ranges 'make-keymap 'make-sparse-keymap) prompt))
775
    (dolist (binding ranges)
776
      ;; Treat char-ranges specially.  FIXME: need to merge as well.
Stefan Monnier's avatar
Stefan Monnier committed
777
      (define-key map (vector (car binding)) (cdr binding)))
778
    ;; Process the bindings starting from the end.
779 780 781
    (dolist (binding (prog1 bindings (setq bindings ())))
      (let* ((key (car binding))
             (oldbind (assq key bindings)))
782 783 784 785 786 787 788 789
        (push (if (not oldbind)
                  ;; The normal case: no duplicate bindings.
                  binding
                ;; This is the second binding for this key.
                (setq bindings (delq oldbind bindings))
                (cons key (keymap--merge-bindings (cdr binding)
                                                  (cdr oldbind))))
              bindings)))
790 791
    (nconc map bindings)))

792 793
(put 'keyboard-translate-table 'char-table-extra-slots 0)

794
(defun keyboard-translate (from to)
795
  "Translate character FROM to TO on the current terminal.
796 797
This function creates a `keyboard-translate-table' if necessary
and then modifies one entry in it."
798 799 800
  (or (char-table-p keyboard-translate-table)
      (setq keyboard-translate-table
	    (make-char-table 'keyboard-translate-table nil)))
801 802
  (aset keyboard-translate-table from to))

803
;;;; Key binding commands.
804

805 806 807 808 809 810 811
(defun global-set-key (key command)
  "Give KEY a global binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a key sequence; noninteractively, it is a string or vector
of characters or event types, and non-ASCII characters with codes
above 127 (such as ISO Latin-1) can be included if you use a vector.
812

813 814 815 816 817 818 819
Note that if KEY has a local binding in the current buffer,
that local binding will continue to shadow any global binding
that you make with this function."
  (interactive "KSet key globally: \nCSet key %s to command: ")
  (or (vectorp key) (stringp key)
      (signal 'wrong-type-argument (list 'arrayp key)))
  (define-key (current-global-map) key command))
820

821 822 823 824 825 826 827
(defun local-set-key (key command)
  "Give KEY a local binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a key sequence; noninteractively, it is a string or vector
of characters or event types, and non-ASCII characters with codes
above 127 (such as ISO Latin-1) can be included if you use a vector.
828

Juanma Barranquero's avatar
Juanma Barranquero committed
829 830
The binding goes in the current buffer's local map, which in most
cases is shared with all other buffers in the same major mode."
831 832 833 834 835 836 837
  (interactive "KSet key locally: \nCSet key %s locally to command: ")
  (let ((map (current-local-map)))
    (or map
	(use-local-map (setq map (make-sparse-keymap))))
    (or (vectorp key) (stringp key)
	(signal 'wrong-type-argument (list 'arrayp key)))
    (define-key map key command)))
838

839 840 841 842 843
(defun global-unset-key (key)
  "Remove global binding of KEY.
KEY is a string or vector representing a sequence of keystrokes."
  (interactive "kUnset key globally: ")
  (global-set-key key nil))
844

845 846 847 848 849 850 851 852 853 854 855
(defun local-unset-key (key)
  "Remove local binding of KEY.
KEY is a string or vector representing a sequence of keystrokes."
  (interactive "kUnset key locally: ")
  (if (current-local-map)
      (local-set-key key nil))
  nil)

;;;; substitute-key-definition and its subroutines.

(defvar key-substitution-in-progress nil
Vinicius Jose Latorre's avatar
Vinicius Jose Latorre committed
856
  "Used internally by `substitute-key-definition'.")
857 858 859 860 861 862 863

(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
  "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
In other words, OLDDEF is replaced with NEWDEF where ever it appears.
Alternatively, if optional fourth argument OLDMAP is specified, we redefine
in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.

864 865
If you don't specify OLDMAP, you can usually get the same results
in a cleaner way with command remapping, like this:
Juanma Barranquero's avatar
Juanma Barranquero committed
866
  (define-key KEYMAP [remap OLDDEF] NEWDEF)
867
\n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
  ;; Don't document PREFIX in the doc string because we don't want to
  ;; advertise it.  It's meant for recursive calls only.  Here's its
  ;; meaning

  ;; If optional argument PREFIX is specified, it should be a key
  ;; prefix, a string.  Redefined bindings will then be bound to the
  ;; original key, with PREFIX added at the front.
  (or prefix (setq prefix ""))
  (let* ((scan (or oldmap keymap))
	 (prefix1 (vconcat prefix [nil]))
	 (key-substitution-in-progress
	  (cons scan key-substitution-in-progress)))
    ;; Scan OLDMAP, finding each char or event-symbol that
    ;; has any definition, and act on it with hack-key.
    (map-keymap
     (lambda (char defn)
       (aset prefix1 (length prefix) char)
       (substitute-key-definition-key defn olddef newdef prefix1 keymap))
     scan)))

(defun substitute-key-definition-key (defn olddef newdef prefix keymap)
  (let (inner-def skipped menu-item)
    ;; Find the actual command name within the binding.
    (if (eq (car-safe defn) 'menu-item)
	(setq menu-item defn defn (nth 2 defn))
      ;; Skip past menu-prompt.
      (while (stringp (car-safe defn))
	(push (pop defn) skipped))
      ;; Skip past cached key-equivalence data for menu items.
      (if (consp (car-safe defn))
	  (setq defn (cdr defn))))
    (if (or (eq defn olddef)
	    ;; Compare with equal if definition is a key sequence.
	    ;; That is useful for operating on function-key-map.
	    (and (or (stringp defn) (vectorp defn))
		 (equal defn olddef)))
	(define-key keymap prefix
	  (if menu-item
	      (let ((copy (copy-sequence menu-item)))
		(setcar (nthcdr 2 copy) newdef)
		copy)
	    (nconc (nreverse skipped) newdef)))
      ;; Look past a symbol that names a keymap.
      (setq inner-def
912
	    (or (indirect-function defn t) defn))
913 914 915 916 917 918 919 920 921 922 923 924
      ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
      ;; avoid autoloading a keymap.  This is mostly done to preserve the
      ;; original non-autoloading behavior of pre-map-keymap times.
      (if (and (keymapp inner-def)
	       ;; Avoid recursively scanning
	       ;; where KEYMAP does not have a submap.
	       (let ((elt (lookup-key keymap prefix)))
		 (or (null elt) (natnump elt) (keymapp elt)))
	       ;; Avoid recursively rescanning keymap being scanned.
	       (not (memq inner-def key-substitution-in-progress)))
	  ;; If this one isn't being scanned already, scan it now.
	  (substitute-key-definition olddef newdef keymap inner-def prefix)))))
925 926


Juanma Barranquero's avatar
Juanma Barranquero committed
927
;;;; The global keymap tree.
928

929 930
;; global-map, esc-map, and ctl-x-map have their values set up in
;; keymap.c; we just give them docstrings here.
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

(defvar global-map nil
  "Default global keymap mapping Emacs keyboard input into commands.
The value is a keymap which is usually (but not necessarily) Emacs's
global map.")

(defvar esc-map nil
  "Default keymap for ESC (meta) commands.
The normal global definition of the character ESC indirects to this keymap.")

(defvar ctl-x-map nil
  "Default keymap for C-x commands.
The normal global definition of the character C-x indirects to this keymap.")

(defvar ctl-x-4-map (make-sparse-keymap)
Pavel Janík's avatar
Pavel Janík committed
946
  "Keymap for subcommands of C-x 4.")
947
(defalias 'ctl-x-4-prefix ctl-x-4-map)
948 949 950 951
(define-key ctl-x-map "4" 'ctl-x-4-prefix)

(defvar ctl-x-5-map (make-sparse-keymap)
  "Keymap for frame commands.")
952
(defalias 'ctl-x-5-prefix ctl-x-5-map)
953 954
(define-key ctl-x-map "5" 'ctl-x-5-prefix)

955

956 957
;;;; Event manipulation functions.

958
(defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
959

960 961 962 963 964 965
(defun listify-key-sequence (key)
  "Convert a key sequence to a list of events."
  (if (vectorp key)
      (append key nil)
    (mapcar (function (lambda (c)
			(if (> c 127)
966
			    (logxor c listify-key-sequence-1)
967
			  c)))
968
	    key)))
969

970
(defun eventp (obj)
971
  "True if the argument is an event object."
972 973 974 975
  (when obj
    (or (integerp obj)
        (and (symbolp obj) obj (not (keywordp obj)))
        (and (consp obj) (symbolp (car obj))))))
976 977

(defun event-modifiers (event)
978
  "Return a list of symbols representing the modifier keys in event EVENT.
979
The elements of the list may include `meta', `control',
980
`shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
981 982 983
and `down'.
EVENT may be an event or an event type.  If EVENT is a symbol
that has never been used in an event that has been read as input
984 985
in the current Emacs session, then this function may fail to include
the `click' modifier."
986 987 988 989
  (let ((type event))
    (if (listp type)
	(setq type (car type)))
    (if (symbolp type)
990 991 992
        ;; Don't read event-symbol-elements directly since we're not
        ;; sure the symbol has already been parsed.
	(cdr (internal-event-symbol-parse-modifiers type))
993 994 995 996
      (let ((list nil)
	    (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
					       ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
	(if (not (zerop (logand type ?\M-\^@)))
997
	    (push 'meta list))
998 999
	(if (or (not (zerop (logand type ?\C-\^@)))
		(< char 32))
1000
	    (push 'control list))
1001 1002
	(if (or (not (zerop (logand type ?\S-\^@)))
		(/= char (downcase char)))
1003
	    (push 'shift list))
1004
	(or (zerop (logand type ?\H-\^@))
1005
	    (push 'hyper list))
1006
	(or (zerop (logand type ?\s-\^@))
1007
	    (push 'super list))
1008
	(or (zerop (logand type ?\A-\^@))
1009
	    (push 'alt list))
1010 1011
	list))))

1012
(defun event-basic-type (event)
1013
  "Return the basic type of the given event (all modifiers removed).
1014 1015 1016 1017
The value is a printing character (not upper case) or a symbol.
EVENT may be an event or an event type.  If EVENT is a symbol
that has never been used in an event that has been read as input
in the current Emacs session, then this function may return nil."
1018 1019
  (if (consp event)
      (setq event (car event)))
1020 1021
  (if (symbolp event)
      (car (get event 'event-symbol-elements))
1022 1023 1024 1025 1026 1027 1028
    (let* ((base (logand event (1- ?\A-\^@)))
	   (uncontrolled (if (< base 32) (logior base 64) base)))
      ;; There are some numbers that are invalid characters and
      ;; cause `downcase' to get an error.
      (condition-case ()
	  (downcase uncontrolled)
	(error uncontrolled)))))
1029

1030 1031
(defsubst mouse-movement-p (object)
  "Return non-nil if OBJECT is a mouse movement event."
1032
  (eq (car-safe object) 'mouse-movement))
1033

1034 1035 1036 1037 1038
(defun mouse-event-p (object)
  "Return non-nil if OBJECT is a mouse click event."
  ;; is this really correct? maybe remove mouse-movement?
  (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))

1039
(defun event-start (event)
1040
  "Return the starting position of EVENT.
1041 1042
EVENT should be a mouse click, drag, or key press event.  If
EVENT is nil, the value of `posn-at-point' is used instead.
1043 1044 1045 1046 1047 1048 1049 1050

The following accessor functions are used to access the elements
of the position:

`posn-window': The window the event is in.
`posn-area': A symbol identifying the area the event occurred in,
or nil if the event occurred in the text area.
`posn-point': The buffer position of the event.
Paul Eggert's avatar
Paul Eggert committed
1051
`posn-x-y': The pixel-based coordinates of the event.
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
`posn-col-row': The estimated column and row corresponding to the
position of the event.
`posn-actual-col-row': The actual column and row corresponding to the
position of the event.
`posn-string': The string object of the event, which is either
nil or (STRING . POSITION)'.
`posn-image': The image object of the event, if any.
`posn-object': The image or string object of the event, if any.
`posn-timestamp': The time the event occurred, in milliseconds.

For more information, see Info node `(elisp)Click Events'."
1063
  (if (consp event) (nth 1 event)
1064 1065
    (or (posn-at-point)
        (list (selected-window) (point) '(0 . 0) 0))))
1066

1067
(defun event-end (event)
1068
  "Return the ending position of EVENT.
Kenichi Handa's avatar
Kenichi Handa committed
1069
EVENT should be a click, drag, or key press event.
1070 1071

See `event-start' for a description of the value returned."
1072
  (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
1073 1074
    (or (posn-at-point)
        (list (selected-window) (point) '(0 . 0) 0))))
1075

1076 1077 1078
(defsubst event-click-count (event)
  "Return the multi-click count of EVENT, a click or drag event.
The return value is a positive integer."
1079
  (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
1080 1081

;;;; Extracting fields of the positions in an event.
1082

1083 1084 1085 1086 1087 1088 1089
(defun posnp (obj)
  "Return non-nil if OBJ appears to be a valid `posn' object."
  (and (windowp (car-safe obj))
       (atom (car-safe (setq obj (cdr obj))))                ;AREA-OR-POS.
       (integerp (car-safe (car-safe (setq obj (cdr obj))))) ;XOFFSET.
       (integerp (car-safe (cdr obj)))))                     ;TIMESTAMP.

1090 1091
(defsubst posn-window (position)
  "Return the window in POSITION.
Kenichi Handa's avatar
Kenichi Handa committed
1092 1093
POSITION should be a list of the form returned by the `event-start'
and `event-end' functions."
1094 1095
  (nth 0 position))

Kenichi Handa's avatar
Kenichi Handa committed
1096 1097 1098 1099 1100 1101 1102 1103 1104
(defsubst posn-area (position)
  "Return the window area recorded in POSITION, or nil for the text area.
POSITION should be a list of the form returned by the `event-start'
and `event-end' functions."
  (let ((area (if (consp (nth 1 position))
		  (car (nth 1 position))
		(nth 1 position))))
    (and (symbolp area) area)))

1105
(defun posn-point (position)
1106
  "Return the buffer location in POSITION.
Kenichi Handa's avatar
Kenichi Handa committed
1107
POSITION should be a list of the form returned by the `event-start'
1108 1109 1110
and `event-end' functions.
Returns nil if POSITION does not correspond to any buffer location (e.g.
a click on a scroll bar)."
Kenichi Handa's avatar
Kenichi Handa committed
1111
  (or (nth 5 position)
1112 1113 1114 1115
      (let ((pt (nth 1 position)))
        (or (car-safe pt)
            ;; Apparently this can also be `vertical-scroll-bar' (bug#13979).
            (if (integerp pt) pt)))))
Kenichi Handa's avatar
Kenichi Handa committed
1116 1117 1118 1119

(defun posn-set-point (position)
  "Move point to POSITION.
Select the corresponding window as well."
Vinicius Jose Latorre's avatar
Vinicius Jose Latorre committed
1120 1121 1122 1123 1124
  (if (not (windowp (posn-window position)))
      (error "Position not in text area of window"))
  (select-window (posn-window position))
  (if (numberp (posn-point position))
      (goto-char (posn-point position))))
1125