cl-lib.el 25.5 KB
Newer Older
1
;;; cl-lib.el --- Common Lisp extensions for Emacs  -*- lexical-binding: t -*-
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1993, 2001-2019 Free Software Foundation, Inc.
4 5

;; Author: Dave Gillespie <daveg@synaptics.com>
6
;; Version: 1.0
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
;; Keywords: extensions

;; This file is part of GNU Emacs.

;; GNU Emacs 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.

;; 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
22
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

;;; Commentary:

;; These are extensions to Emacs Lisp that provide a degree of
;; Common Lisp compatibility, beyond what is already built-in
;; in Emacs Lisp.
;;
;; This package was written by Dave Gillespie; it is a complete
;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
;;
;; Bug reports, comments, and suggestions are welcome!

;; This file contains the portions of the Common Lisp extensions
;; package which should always be present.


;;; Change Log:

;; Version 2.02 (30 Jul 93):
;;  * Added "cl-compat.el" file, extra compatibility with old package.
;;  * Added `lexical-let' and `lexical-let*'.
;;  * Added `define-modify-macro', `callf', and `callf2'.
;;  * Added `ignore-errors'.
;;  * Changed `(setf (nthcdr N PLACE) X)' to work when N is zero.
;;  * Merged `*gentemp-counter*' into `*gensym-counter*'.
;;  * Extended `subseq' to allow negative START and END like `substring'.
;;  * Added `in-ref', `across-ref', `elements of-ref' loop clauses.
;;  * Added `concat', `vconcat' loop clauses.
;;  * Cleaned up a number of compiler warnings.

;; Version 2.01 (7 Jul 93):
;;  * Added support for FSF version of Emacs 19.
;;  * Added `add-hook' for Emacs 18 users.
;;  * Added `defsubst*' and `symbol-macrolet'.
;;  * Added `maplist', `mapc', `mapl', `mapcan', `mapcon'.
;;  * Added `map', `concatenate', `reduce', `merge'.
;;  * Added `revappend', `nreconc', `tailp', `tree-equal'.
;;  * Added `assert', `check-type', `typecase', `typep', and `deftype'.
;;  * Added destructuring and `&environment' support to `defmacro*'.
;;  * Added destructuring to `loop', and added the following clauses:
;;      `elements', `frames', `overlays', `intervals', `buffers', `key-seqs'.
;;  * Renamed `delete' to `delete*' and `remove' to `remove*'.
;;  * Completed support for all keywords in `remove*', `substitute', etc.
;;  * Added `most-positive-float' and company.
;;  * Fixed hash tables to work with latest Lucid Emacs.
;;  * `proclaim' forms are no longer compile-time-evaluating; use `declaim'.
;;  * Syntax for `warn' declarations has changed.
;;  * Improved implementation of `random*'.
;;  * Moved most sequence functions to a new file, cl-seq.el.
;;  * Moved `eval-when' into cl-macs.el.
;;  * Moved `pushnew' and `adjoin' to cl.el for most common cases.
;;  * Moved `provide' forms down to ends of files.
;;  * Changed expansion of `pop' to something that compiles to better code.
;;  * Changed so that no patch is required for Emacs 19 byte compiler.
;;  * Made more things dependent on `optimize' declarations.
;;  * Added a partial implementation of struct print functions.
;;  * Miscellaneous minor changes.

;; Version 2.00:
;;  * First public release of this package.


;;; Code:

87
(require 'macroexp)
88

89 90
(defvar cl--optimize-speed 1)
(defvar cl--optimize-safety 1)
91

92 93 94
;;;###autoload
(define-obsolete-variable-alias
  ;; This alias is needed for compatibility with .elc files that use defstruct
95 96
  ;; and were compiled with Emacs<24.3.
  'custom-print-functions 'cl-custom-print-functions "24.3")
97 98 99 100 101 102 103 104 105 106 107 108 109 110

;;;###autoload
(defvar cl-custom-print-functions nil
  "This is a list of functions that format user objects for printing.
Each function is called in turn with three arguments: the object, the
stream, and the print level (currently ignored).  If it is able to
print the object it returns true; otherwise it returns nil and the
printer proceeds to the next function on the list.

This variable is not used at present, but it is defined in hopes that
a future Emacs interpreter will be able to use it.")

;;; Generalized variables.
;; These macros are defined here so that they
111
;; can safely be used in init files.
112

113
;;;###autoload
114 115
(defmacro cl-incf (place &optional x)
  "Increment PLACE by X (1 by default).
116
PLACE may be a symbol, or any generalized variable allowed by `setf'.
117 118 119 120 121 122 123 124
The return value is the incremented value of PLACE."
  (declare (debug (place &optional form)))
  (if (symbolp place)
      (list 'setq place (if x (list '+ place x) (list '1+ place)))
    (list 'cl-callf '+ place (or x 1))))

(defmacro cl-decf (place &optional x)
  "Decrement PLACE by X (1 by default).
125
PLACE may be a symbol, or any generalized variable allowed by `setf'.
126 127 128 129 130 131 132
The return value is the decremented value of PLACE."
  (declare (debug cl-incf))
  (if (symbolp place)
      (list 'setq place (if x (list '- place x) (list '1- place)))
    (list 'cl-callf '- place (or x 1))))

(defmacro cl-pushnew (x place &rest keys)
133
  "Add X to the list stored in PLACE unless X is already in the list.
134 135
PLACE is a generalized variable that stores a list.

136 137
Like (push X PLACE), except that PLACE is unmodified if X is `eql'
to an element already in the list stored in PLACE.
138

139 140 141 142 143 144 145 146
\nKeywords supported:  :test :test-not :key
\n(fn X PLACE [KEYWORD VALUE]...)"
  (declare (debug
            (form place &rest
                  &or [[&or ":test" ":test-not" ":key"] function-form]
                  [keywordp form])))
  (if (symbolp place)
      (if (null keys)
147 148 149 150 151 152 153 154 155
          (macroexp-let2 nil var x
            `(if (memql ,var ,place)
                 ;; This symbol may later on expand to actual code which then
                 ;; trigger warnings like "value unused" since cl-pushnew's
                 ;; return value is rarely used.  It should not matter that
                 ;; other warnings may be silenced, since `place' is used
                 ;; earlier and should have triggered them already.
                 (with-no-warnings ,place)
               (setq ,place (cons ,var ,place))))
156 157
	`(setq ,place (cl-adjoin ,x ,place ,@keys)))
    `(cl-callf2 cl-adjoin ,x ,place ,@keys)))
158

159
(defun cl--set-buffer-substring (start end val)
160 161 162 163 164
  (save-excursion (delete-region start end)
		  (goto-char start)
		  (insert val)
		  val))

165
(defun cl--set-substring (str start end val)
166 167 168 169 170 171 172 173 174 175
  (if end (if (< end 0) (cl-incf end (length str)))
    (setq end (length str)))
  (if (< start 0) (cl-incf start (length str)))
  (concat (and (> start 0) (substring str 0 start))
	  val
	  (and (< end (length str)) (substring str end))))


;;; Blocks and exits.

176 177
(defalias 'cl--block-wrapper 'identity)
(defalias 'cl--block-throw 'throw)
178 179 180 181 182 183 184


;;; Multiple values.
;; True multiple values are not supported, or even
;; simulated.  Instead, cl-multiple-value-bind and friends simply expect
;; the target form to return the values as a list.

185 186 187 188 189
(defun cl--defalias (cl-f el-f &optional doc)
  (defalias cl-f el-f doc)
  (put cl-f 'byte-optimizer 'byte-compile-inline-expand))

(cl--defalias 'cl-values #'list
190 191 192 193 194 195
  "Return multiple values, Common Lisp style.
The arguments of `cl-values' are the values
that the containing function should return.

\(fn &rest VALUES)")

196
(defun cl-values-list (list)
197
  "Return multiple values, Common Lisp style, taken from a list.
198 199 200 201 202 203 204 205
LIST specifies the list of values that the containing function
should return.

Note that Emacs Lisp doesn't really support multiple values, so
all this function does is return LIST."
  (unless (listp list)
    (signal 'wrong-type-argument list))
  list)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

(defsubst cl-multiple-value-list (expression)
  "Return a list of the multiple values produced by EXPRESSION.
This handles multiple values in Common Lisp style, but it does not
work right when EXPRESSION calls an ordinary Emacs Lisp function
that returns just one value."
  expression)

(defsubst cl-multiple-value-apply (function expression)
  "Evaluate EXPRESSION to get multiple values and apply FUNCTION to them.
This handles multiple values in Common Lisp style, but it does not work
right when EXPRESSION calls an ordinary Emacs Lisp function that returns just
one value."
  (apply function expression))

(defalias 'cl-multiple-value-call 'apply
  "Apply FUNCTION to ARGUMENTS, taking multiple values into account.
This implementation only handles the case where there is only one argument.")

225
(cl--defalias 'cl-nth-value #'nth
226 227 228
  "Evaluate EXPRESSION to get multiple values and return the Nth one.
This handles multiple values in Common Lisp style, but it does not work
right when EXPRESSION calls an ordinary Emacs Lisp function that returns just
229 230 231
one value.

\(fn N EXPRESSION)")
232 233 234

;;; Declarations.

235 236 237
(defvar cl--compiling-file nil)
(defun cl--compiling-file ()
  (or cl--compiling-file
238 239 240 241 242
      (and (boundp 'byte-compile--outbuffer)
           (bufferp (symbol-value 'byte-compile--outbuffer))
	   (equal (buffer-name (symbol-value 'byte-compile--outbuffer))
		  " *Compiler Output*"))))

243
(defvar cl--proclaims-deferred nil)
244 245

(defun cl-proclaim (spec)
Glenn Morris's avatar
Glenn Morris committed
246
  "Record a global declaration specified by SPEC."
247 248
  (if (fboundp 'cl--do-proclaim) (cl--do-proclaim spec t)
    (push spec cl--proclaims-deferred))
249 250 251
  nil)

(defmacro cl-declaim (&rest specs)
Glenn Morris's avatar
Glenn Morris committed
252 253 254
  "Like `cl-proclaim', but takes any number of unevaluated, unquoted arguments.
Puts `(cl-eval-when (compile load eval) ...)' around the declarations
so that they are registered at compile-time as well as run-time."
255
  (let ((body (mapcar (lambda (x) `(cl-proclaim ',x)) specs)))
256 257
    (if (cl--compiling-file) `(cl-eval-when (compile load eval) ,@body)
      `(progn ,@body))))           ; Avoid loading cl-macs.el for cl-eval-when.
258 259 260 261


;;; Numbers.

262
(define-obsolete-function-alias 'cl-floatp-safe 'floatp "24.4")
263

264
(defsubst cl-plusp (number)
265 266 267
  "Return t if NUMBER is positive."
  (> number 0))

268
(defsubst cl-minusp (number)
269 270 271 272 273 274 275 276 277 278 279
  "Return t if NUMBER is negative."
  (< number 0))

(defun cl-oddp (integer)
  "Return t if INTEGER is odd."
  (eq (logand integer 1) 1))

(defun cl-evenp (integer)
  "Return t if INTEGER is even."
  (eq (logand integer 1) 0))

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
(defconst cl-digit-char-table
  (let* ((digits (make-vector 256 nil))
         (populate (lambda (start end base)
                     (mapc (lambda (i)
                             (aset digits i (+ base (- i start))))
                           (number-sequence start end)))))
    (funcall populate ?0 ?9 0)
    (funcall populate ?A ?Z 10)
    (funcall populate ?a ?z 10)
    digits))

(defun cl-digit-char-p (char &optional radix)
  "Test if CHAR is a digit in the specified RADIX (default 10).
If true return the decimal value of digit CHAR in RADIX."
  (or (<= 2 (or radix 10) 36)
      (signal 'args-out-of-range (list 'radix radix '(2 36))))
  (let ((n (aref cl-digit-char-table char)))
    (and n (< n (or radix 10)) n)))

299 300 301
(defconst cl-most-positive-float nil
  "The largest value that a Lisp float can hold.
If your system supports infinities, this is the largest finite value.
302
For Emacs, this equals 1.7976931348623157e+308.
303 304 305 306 307 308 309 310 311
Call `cl-float-limits' to set this.")

(defconst cl-most-negative-float nil
  "The largest negative value that a Lisp float can hold.
This is simply -`cl-most-positive-float'.
Call `cl-float-limits' to set this.")

(defconst cl-least-positive-float nil
  "The smallest value greater than zero that a Lisp float can hold.
312 313
For Emacs, this equals 5e-324 if subnormal numbers are supported,
`cl-least-positive-normalized-float' if they are not.
314 315 316 317 318 319 320 321 322
Call `cl-float-limits' to set this.")

(defconst cl-least-negative-float nil
  "The smallest value less than zero that a Lisp float can hold.
This is simply -`cl-least-positive-float'.
Call `cl-float-limits' to set this.")

(defconst cl-least-positive-normalized-float nil
  "The smallest normalized Lisp float greater than zero.
323 324
This is the smallest value that has full precision.
For Emacs, this equals 2.2250738585072014e-308.
325 326 327 328 329 330 331 332 333 334
Call `cl-float-limits' to set this.")

(defconst cl-least-negative-normalized-float nil
  "The smallest normalized Lisp float less than zero.
This is simply -`cl-least-positive-normalized-float'.
Call `cl-float-limits' to set this.")

(defconst cl-float-epsilon nil
  "The smallest positive float that adds to 1.0 to give a distinct value.
Adding a number less than this to 1.0 returns 1.0 due to roundoff.
335
For Emacs, this equals 2.220446049250313e-16.
336 337 338 339
Call `cl-float-limits' to set this.")

(defconst cl-float-negative-epsilon nil
  "The smallest positive float that subtracts from 1.0 to give a distinct value.
340
For Emacs, this equals 1.1102230246251565e-16.
341 342 343 344 345
Call `cl-float-limits' to set this.")


;;; Sequence functions.

346
(cl--defalias 'cl-copy-seq 'copy-sequence)
347

348
(declare-function cl--mapcar-many "cl-extra" (cl-func cl-seqs &optional acc))
349 350 351 352 353 354 355 356 357 358

(defun cl-mapcar (cl-func cl-x &rest cl-rest)
  "Apply FUNCTION to each element of SEQ, and make a list of the results.
If there are several SEQs, FUNCTION is called with that many arguments,
and mapping stops as soon as the shortest list runs out.  With just one
SEQ, this is like `mapcar'.  With several, it is like the Common Lisp
`mapcar' function extended to arbitrary sequence types.
\n(fn FUNCTION SEQ...)"
  (if cl-rest
      (if (or (cdr cl-rest) (nlistp cl-x) (nlistp (car cl-rest)))
359
	  (cl--mapcar-many cl-func (cons cl-x cl-rest) 'accumulate)
360 361 362 363 364 365
	(let ((cl-res nil) (cl-y (car cl-rest)))
	  (while (and cl-x cl-y)
	    (push (funcall cl-func (pop cl-x) (pop cl-y)) cl-res))
	  (nreverse cl-res)))
    (mapcar cl-func cl-x)))

366
(cl--defalias 'cl-svref 'aref)
367 368 369

;;; List functions.

370 371 372
(cl--defalias 'cl-first 'car)
(cl--defalias 'cl-second 'cadr)
(cl--defalias 'cl-rest 'cdr)
373

374 375
(cl--defalias 'cl-third 'cl-caddr "Return the third element of the list X.")
(cl--defalias 'cl-fourth 'cl-cadddr "Return the fourth element of the list X.")
376

377 378
(defsubst cl-fifth (x)
  "Return the fifth element of the list X."
Stefan Monnier's avatar
Stefan Monnier committed
379
  (declare (gv-setter (lambda (store) `(setcar (nthcdr 4 ,x) ,store))))
380 381
  (nth 4 x))

382 383
(defsubst cl-sixth (x)
  "Return the sixth element of the list X."
Stefan Monnier's avatar
Stefan Monnier committed
384
  (declare (gv-setter (lambda (store) `(setcar (nthcdr 5 ,x) ,store))))
385 386
  (nth 5 x))

387 388
(defsubst cl-seventh (x)
  "Return the seventh element of the list X."
Stefan Monnier's avatar
Stefan Monnier committed
389
  (declare (gv-setter (lambda (store) `(setcar (nthcdr 6 ,x) ,store))))
390 391
  (nth 6 x))

392 393
(defsubst cl-eighth (x)
  "Return the eighth element of the list X."
Stefan Monnier's avatar
Stefan Monnier committed
394
  (declare (gv-setter (lambda (store) `(setcar (nthcdr 7 ,x) ,store))))
395 396
  (nth 7 x))

397 398
(defsubst cl-ninth (x)
  "Return the ninth element of the list X."
Stefan Monnier's avatar
Stefan Monnier committed
399
  (declare (gv-setter (lambda (store) `(setcar (nthcdr 8 ,x) ,store))))
400 401
  (nth 8 x))

402 403
(defsubst cl-tenth (x)
  "Return the tenth element of the list X."
Stefan Monnier's avatar
Stefan Monnier committed
404
  (declare (gv-setter (lambda (store) `(setcar (nthcdr 9 ,x) ,store))))
405 406
  (nth 9 x))

Mark Oteiza's avatar
Mark Oteiza committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
(defalias 'cl-caaar 'caaar)
(defalias 'cl-caadr 'caadr)
(defalias 'cl-cadar 'cadar)
(defalias 'cl-caddr 'caddr)
(defalias 'cl-cdaar 'cdaar)
(defalias 'cl-cdadr 'cdadr)
(defalias 'cl-cddar 'cddar)
(defalias 'cl-cdddr 'cdddr)
(defalias 'cl-caaaar 'caaaar)
(defalias 'cl-caaadr 'caaadr)
(defalias 'cl-caadar 'caadar)
(defalias 'cl-caaddr 'caaddr)
(defalias 'cl-cadaar 'cadaar)
(defalias 'cl-cadadr 'cadadr)
(defalias 'cl-caddar 'caddar)
(defalias 'cl-cadddr 'cadddr)
(defalias 'cl-cdaaar 'cdaaar)
(defalias 'cl-cdaadr 'cdaadr)
(defalias 'cl-cdadar 'cdadar)
(defalias 'cl-cdaddr 'cdaddr)
(defalias 'cl-cddaar 'cddaar)
(defalias 'cl-cddadr 'cddadr)
(defalias 'cl-cdddar 'cdddar)
(defalias 'cl-cddddr 'cddddr)
431 432 433 434 435 436 437 438 439 440 441 442

;;(defun last* (x &optional n)
;;  "Returns the last link in the list LIST.
;;With optional argument N, returns Nth-to-last link (default 1)."
;;  (if n
;;      (let ((m 0) (p x))
;;	(while (consp p) (cl-incf m) (pop p))
;;	(if (<= n 0) p
;;	  (if (< n m) (nthcdr (- m n) x) x)))
;;    (while (consp (cdr x)) (pop x))
;;    x))

443
(defun cl-list* (arg &rest rest)
444 445 446 447
  "Return a new list with specified ARGs as elements, consed to last ARG.
Thus, `(cl-list* A B C D)' is equivalent to `(nconc (list A B C) D)', or to
`(cons A (cons B (cons C D)))'.
\n(fn ARG...)"
448
  (declare (compiler-macro cl--compiler-macro-list*))
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  (cond ((not rest) arg)
	((not (cdr rest)) (cons arg (car rest)))
	(t (let* ((n (length rest))
		  (copy (copy-sequence rest))
		  (last (nthcdr (- n 2) copy)))
	     (setcdr last (car (cdr last)))
	     (cons arg copy)))))

(defun cl-ldiff (list sublist)
  "Return a copy of LIST with the tail SUBLIST removed."
  (let ((res nil))
    (while (and (consp list) (not (eq list sublist)))
      (push (pop list) res))
    (nreverse res)))

(defun cl-copy-list (list)
  "Return a copy of LIST, which may be a dotted list.
The elements of LIST are not copied, just the list structure itself."
  (if (consp list)
      (let ((res nil))
	(while (consp list) (push (pop list) res))
	(prog1 (nreverse res) (setcdr res list)))
    (car list)))

;; Autoloaded, but we have not loaded cl-loaddefs yet.
(declare-function cl-floor "cl-extra" (x &optional y))
(declare-function cl-ceiling "cl-extra" (x &optional y))
(declare-function cl-truncate "cl-extra" (x &optional y))
(declare-function cl-round "cl-extra" (x &optional y))
(declare-function cl-mod "cl-extra" (x y))

480
(defun cl-adjoin (cl-item cl-list &rest cl-keys)
481 482 483 484
  "Return ITEM consed onto the front of LIST only if it's not already there.
Otherwise, return LIST unmodified.
\nKeywords supported:  :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
485
  (declare (compiler-macro cl--compiler-macro-adjoin))
486 487 488 489 490 491 492 493 494 495 496 497 498 499
  (cond ((or (equal cl-keys '(:test eq))
	     (and (null cl-keys) (not (numberp cl-item))))
	 (if (memq cl-item cl-list) cl-list (cons cl-item cl-list)))
	((or (equal cl-keys '(:test equal)) (null cl-keys))
	 (if (member cl-item cl-list) cl-list (cons cl-item cl-list)))
	(t (apply 'cl--adjoin cl-item cl-list cl-keys))))

(defun cl-subst (cl-new cl-old cl-tree &rest cl-keys)
  "Substitute NEW for OLD everywhere in TREE (non-destructively).
Return a copy of TREE with all elements `eql' to OLD replaced by NEW.
\nKeywords supported:  :test :test-not :key
\n(fn NEW OLD TREE [KEYWORD VALUE]...)"
  (if (or cl-keys (and (numberp cl-old) (not (integerp cl-old))))
      (apply 'cl-sublis (list (cons cl-old cl-new)) cl-tree cl-keys)
500
    (cl--do-subst cl-new cl-old cl-tree)))
501

502
(defun cl--do-subst (cl-new cl-old cl-tree)
503 504
  (cond ((eq cl-tree cl-old) cl-new)
	((consp cl-tree)
505 506
	 (let ((a (cl--do-subst cl-new cl-old (car cl-tree)))
	       (d (cl--do-subst cl-new cl-old (cdr cl-tree))))
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	   (if (and (eq a (car cl-tree)) (eq d (cdr cl-tree)))
	       cl-tree (cons a d))))
	(t cl-tree)))

(defun cl-acons (key value alist)
  "Add KEY and VALUE to ALIST.
Return a new list with (cons KEY VALUE) as car and ALIST as cdr."
  (cons (cons key value) alist))

(defun cl-pairlis (keys values &optional alist)
  "Make an alist from KEYS and VALUES.
Return a new alist composed by associating KEYS to corresponding VALUES;
the process stops as soon as KEYS or VALUES run out.
If ALIST is non-nil, the new pairs are prepended to it."
  (nconc (cl-mapcar 'cons keys values) alist))

Stefan Monnier's avatar
Stefan Monnier committed
523 524 525 526 527 528 529 530 531 532
;;; Generalized variables.

;; These used to be in cl-macs.el since all macros that use them (like setf)
;; were autoloaded from cl-macs.el.  But now that setf, push, and pop are in
;; core Elisp, they need to either be right here or be autoloaded via
;; cl-loaddefs.el, which is more trouble than it is worth.

;; Some more Emacs-related place types.
(gv-define-simple-setter buffer-file-name set-visited-file-name t)
(gv-define-setter buffer-modified-p (flag &optional buf)
533 534 535
  (macroexp-let2 nil buffer `(or ,buf (current-buffer))
    `(with-current-buffer ,buffer
       (set-buffer-modified-p ,flag))))
Stefan Monnier's avatar
Stefan Monnier committed
536 537
(gv-define-simple-setter buffer-name rename-buffer t)
(gv-define-setter buffer-string (store)
538
  `(insert (prog1 ,store (erase-buffer))))
Stefan Monnier's avatar
Stefan Monnier committed
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
(gv-define-simple-setter buffer-substring cl--set-buffer-substring)
(gv-define-simple-setter current-buffer set-buffer)
(gv-define-simple-setter current-column move-to-column t)
(gv-define-simple-setter current-global-map use-global-map t)
(gv-define-setter current-input-mode (store)
  `(progn (apply #'set-input-mode ,store) ,store))
(gv-define-simple-setter current-local-map use-local-map t)
(gv-define-simple-setter current-window-configuration
                         set-window-configuration t)
(gv-define-simple-setter default-file-modes set-default-file-modes t)
(gv-define-simple-setter documentation-property put)
(gv-define-setter face-background (x f &optional s)
  `(set-face-background ,f ,x ,s))
(gv-define-setter face-background-pixmap (x f &optional s)
  `(set-face-background-pixmap ,f ,x ,s))
(gv-define-setter face-font (x f &optional s) `(set-face-font ,f ,x ,s))
(gv-define-setter face-foreground (x f &optional s)
  `(set-face-foreground ,f ,x ,s))
(gv-define-setter face-underline-p (x f &optional s)
558
  `(set-face-underline ,f ,x ,s))
Stefan Monnier's avatar
Stefan Monnier committed
559
(gv-define-simple-setter file-modes set-file-modes t)
560 561
(gv-define-setter frame-height (x &optional frame)
  `(set-frame-height (or ,frame (selected-frame)) ,x))
Stefan Monnier's avatar
Stefan Monnier committed
562 563
(gv-define-simple-setter frame-parameters modify-frame-parameters t)
(gv-define-simple-setter frame-visible-p cl--set-frame-visible-p)
564 565
(gv-define-setter frame-width (x &optional frame)
  `(set-frame-width (or ,frame (selected-frame)) ,x))
Stefan Monnier's avatar
Stefan Monnier committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
(gv-define-simple-setter getenv setenv t)
(gv-define-simple-setter get-register set-register)
(gv-define-simple-setter global-key-binding global-set-key)
(gv-define-simple-setter local-key-binding local-set-key)
(gv-define-simple-setter mark set-mark t)
(gv-define-simple-setter mark-marker set-mark t)
(gv-define-simple-setter marker-position set-marker t)
(gv-define-setter mouse-position (store scr)
  `(set-mouse-position ,scr (car ,store) (cadr ,store)
                       (cddr ,store)))
(gv-define-simple-setter point goto-char)
(gv-define-simple-setter point-marker goto-char t)
(gv-define-setter point-max (store)
  `(progn (narrow-to-region (point-min) ,store) ,store))
(gv-define-setter point-min (store)
  `(progn (narrow-to-region ,store (point-max)) ,store))
(gv-define-setter read-mouse-position (store scr)
  `(set-mouse-position ,scr (car ,store) (cdr ,store)))
(gv-define-simple-setter screen-height set-screen-height t)
(gv-define-simple-setter screen-width set-screen-width t)
(gv-define-simple-setter selected-window select-window)
(gv-define-simple-setter selected-screen select-screen)
(gv-define-simple-setter selected-frame select-frame)
(gv-define-simple-setter standard-case-table set-standard-case-table)
(gv-define-simple-setter syntax-table set-syntax-table)
(gv-define-simple-setter visited-file-modtime set-visited-file-modtime t)
(gv-define-setter window-height (store)
  `(progn (enlarge-window (- ,store (window-height))) ,store))
(gv-define-setter window-width (store)
  `(progn (enlarge-window (- ,store (window-width)) t) ,store))
(gv-define-simple-setter x-get-secondary-selection x-own-secondary-selection t)

;; More complex setf-methods.

;; This is a hack that allows (setf (eq a 7) B) to mean either
;; (setq a 7) or (setq a nil) depending on whether B is nil or not.
;; This is useful when you have control over the PLACE but not over
;; the VALUE, as is the case in define-minor-mode's :variable.
;; It turned out that :variable needed more flexibility anyway, so
;; this doesn't seem too useful now.
(gv-define-expander eq
  (lambda (do place val)
    (gv-letplace (getter setter) place
      (macroexp-let2 nil val val
        (funcall do `(eq ,getter ,val)
                 (lambda (v)
                   `(cond
                     (,v ,(funcall setter val))
                     ((eq ,getter ,val) ,(funcall setter `(not ,val))))))))))

(gv-define-expander substring
  (lambda (do place from &optional to)
    (gv-letplace (getter setter) place
Leo Liu's avatar
Leo Liu committed
619 620 621 622 623
      (macroexp-let2* nil ((start from) (end to))
        (funcall do `(substring ,getter ,start ,end)
                 (lambda (v)
                   (funcall setter `(cl--set-substring
                                     ,getter ,start ,end ,v))))))))
Stefan Monnier's avatar
Stefan Monnier committed
624

625 626 627
;;; Miscellaneous.

(provide 'cl-lib)
628 629 630 631
(unless (load "cl-loaddefs" 'noerror 'quiet)
  ;; When bootstrapping, cl-loaddefs hasn't been built yet!
  (require 'cl-macs)
  (require 'cl-seq))
632

633
(defun cl--old-struct-type-of (orig-fun object)
634
  (or (and (vectorp object) (> (length object) 0)
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
           (let ((tag (aref object 0)))
             (when (and (symbolp tag)
                        (string-prefix-p "cl-struct-" (symbol-name tag)))
               (unless (eq (symbol-function tag)
                           :quick-object-witness-check)
                 ;; Old-style old-style struct:
                 ;; Convert to new-style old-style struct!
                 (let* ((type (intern (substring (symbol-name tag)
                                                 (length "cl-struct-"))))
                        (class (cl--struct-get-class type)))
                   ;; If the `cl-defstruct' was recompiled after the code
                   ;; which constructed `object', `cl--struct-get-class' may
                   ;; not have called `cl-struct-define' and setup the tag
                   ;; symbol for us.
                   (unless (eq (symbol-function tag)
                               :quick-object-witness-check)
                     (set tag class)
                     (fset tag :quick-object-witness-check))))
               (cl--class-name (symbol-value tag)))))
      (funcall orig-fun object)))

;;;###autoload
(define-minor-mode cl-old-struct-compat-mode
  "Enable backward compatibility with old-style structs.
This can be needed when using code byte-compiled using the old
macro-expansion of `cl-defstruct' that used vectors objects instead
of record objects."
  :global t
  (cond
   (cl-old-struct-compat-mode
    (advice-add 'type-of :around #'cl--old-struct-type-of))
   (t
    (advice-remove 'type-of #'cl--old-struct-type-of))))

669
;;; cl-lib.el ends here