pub const PRELUDE: &str = r#"
;; declare: a no-op at runtime (specs are advisory; defun/lambda ignore them).
;; Defined first so that every later definition may carry one.
(defmacro declare (&rest _specs) nil)
;;; backquote.el. The reader makes `X, ,X and ,@X into (\` X), (\, X) and
;;; (\,@ X), as Emacs's does; these macros expand them through
;;; `backquote-process' (src/backquote.rs). Defined first because every later
;;; macro in this prelude is written with backquote.
(defun backquote-list*-function (first &rest list)
(if list
(let* ((rest list) (newlist (cons first nil)) (last newlist))
(while (cdr rest)
(setcdr last (cons (car rest) nil))
(setq last (cdr last)
rest (cdr rest)))
(setcdr last (car rest))
newlist)
first))
;; backquote.el reverses with `nreverse', which this prelude defines later;
;; the list is freshly consed, so `reverse' is indistinguishable.
(defmacro backquote-list*-macro (first &rest list)
(setq list (reverse (cons first list))
first (car list)
list (cdr list))
(if list
(let* ((second (car list))
(rest (cdr list))
(newlist (list 'cons second first)))
(while rest
(setq newlist (list 'cons (car rest) newlist)
rest (cdr rest)))
newlist)
first))
(fset 'backquote-list* (symbol-function 'backquote-list*-macro))
(defconst backquote-backquote-symbol '\`)
(defconst backquote-unquote-symbol '\,)
(defconst backquote-splice-symbol '\,@)
(defmacro backquote (structure)
(cdr (backquote-process structure)))
(fset '\` (symbol-function 'backquote))
;;; The c[ad]+r family (caar .. cddddr) is Rust subrs: src/builtins.rs `cxr`.
;; Regexp matching folds case unless this is let-bound to nil (Emacs default t).
(defvar case-fold-search t)
;; subr.el's default SEPARATORS for `split-string'. Space, formfeed, tab,
;; newline, carriage return, vertical tab -- ASCII only, deliberately not
;; "whitespace" in the Unicode sense. The Rust subr carries the same literal
;; (`SPLIT_STRING_DEFAULT_SEPARATORS' in src/builtins.rs); this defvar exists so
;; Lisp can read and rebind it, as subr.el's does.
(defvar split-string-default-separators "[ \f\t\n\r\v]+")
;;; ---- build/system identity (C-level vars from emacs.c, verified against
;;; ---- GNU Emacs 30.2) ----
;; `emacs-version' is a C variable (Vemacs_version). We track the emulated
;; Emacs release the prelude is faithful to.
(defconst emacs-version "30.2")
;; `emacs-major-version'/`emacs-minor-version' are derived in lisp/version.el
;; exactly like this; kept here because version.el is not preloaded.
(defconst emacs-major-version
(progn (string-match "^[0-9]+" emacs-version)
(string-to-number (match-string 0 emacs-version))))
(defconst emacs-minor-version
(progn (string-match "^[0-9]+\\.\\([0-9]+\\)" emacs-version)
(string-to-number (match-string 1 emacs-version))))
;; `emacs-build-system'/`emacs-build-time'/`emacs-build-number' are defined in
;; lisp/version.el exactly like this (minus the Android build branches, which
;; never apply here); kept here because version.el is not preloaded. Because
;; `emacs-build-system' is non-nil, `emacs-build-time' is a `current-time'
;; timestamp, matching a normally-dumped `emacs -Q --batch'.
;;
;; version.el evaluates that `(current-time)' while the binary is being DUMPED,
;; so the value is a constant of the build and every run of one Emacs reports
;; the same list. elisprs has no dump step, so `--build-time--' supplies the
;; corresponding fixed point (the executable's mtime); calling `current-time'
;; here instead gave a different answer on every invocation.
(defconst emacs-build-system (system-name))
(defconst emacs-build-time (if emacs-build-system (--build-time--)))
(defconst emacs-build-number 1)
;; `system-type' (Vsystem_type) is platform-derived; the Rust primitive maps the
;; running OS to Emacs's symbol (darwin/gnu-linux/berkeley-unix/windows-nt).
(defvar system-type (--system-type--))
;; No GUI and non-interactive batch execution, matching `emacs -Q --batch'.
(defvar window-system nil)
(defvar noninteractive t)
;; `temporary-file-directory' is defined below, right after
;; `file-name-as-directory', which its initializer depends on.
;;; ---- numeric helpers ----
;; Fixnum bounds match GNU Emacs on a 64-bit build (62-bit tagged integers).
(defconst most-positive-fixnum 2305843009213693951)
(defconst most-negative-fixnum -2305843009213693952)
(defconst float-pi 3.141592653589793)
(defconst float-e 2.718281828459045)
(defconst pi 3.141592653589793)
;; `abs` is a primitive subr (keeps int/float type; (abs -0.0) => 0.0).
;; NaN propagates: any NaN arg makes the result NaN (a NaN never wins `>`/`<`,
;; so once it lands in the accumulator no later value can displace it).
;; `mod` is a primitive subr (handles float operands + divisor-sign semantics).
(defun /= (a b) (not (= a b)))
(defun plusp (x) (> x 0))
(defun minusp (x) (< x 0))
(defun cl-plusp (x) (> x 0))
(defun cl-minusp (x) (< x 0))
;; zerop is a byte-compiled defsubst from subr.el in Emacs -- NOT a C subr
;; ((subrp (symbol-function 'zerop)) => nil) -- so a wrong argument count is
;; caught by exec_byte_code and signalled as ((MANDATORY . NONREST) NARGS):
;; (wrong-number-of-arguments (1 . 1) 2), never as #<subr zerop>. Take &rest
;; and reproduce that exact shape, like cl-evenp/cl-oddp below; the body is
;; subr.el's (= 0 number), whose own `=' supplies number-or-marker-p errors.
;; This defun shadows the native subr registered in builtins.rs.
(defun zerop (&rest args)
(unless (= (length args) 1)
(signal 'wrong-number-of-arguments (list (cons 1 1) (length args))))
(= 0 (car args)))
(defun evenp (x) (zerop (% x 2)))
(defun oddp (x) (not (zerop (% x 2))))
;; natnump is a native subr (builtins.rs): it is a C subr in Emacs, so its
;; error objects must carry `#<subr natnump>`, not a closure.
(defun wholenump (x) (natnump x))
;;; ---- list construction / access ----
;; `nthcdr' is a Rust subr (src/builtins.rs `nthcdr_fn'), ported from fns.c
;; `Fnthcdr'. The elisp definition it replaces counted N down in a `while' loop,
;; which neither accepted a bignum N nor terminated on a circular LIST —
;; (nthcdr 4611686018427387903 CYCLE) spun forever where Emacs answers in
;; constant time via Brent's tortoise plus a modulo reduction.
(defun last (l &optional n)
;; The last N cons cells of L (default 1): (last '(1 2 3) 2) => (2 3).
;; Guard on consp so an improper tail stops the walk instead of erroring:
;; (last '(1 2 . 3)) => (2 . 3).
(cond
;; A non-list has no cons cells to take: Emacs returns it unchanged --
;; (last t) and (last t 0) are both t.
((not (consp l)) l)
;; subr.el: `(nthcdr (1- (safe-length list)) list)'. Walking `cdr' until
;; it stops being a cons never terminated on a circular list; `safe-length'
;; does, so `(last CYCLE)' answers the same cell Emacs does.
((null n) (nthcdr (1- (safe-length l)) l))
;; `safe-length', not `length': an improper list has no `length' (it signals
;; `wrong-type-argument listp TAIL'), so `(last (cons "z" 1.5) 7)' errored
;; where Emacs answers the whole improper list, `("z" . 1.5)'. The two agree
;; on every proper list.
(t (nthcdr (max 0 (- (safe-length l) n)) l))))
(defun number-sequence (from &optional to inc)
;; With only FROM, or FROM=TO, the sequence is (FROM); INC defaults to 1.
(if (or (null to) (= from to))
(list from)
(setq inc (or inc 1))
;; A zero increment would loop forever; Emacs signals instead.
(when (= inc 0) (error "The increment can not be zero"))
(let ((r nil))
(if (< inc 0)
(while (>= from to) (setq r (cons from r)) (setq from (+ from inc)))
(while (<= from to) (setq r (cons from r)) (setq from (+ from inc))))
(reverse r))))
(defun safe-length (l)
;; Length of a possibly circular or dotted list, never erroring or looping
;; forever. Faithful to Emacs 30.2's FOR_EACH_TAIL_SAFE (Brent's teleporting
;; tortoise/hare, lisp.h): the tortoise jumps to the current tail after
;; 2, 4, 8, ... steps and a cycle is reported when the tail meets it, so a
;; circular list returns an integer >= the number of distinct cells -- a
;; 3-cycle => 5, exactly as Emacs. (safe-length '(1 2 . 3)) => 2.
(let ((tail l) (tortoise l) (interval 2) (q 2) (len 0) (done nil))
(while (and (consp tail) (not done))
(setq len (1+ len) tail (cdr tail))
(if (not (consp tail))
(setq done t)
(setq q (1- q))
(if (> q 0)
(when (eq tail tortoise) (setq done t))
(setq interval (* interval 2) q interval tortoise tail))))
len))
;; fns.c `length_internal': LEN is the C `int' parameter, so a fixnum LENGTH
;; is truncated to 32 bits on the way in. Walking a list that is no longer
;; than LEN conses returns what is left of LEN; reaching zero returns -1. A
;; LEN of #xffff or more walks with FOR_EACH_TAIL, which signals on a cycle.
(defun length--internal (sequence len)
(setq len (logand len #xffffffff))
(when (>= len #x80000000) (setq len (- len #x100000000)))
(when (>= len #xffff)
;; `length' signals `(circular-list SEQUENCE)' as FOR_EACH_TAIL does.
(condition-case nil (length sequence) (wrong-type-argument nil)))
(catch 'length--done
(while (consp sequence)
(when (<= (setq len (1- len)) 0) (throw 'length--done -1))
(setq sequence (cdr sequence)))
len))
(defun length< (sequence length)
(unless (fixnump length) (signal 'wrong-type-argument (list 'fixnump length)))
(if (consp sequence)
(not (= (length--internal sequence length) -1))
(< (length sequence) length)))
(defun length> (sequence length)
(unless (fixnump length) (signal 'wrong-type-argument (list 'fixnump length)))
(if (consp sequence)
(= (length--internal sequence (1+ length)) -1)
(> (length sequence) length)))
(defun length= (sequence length)
(unless (fixnump length) (signal 'wrong-type-argument (list 'fixnump length)))
(cond ((< length 0) nil)
((consp sequence) (= (length--internal sequence (1+ length)) 1))
(t (= (length sequence) length))))
(defun car-safe (x) (if (consp x) (car x) nil))
(defun cdr-safe (x) (if (consp x) (cdr x) nil))
(defun caar-safe (x) (if (consp x) (car x) nil))
;;; ---- membership / search ----
;; `memq'/`memql'/`member'/`assq'/`assoc'/`rassq'/`rassoc'/`mapconcat' are C
;; subrs in fns.c, and are Rust subrs here (see `builtins::TailWalk'). They were
;; prelude `defun's, whose bare `while (consp l)' walk had no cycle check and so
;; ran forever on a circular list where Emacs signals `circular-list'.
(defun assoc-string (key alist &optional case-fold)
;; First ALIST element equal to KEY as a string (elements may be strings or
;; (STRING . VALUE) conses); CASE-FOLD ignores case. A matched element may
;; itself be nil (e.g. key nil over (... nil)), so track a separate DONE
;; flag like C `Fassoc_string' returning ELT directly -- looping on
;; (not r) spins forever when r is set to nil.
(let ((k (if (symbolp key) (symbol-name key) key)) (r nil) (done nil))
(while (and (consp alist) (not done))
(let* ((el (car alist))
(raw (if (consp el) (car el) el))
(s (if (symbolp raw) (symbol-name raw) raw)))
(if (and (stringp s)
(if case-fold (string-equal-ignore-case k s) (string= k s)))
(setq r el done t)
(setq alist (cdr alist)))))
r))
(defun alist-get (k al &optional default _remove testfn)
;; Value associated with K in alist AL (DEFAULT if absent); TESTFN overrides eq.
(let ((p (if testfn (assoc k al testfn) (assq k al))))
(if p (cdr p) default)))
(defun plist-get (pl k &optional predicate)
;; Fplist_get walks with FOR_EACH_TAIL_SAFE and never signals: it breaks as
;; soon as the cdr is not a cons -- BEFORE testing the key -- so an improper
;; or odd plist just answers nil: (plist-get '(1 . 2) 1) => nil,
;; (plist-get '(1) 1) => nil, (plist-get 5 1) => nil.
(let ((test (or predicate #'eq)) (r nil))
(while (and (consp pl) (consp (cdr pl)))
(if (funcall test (car pl) k) (progn (setq r (cadr pl)) (setq pl nil))
(setq pl (cddr pl))))
r))
(defun plist-member (pl k &optional predicate)
;; Fplist_member tests the key FIRST, then steps by two, breaking mid-step
;; when the odd-position cdr is not a cons; CHECK_TYPE at the end names the
;; WHOLE plist under `plistp': (plist-member '(1 . 2) 1) => (1 . 2), but
;; (plist-member '(1 . 2) 2) => (wrong-type-argument plistp (1 . 2)) and
;; (plist-member 5 1) => (wrong-type-argument plistp 5).
(let ((test (or predicate #'eq)) (tail pl) (r nil) (done nil))
(while (and (not done) (consp tail))
(if (funcall test (car tail) k) (setq r tail done t)
(progn (setq tail (cdr tail))
(if (consp tail) (setq tail (cdr tail)) (setq done t)))))
(unless (or r (null tail))
(signal 'wrong-type-argument (list 'plistp pl)))
r))
;;; ---- higher-order / sequence ----
;; seq-* accept any sequence; coerce list/vector/string to a list to iterate.
(defun seq-reduce (f l init) (setq l (append l nil)) (while l (setq init (funcall f init (car l))) (setq l (cdr l))) init)
(defun seq-map (f l) (mapcar f l))
(defun seq-each (f l) (mapc f l))
(defun seq-filter (pred l)
(setq l (append l nil))
(let ((r nil)) (while l (if (funcall pred (car l)) (setq r (cons (car l) r))) (setq l (cdr l))) (reverse r)))
(defun seq-remove (pred l) (seq-filter (lambda (e) (not (funcall pred e))) l))
(defun seq-find (pred l &optional default)
(setq l (append l nil))
(let ((res default)) (while l (if (funcall pred (car l)) (progn (setq res (car l)) (setq l nil)) (setq l (cdr l)))) res))
(defun seq-some (pred l) (setq l (append l nil)) (let ((r nil)) (while (and l (not r)) (setq r (funcall pred (car l))) (setq l (cdr l))) r))
(defun seq-every-p (pred l) (setq l (append l nil)) (let ((r t)) (while (and l r) (setq r (funcall pred (car l))) (setq l (cdr l))) r))
(defun seq-count (pred l) (setq l (append l nil)) (let ((n 0)) (while l (if (funcall pred (car l)) (setq n (1+ n))) (setq l (cdr l))) n))
(defun seq-empty-p (l) (= 0 (length l)))
(defun seq-length (l) (length l))
;; seq.el: `seq-copy' is `copy-sequence' and `seq-random-elt' indexes a random
;; position, refusing an empty sequence with seq.el's own message.
(defun seq-copy (sequence) (copy-sequence sequence))
(defun seq-random-elt (sequence)
(if (seq-empty-p sequence)
(error "Sequence cannot be empty")
(seq-elt sequence (random (seq-length sequence)))))
;; `seq-elt' is `(cl-defgeneric seq-elt (sequence n) (elt sequence n))' in
;; seq.el and Emacs ships seq.elc, so the body that actually runs is the
;; byte-compiled one -- and the byte compiler emits the `Belt' opcode for
;; `(elt SEQ N)' rather than a call to `Felt'. `Belt' does NOT delegate to
;; `Felt' for a cons with a small non-negative index: it walks the cdrs inline
;; and reports the TAIL it choked on, where `Felt' -> `Fnthcdr' reports the
;; original list (bytecode.c:1578-1599 vs fns.c:1755-1866 on emacs-30):
;;
;; (elt (cons "" 'sym) 2) => (wrong-type-argument listp ("" . sym))
;; (seq-elt (cons "" 'sym) 2) => (wrong-type-argument listp sym)
;;
;; The fast path is guarded by `RANGED_FIXNUMP (0, v2, SMALL_LIST_LEN_MAX)' --
;; SMALL_LIST_LEN_MAX is 127 (lisp.h) -- so a negative, bignum or >127 index
;; falls through to `elt' exactly as the opcode falls through to `Felt', and so
;; does every non-cons sequence. A cons walk that lands on nil answers nil.
(defun seq-elt (l n)
(if (and (consp l) (integerp n) (>= n 0) (<= n 127))
(let ((tail l) (k n))
(while (and (> k 0) (consp tail))
(setq tail (cdr tail))
(setq k (1- k)))
(cond ((consp tail) (car tail))
((null tail) nil)
(t (signal 'wrong-type-argument (list 'listp tail)))))
(elt l n)))
(defun seq-do (f l) (mapc f l))
(defun seqp (object) (sequencep object))
(defun seq-contains-p (seq elt &optional testfn)
(let ((test (or testfn #'equal)) (l (append seq nil)) (r nil))
(while (and l (not r)) (when (funcall test elt (car l)) (setq r t)) (setq l (cdr l)))
r))
(defun seq-reverse (l) (reverse l))
;;; ---- set-ish list ops ----
(defun remove (elt seq)
;; subr.el: (delete elt (if (nlistp seq) seq (copy-sequence seq))) -- a
;; dotted list dies inside `copy-sequence' naming the TAIL, and a
;; non-sequence inside `delete' naming itself under `sequencep'.
(delete elt (if (nlistp seq) seq (copy-sequence seq))))
(defun remq (elt list)
;; subr.el: cdr past `eq' matches at the head (a non-cons LIST signals
;; `listp' via `car'), then copy -- (delq ELT (copy-sequence LIST)) -- only
;; when a match remains. `memq' names the WHOLE (post-skip) list on a dotted
;; tail; `copy-sequence' names the TAIL.
(while (and (eq elt (car list)) (setq list (cdr list))))
(if (memq elt list)
(delq elt (copy-sequence list))
list))
;; `Fstring_to_multibyte': a unibyte string is converted into a fresh multibyte
;; one without the original's properties; a multibyte one is returned as is.
;; Strings carry no unibyte flag here, so an all-ASCII one stands for unibyte.
(defun string-to-multibyte (s)
(if (and (stringp s) (string-match-p "\\`[[:ascii:]]*\\'" s))
(substring-no-properties s)
s))
(defun string-as-multibyte (s) s)
(defun string-to-unibyte (s &rest _) s)
(defun string-as-unibyte (s) s)
(defun multibyte-string-p (s)
;; Approximate Emacs: a string is "multibyte" if it has any non-ASCII char.
(let ((l (and (stringp s) (string-to-list s))) (r nil))
(while (and l (not r)) (when (>= (car l) 128) (setq r t)) (setq l (cdr l)))
r))
;; delete/delq remove matching elements destructively (splicing cons cells) for
;; lists; delete filters vectors/strings into a fresh copy.
(defun delete (elt seq)
;; Fdelete: vectors and strings filter into a fresh copy; a cons/nil walks
;; like Fdelq with `equal', where CHECK_LIST_END names SEQ as rebound by any
;; head removals -- (delete "a" '("a" . [1 2])) => (wrong-type-argument
;; listp [1 2]) but with "b" the data is the whole dotted list. Anything
;; else is not a sequence at all.
(cond
((vectorp seq)
(vconcat (seq-filter (lambda (e) (not (equal e elt))) (append seq nil))))
((stringp seq)
(concat (seq-filter (lambda (e) (not (equal e elt))) (append seq nil))))
((not (listp seq)) (signal 'wrong-type-argument (list 'sequencep seq)))
(t
(let ((tail seq) (prev nil))
(while (consp tail)
(if (equal elt (car tail))
(if (null prev) (setq seq (cdr tail)) (setcdr prev (cdr tail)))
(setq prev tail))
(setq tail (cdr tail)))
(unless (null tail)
(signal 'wrong-type-argument (list 'listp seq)))
seq))))
(defun delq (elt list)
;; Fdelq: the same walk with `eq'; CHECK_LIST_END names LIST as rebound by
;; head removals, so (delq 'a (cons 'a 5)) => (wrong-type-argument listp 5)
;; while (delq 'x (cons 'a 5)) names the whole (a . 5).
(let ((tail list) (prev nil))
(while (consp tail)
(if (eq elt (car tail))
(if (null prev) (setq list (cdr tail)) (setcdr prev (cdr tail)))
(setq prev tail))
(setq tail (cdr tail)))
(unless (null tail)
(signal 'wrong-type-argument (list 'listp list)))
list))
(defun delete-dups (l)
;; Destructively remove `equal' duplicates, keeping the first occurrence.
;; subr.el sizes a hash table with (length list) FIRST, which is what makes a
;; non-list signal sequencep and a dotted list signal listp on its tail:
;; (delete-dups 'sym) => (wrong-type-argument sequencep sym).
(length l)
(let ((tail l))
(while tail
(setcdr tail (delete (car tail) (cdr tail)))
(setq tail (cdr tail))))
l)
(defun nconc (&rest args)
;; Faithful Fnconc: nil arguments are skipped; every argument but the last
;; must be a cons (CHECK_CONS => `consp', not `listp': (nconc 0 '(1)) =>
;; wrong-type-argument consp 0); each argument's cons spine is walked to its
;; LAST CONS -- a dotted tail is simply overwritten, never an error, so
;; (nconc '(1) '(2 . 3) '(4)) => (1 2 4) -- and spliced onto the next
;; argument. The last argument is never validated and becomes the final cdr.
(let ((val nil))
(while args
(let ((tem (car args)))
(when tem
(when (null val) (setq val tem))
(when (cdr args)
(unless (consp tem)
(signal 'wrong-type-argument (list 'consp tem)))
(let ((tail tem))
(while (consp (cdr tail)) (setq tail (cdr tail)))
(setcdr tail (cadr args))
;; Fnconc: when the NEXT arg is nil, substitute the tail cons we
;; just spliced so the following iteration keeps extending it.
(when (null (cadr args)) (setcar (cdr args) tail))))))
(setq args (cdr args)))
val))
(defun rassq-delete-all (value alist)
;; Faithful subr.el port (destructive): drop leading matches by advancing
;; ALIST, then setcdr out interior ones. `(car alist)' on a non-list is what
;; signals: (rassq-delete-all "x" -1) => (wrong-type-argument listp -1).
(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)
;;; ---- cl-lib niceties ----
(defun cl-first (l) (car l))
(defun cl-second (l) (cadr l))
(defun cl-third (l) (caddr l))
(defun cl-rest (l) (cdr l))
;; data.c `Finteractive_form' and eval.c `Fcommandp'. A macro's function cell
;; is `(macro . FN)' in Emacs, a cons whose car is not `lambda', so neither
;; treats one as a command. A primitive's `intspec' is recorded by
;; `--set-subr-intspec' below. Not modelled: loading an autoload to read its
;; form, and the OClosure `oclosure-interactive-form' delegation.
(defun interactive-form (cmd)
(let ((fun (indirect-function cmd)) (found nil) (spec nil))
(when fun
(setq fun cmd)
(while (and (not found) (symbolp fun))
(let ((tmp (get fun 'interactive-form)))
(if tmp
(setq found t spec tmp)
(setq fun (symbol-function fun)))))
(cond
(found spec)
((subrp fun)
(let ((spec (--subr-intspec fun)))
(and spec (list 'interactive spec))))
((and (closurep fun) (> (length fun) 5))
(let ((form (aref fun 5)))
(list 'interactive (if (vectorp form) (aref form 0) form))))
((eq (car-safe fun) 'lambda)
(let ((spec (assq 'interactive (cdr (cdr fun)))))
(if (null (cdr (cdr spec)))
spec
(list 'interactive (car (cdr spec))))))))))
(defun commandp (function &optional for-call-interactively)
(let ((fun (indirect-function function)))
(cond
((null fun) nil)
((subrp fun) (and (--subr-intspec fun) t))
((closurep fun) (> (length fun) 5))
((or (stringp fun) (vectorp fun)) (null for-call-interactively))
((not (consp fun)) nil)
((eq (car fun) 'autoload)
(if (car (cdr (cdr (cdr fun)))) t
(setq fun function)
(while (symbolp fun)
(when (get fun 'interactive-form)
(error "Found an 'interactive-form' property!"))
(setq fun (symbol-function fun)))
nil))
((eq (car fun) 'lambda)
(and (assq 'interactive (cdr-safe (cdr fun))) t))
(t nil))))
;; The primitives that are commands, with their DEFUN intspecs (Emacs 31.1;
;; `search-forward-regexp' / `search-backward-regexp' share the `re-search-*'
;; subr objects).
(--set-subr-intspec 'backward-char "^p")
(--set-subr-intspec 'beginning-of-line "^p")
(--set-subr-intspec 'copy-file "fCopy file: \nGCopy %s to file: \np\nP")
(--set-subr-intspec 'delete-char "p\nP")
(--set-subr-intspec 'delete-region "r")
(--set-subr-intspec 'end-of-line "^p")
(--set-subr-intspec 'erase-buffer "*")
(--set-subr-intspec 'forward-char "^p")
(--set-subr-intspec 'forward-line "^p")
(--set-subr-intspec 'forward-word "^p")
(--set-subr-intspec 'goto-char '(goto-char--read-natnum-interactive "Go to char: "))
(--set-subr-intspec 'indent-to "NIndent to column: ")
(--set-subr-intspec 'insert-char '(list (read-char-by-name "Insert character (Unicode name or hex): ") (prefix-numeric-value current-prefix-arg) t))
(--set-subr-intspec 'kill-buffer "bKill buffer: ")
(--set-subr-intspec 'kill-local-variable "vKill Local Variable: ")
(--set-subr-intspec 'make-local-variable "vMake Local Variable: ")
(--set-subr-intspec 'make-variable-buffer-local "vMake Variable Buffer Local: ")
(--set-subr-intspec 'move-to-column "NMove to column: ")
(--set-subr-intspec 'narrow-to-region "r")
(--set-subr-intspec 're-search-backward "sRE search backward: ")
(--set-subr-intspec 're-search-forward "sRE search: ")
(--set-subr-intspec 'rename-buffer '(list (read-string "Rename buffer (to new name): " nil 'buffer-name-history (buffer-name (current-buffer))) current-prefix-arg))
(--set-subr-intspec 'rename-file "fRename file: \nGRename %s to file: \np")
(--set-subr-intspec 'search-backward "MSearch backward: ")
(--set-subr-intspec 'search-forward "MSearch: ")
(--set-subr-intspec 'widen "")
(--set-subr-intspec 'write-region "r\nFWrite region to file: \ni\ni\ni\np")
(defun plistp (l)
(let ((n 0)) (while (consp l) (setq n (1+ n)) (setq l (cdr l))) (and (null l) (= 0 (% n 2)))))
;; Port of cl-some/cl-every from cl-extra.el: with extra SEQs (or a non-list
;; SEQ) map PRED over the sequences in parallel, stopping at the shortest.
(defun cl-some (pred seq &rest rest)
(if (or rest (nlistp seq))
(catch 'cl-some
(apply (function cl-map) nil
(lambda (&rest x)
(let ((res (apply pred x)))
(if res (throw 'cl-some res))))
seq rest)
nil)
(let ((x nil))
(while (and seq (not (setq x (funcall pred (car seq))))) (setq seq (cdr seq)))
x)))
(defun cl-every (pred seq &rest rest)
(if (or rest (nlistp seq))
(catch 'cl-every
(apply (function cl-map) nil
(lambda (&rest x) (or (apply pred x) (throw 'cl-every nil)))
seq rest)
t)
(while (and seq (funcall pred (car seq))) (setq seq (cdr seq)))
(null seq)))
(defun cl-notany (pred seq &rest rest) (not (apply (function cl-some) pred seq rest)))
(defun cl-notevery (pred seq &rest rest) (not (apply (function cl-every) pred seq rest)))
(defun cl-copy-list (list)
(if (consp list)
(let ((res nil))
(while (consp list) (setq res (cons (car list) res) list (cdr list)))
(prog1 (nreverse res) (setcdr res list)))
(car list)))
(defun cl-revappend (l tail) (append (reverse l) tail))
(defun cl-nreconc (l tail) (nconc (nreverse l) tail))
(defmacro cl-nth-value (n form) (list 'nth n form))
(defun cl-subst (new old tree &rest keys)
;; With no keywords, substitute OLD (matched by `eql') throughout TREE. When
;; :test/:test-not/:key are given, defer to `cl-sublis' exactly like Emacs, so
;; the predicate is applied to every node — conses included.
(if keys
(apply 'cl-sublis (list (cons old new)) tree keys)
(cond ((eql tree old) new)
((consp tree) (cons (cl-subst new old (car tree)) (cl-subst new old (cdr tree))))
(t tree))))
;; NOTE: `push'/`dolist' are defined later in this file, so these helpers use
;; explicit `while'/`setq'/`cons' loops to stay valid at load time.
;; cl-extra.el's `cl-maplist' / `cl-mapl' / `cl-mapcon' / `cl-mapc', verbatim
;; but for `push'/`pop' (not yet defined here). With several LISTs they step
;; every list at once and stop at the first that runs out.
(defun cl-maplist (func list &rest rest)
(if rest
(let ((res nil) (args (cons list (copy-sequence rest))) p)
(while (not (memq nil args))
(setq res (cons (apply func args) res))
(setq p args)
(while p (setcar p (cdr (car p))) (setq p (cdr p))))
(nreverse res))
(let ((res nil))
(while list
(setq res (cons (funcall func list) res))
(setq list (cdr list)))
(nreverse res))))
(defun cl-mapl (func list &rest rest)
(if rest
(let ((args (cons list (copy-sequence rest))) p)
(while (not (memq nil args))
(apply func args)
(setq p args)
(while p (setcar p (cdr (car p))) (setq p (cdr p)))))
(let ((p list))
(while p (funcall func p) (setq p (cdr p)))))
list)
(defun cl-mapcon (func list &rest rest)
(apply (function nconc) (apply (function cl-maplist) func list rest)))
;; `cl-mapc' returns SEQ, not the results. Two lists step together in lisp; any
;; other shape goes through `cl-mapcar', which already handles mixed sequence
;; types (cl--mapcar-many without the accumulator).
(defun cl-mapc (func seq &rest rest)
(if rest
(if (or (cdr rest) (nlistp seq) (nlistp (car rest)))
(progn (apply (function cl-mapcar) func seq rest) seq)
(let ((x seq) (y (car rest)))
(while (and x y)
(funcall func (car x) (car y))
(setq x (cdr x) y (cdr y)))
seq))
(mapc func seq)))
;; cl-lib.el aliases and one-liners (`defalias' is defined further down, and
;; is `fset' here).
(fset (quote cl-copy-seq) (function copy-sequence))
(fset (quote cl-svref) (function aref))
(fset (quote cl-multiple-value-call) (function apply))
(defun cl-multiple-value-list (expression) expression)
(defun cl-multiple-value-apply (function expression) (apply function expression))
;; cl-extra.el: the property is read through `cl-getf' so DEF is honoured;
;; setf on it is `put' (its gv-setter declaration).
(defun cl-get (sym tag &optional def) (cl-getf (symbol-plist sym) tag def))
;; cl-lib.el's `cl-adjoin', verbatim. The two fast paths are not an
;; optimization detail — they are the contract, because `memq'/`member' walk the
;; list themselves: with no keys and a non-numeric ITEM the walk is `memq', so
;; `(cl-adjoin "" t)' is `(wrong-type-argument listp t)' where a `seq-some'
;; paraphrase reported `sequencep'.
(defun cl-adjoin (cl-item cl-list &rest cl-keys)
(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))))
;;; ---- misc functions ----
(defun ignore (&rest _args) nil)
(defun always (&rest _args) t)
;; `default-value'/`set-default' are C primitives (builtins.rs) that read/write
;; the global (default) value cell, bypassing any buffer-local binding.
(defmacro setq-default (&rest args)
(let ((forms nil))
(while args
(setq forms (cons (list 'set-default (list 'quote (car args)) (cadr args)) forms))
(setq args (cddr args)))
(cons 'progn (nreverse forms))))
;; Printer limits: special so `(let ((print-length N)) …)` binds them dynamically
;; where the Rust printer can read them.
(defvar print-length nil)
(defvar print-level nil)
(defvar print-escape-newlines nil)
(defvar print-escape-control-characters nil)
(defvar print-escape-multibyte nil)
(defvar print-integers-as-characters nil)
(defvar print-quoted t)
(defvar float-output-format nil)
;; Without this `defvar' a `(let ((print-circle t)) …)' binds a LEXICAL `print-circle'
;; that the Rust printer — which reads the symbol's dynamic value cell — never sees,
;; so shared structure printed unlabelled and a circular list had nothing to stop it.
(defvar print-circle nil)
;; print.c `print-gensym': non-nil prints an uninterned symbol as `#:NAME'.
(defvar print-gensym nil)
;; lread.c `read-circle': nil makes `#N=' and `#N#' invalid syntax; special so
;; that a `let' of it reaches the reader.
(defvar read-circle t)
;; print.c `standard-output': where a print primitive given a nil PRINTCHARFUN
;; sends its output. t is stdout in batch; a buffer, marker or function is
;; honoured exactly as when passed as PRINTCHARFUN.
(defvar standard-output t)
(defvar gensym-counter 0)
;; subr.el: PREFIX is spliced with %s, so a symbol prefix works too.
(defun gensym (&optional prefix)
(let ((num (prog1 gensym-counter
(setq gensym-counter (1+ gensym-counter)))))
(make-symbol (format "%s%d" (or prefix "g") num))))
;; `keywordp' is a subr (see `builtins::install'): the test is not the spelling
;; but whether the symbol is the one the standard obarray holds, which only the
;; host can answer.
;;; ---- control macros ----
(defmacro prog2 (a b &rest body) (declare (indent 2) (debug t)) (list (quote progn) a (cons (quote prog1) (cons b body))))
;; ---- read-modify-write places (push/pop/incf/decf/cl-callf) ----
;;
;; Every one of these mentions PLACE at least twice: once to read it, once to
;; write it. Substituting the place FORM at each mention re-evaluates its
;; subforms, which Emacs never does — gv.el binds them with `gv-letplace' before
;; building either half. The divergence is a wrong *number of side effects*:
;;
;; (let ((n 0) (l (list 1 2))) (cl-incf (car (progn (setq n (1+ n)) l))) n)
;; => 1 in Emacs, was 2 here
;; (let ((n 0) (l (list 1 2 3))) (pop (cdr (progn (setq n (1+ n)) l))) n)
;; => 1 in Emacs, was 3 here (`pop' mentions the place three times)
;;
;; `setf--place-once' rebuilds PLACE over temporaries, and every macro below
;; goes through it — one implementation of the rule, not five.
(defun setf--copyable-p (x)
;; `macroexp-copyable-p', inlined because these macros are defined long before
;; macroexp.el is: a symbol or a constant costs nothing to duplicate; anything
;; else (a call) must be bound.
(not (and (consp x) (not (memq (car x) (quote (quote function)))))))
(defun setf--bind1 (form)
;; (BINDINGS . REF) for one subform: no binding at all when it is copyable.
(if (setf--copyable-p form) (cons nil form)
(let ((tmp (make-symbol "v"))) (cons (list (list tmp form)) tmp))))
(defun setf--place-once (place)
;; (BINDINGS . PLACE') where PLACE' names each of PLACE's subforms once.
;;
;; A *symbol* subform is deliberately left as itself, exactly as gv.el does:
;; re-reading a variable has no side effect, and some setters assign to the
;; subform itself — `(setf (nthcdr 0 l) v)' is `(setq l v)' — which a
;; temporary would silently redirect away from the caller's variable.
(if (not (consp place)) (cons nil place)
(let ((binds nil) (args nil) (rest (cdr place)) (b nil))
(while rest
(setq b (setf--bind1 (car rest)))
(setq binds (append binds (car b)))
(setq args (cons (cdr b) args))
(setq rest (cdr rest)))
(cons binds (cons (car place) (nreverse args))))))
(defun setf--rmw (place newval)
;; Code setting PLACE to (funcall NEWVAL GETTER), evaluating PLACE's subforms
;; exactly once. NEWVAL is a function of the getter form.
(if (symbolp place)
(list (quote setq) place (funcall newval place))
(let* ((b (setf--place-once place)) (p (cdr b)))
(list (quote let*) (car b) (list (quote setf) p (funcall newval p))))))
(defmacro incf (place &rest amt)
(setf--rmw place (lambda (g) (list (quote +) g (if amt (car amt) 1)))))
(defmacro decf (place &rest amt)
(setf--rmw place (lambda (g) (list (quote -) g (if amt (car amt) 1)))))
;; push: cons X onto PLACE. A plain variable uses setq; a generalized place
;; (e.g. (cdr l), (nth 1 l), (gethash k h)) goes through setf. X is bound first,
;; so it is evaluated before the place's subforms — subr.el's `macroexp-let2' on
;; NEWELT wraps the `gv-letplace' the same way round.
(defmacro push (x place)
(if (symbolp place)
(list (quote setq) place (list (quote cons) x place))
(let* ((xb (setf--bind1 x))
(b (setf--place-once place))
(p (cdr b)))
(list (quote let*) (append (car xb) (car b))
(list (quote setf) p (list (quote cons) (cdr xb) p))))))
;; setf: assign to a generalized place. Supports a plain variable and the
;; common cons/sequence/hash/symbol places; multiple place/value pairs expand
;; left-to-right.
(defmacro setf (&rest pairs)
(if (null pairs)
nil
(let ((place (car pairs)) (val (cadr pairs)) (rest (cddr pairs)))
(let ((exp
(if (consp place)
(let ((head (car place)) (args (cdr place)))
(cond
((eq head 'car) `(setcar ,(car args) ,val))
((eq head 'cdr) `(setcdr ,(car args) ,val))
((eq head 'caar) `(setcar (car ,(car args)) ,val))
((eq head 'cadr) `(setcar (cdr ,(car args)) ,val))
((eq head 'cddr) `(setcdr (cdr ,(car args)) ,val))
((eq head 'nth) `(setcar (nthcdr ,(car args) ,(cadr args)) ,val))
((eq head 'nthcdr) `(setcdr (nthcdr (1- ,(car args)) ,(cadr args)) ,val))
((eq head 'elt)
`(if (listp ,(car args))
(setcar (nthcdr ,(cadr args) ,(car args)) ,val)
(aset ,(car args) ,(cadr args) ,val)))
((eq head 'aref) `(aset ,(car args) ,(cadr args) ,val))
((eq head 'gethash) `(puthash ,(car args) ,val ,(cadr args)))
((eq head 'symbol-value) `(set ,(car args) ,val))
((eq head 'alist-get) `(setcdr (assq ,(car args) ,(cadr args)) ,val))
(t (signal 'gv-invalid-place (list place)))))
`(setq ,place ,val))))
(if rest `(progn ,exp (setf ,@rest)) exp)))))
;; subr.el: `(car-safe (prog1 PLACE (setq PLACE (cdr PLACE))))'. The `car-safe'
;; is load-bearing, not decoration — `(pop x)' on a non-list yields nil in Emacs
;; instead of signalling `wrong-type-argument', which is what a plain `car' does.
(defmacro pop (place)
(if (symbolp place)
(list (quote car-safe)
(list (quote prog1) place (list (quote setq) place (list (quote cdr) place))))
(let* ((b (setf--place-once place)) (p (cdr b)))
(list (quote let*) (car b)
(list (quote car-safe)
(list (quote prog1) p (list (quote setf) p (list (quote cdr) p))))))))
(defmacro dolist (spec &rest body)
(declare (indent 1) (debug ((symbolp form &optional form) body)))
;; (dolist (VAR LIST [RESULT]) BODY...) — RESULT is the value of the form; nil
;; if omitted.
;;
;; subr.el binds VAR with a `let' INSIDE the loop, so each iteration gets a
;; FRESH binding. That is observable under lexical binding: a closure made in
;; the body captures that iteration's value, so
;; (let (r) (dolist (x '(1 2 3) r) (push (lambda () x) r)) (mapcar #'funcall r))
;; is (3 2 1) in Emacs. Hoisting VAR into the enclosing `let' and `setq'ing it
;; per iteration — what this used to do — gives every closure the same cell, so
;; the same form answered (nil nil nil).
;;
;; The tail variable is uninterned (`make-symbol') exactly as in subr.el, so a
;; body that itself mentions a variable named `tail' is not captured by it.
(let ((var (car spec)) (lst (cadr spec)) (result (cddr spec))
(tail (make-symbol "tail")))
`(let ((,tail ,lst))
(while ,tail
(let ((,var (car ,tail)))
,@body
(setq ,tail (cdr ,tail))))
,@result)))
(defmacro dotimes (spec &rest body)
(declare (indent 1) (debug dolist))
;; (dotimes (VAR COUNT [RESULT]) BODY...) — RESULT (with VAR bound to COUNT) is
;; the value of the form; nil if omitted.
;;
;; Same shape as `dolist', and for the same reason: subr.el runs the body inside
;; `(let ((VAR counter)) …)', so each iteration gets a FRESH binding and the
;; counter it steps is a separate uninterned variable. Hoisting VAR into the
;; enclosing `let' and `setq'ing it gave every closure made in the body the same
;; cell, so
;; (let (fs) (dotimes (i 3) (push (lambda () i) fs)) (mapcar #'funcall (nreverse fs)))
;; answered (3 3 3) instead of Emacs's (0 1 2) — and it leaked the *post-loop*
;; value, not even the last iteration's.
(let ((var (car spec)) (cnt (cadr spec)) (result (cddr spec))
(upper (make-symbol "upper-bound")) (counter (make-symbol "counter")))
`(let ((,upper ,cnt) (,counter 0))
(while (< ,counter ,upper)
(let ((,var ,counter)) ,@body)
(setq ,counter (1+ ,counter)))
,@(if result `((let ((,var ,counter)) ,@result))))))
;;; ---- error handling ----
(defmacro ignore-errors (&rest body) (declare (debug t) (indent 0)) `(condition-case nil (progn ,@body) (error nil)))
(defmacro ignore-error (condition &rest body) (declare (debug t) (indent 1)) `(condition-case nil (progn ,@body) (,condition nil)))
(defmacro with-suppressed-warnings (_warnings &rest body) (declare (debug (sexp body)) (indent 1)) `(progn ,@body))
(defmacro with-no-warnings (&rest body) (declare (indent 0)) `(progn ,@body))
;; declare-function (subr.el:31): a pure byte-compiler hint that FN is defined
;; in FILE; `byte-compile-macroexpand-declare-function' does the real work. In
;; the interpreter it expands to nil (matching `emacs -Q --batch').
(defmacro declare-function (_fn _file &rest _args)
"Tell the byte-compiler that function FN is defined, in FILE.
Optional ARGLIST specifies FN's arguments. Does nothing in the
interpreter; expands to nil."
(declare (advertised-calling-convention
(fn file &optional arglist fileonly) nil))
nil)
;; byte-run.el (31.1): in interpreted code both macros run BODY when they are
;; EXPANDED -- eager macroexpansion is the "compile time" -- and leave the value
;; behind as a constant. So the body sees no lexical binding of the code around
;; it, runs once however often the expansion is evaluated, and anything it
;; defines (a compiler macro, a defvar) is in place for the rest of the form.
(defvar macroexp--dynvars nil)
(defmacro eval-when-compile (&rest body)
(declare (debug (&rest def-form)) (indent 0))
(list 'quote (eval (cons 'progn body) lexical-binding)))
(defmacro eval-and-compile (&rest body)
(declare (debug (&rest def-form)) (indent 0))
(list 'quote (eval (cons 'progn body)
(when lexical-binding (or macroexp--dynvars t)))))
(defmacro cl-eval-when (situations &rest body)
;; Run BODY when a runtime situation (eval/load/:execute/:load-toplevel) applies.
(if (or (memq 'eval situations) (memq 'load situations)
(memq :execute situations) (memq :load-toplevel situations))
(cons 'progn body)
nil))
;; elisprs has no byte compiler, but the closures the prelude defines stand for
;; Lisp that Emacs ships byte-compiled: they answer these predicates as such,
;; and a closure the user wrote is interpreted.
(defun byte-code-function-p (object)
"Return t if OBJECT is a byte-compiled function object."
(elisprs--prelude-closure-p object))
(defun interpreted-function-p (object)
"Return non-nil if OBJECT is an interpreted function."
(and (closurep object) (not (elisprs--prelude-closure-p object))))
(defun compiled-function-p (object)
"Return non-nil if OBJECT is a function that is compiled."
(or (and (subrp object) t) (elisprs--prelude-closure-p object)))
;; Bound by `macroexpand-all' while it walks a form; libraries (e.g. rx) read it
;; to thread local macro environments. Defaults to nil outside expansion.
(defvar macroexpand-all-environment nil)
;; macroexp-compiling-p (macroexp.el:141): non-nil only when expanding for the
;; byte-compiler. elisprs interprets, so `macroexpand-all-environment' never
;; carries the compiler's declare-function cons — this returns nil.
(defun macroexp-compiling-p ()
"Return non-nil if we're macroexpanding for the compiler."
(member '(declare-function . byte-compile-macroexpand-declare-function)
macroexpand-all-environment))
;; cl-lib global declarations (cl-lib.el:252 / cl-macs.el:2645-2686). Real
;; init files reach these via `(cl-declaim (optimize (speed 3) (safety 0)))'
;; near the top of eieio-core, ede, auth-source, etc. Faithful port: the
;; `optimize'/`special'/`inline'/`warn' specs all target byte-compiler state
;; that elisprs (an interpreter) never consults, so `cl--do-proclaim' records
;; the optimize levels and otherwise no-ops.
(defvar cl--proclaims-deferred nil)
(defvar cl--proclaim-history t)
(defvar cl--optimize-safety)
(defvar cl--optimize-speed)
(defun cl--do-proclaim (spec hist)
(and hist (listp cl--proclaim-history) (push spec cl--proclaim-history))
(cond ((eq (car-safe spec) 'special)
(if (boundp 'byte-compile-bound-variables)
(setq byte-compile-bound-variables
(append (cdr spec) byte-compile-bound-variables))))
((eq (car-safe spec) 'inline)
(while (setq spec (cdr spec))
(or (memq (get (car spec) 'byte-optimizer)
'(nil byte-compile-inline-expand))
(error "%s already has a byte-optimizer, can't make it inline"
(car spec)))
(put (car spec) 'byte-optimizer #'byte-compile-inline-expand)))
((eq (car-safe spec) 'notinline)
(while (setq spec (cdr spec))
(if (eq (get (car spec) 'byte-optimizer)
#'byte-compile-inline-expand)
(put (car spec) 'byte-optimizer nil))))
((eq (car-safe spec) 'optimize)
(let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
'((0 nil) (1 t) (2 t) (3 t))))
(safety (assq (nth 1 (assq 'safety (cdr spec)))
'((0 t) (1 nil) (2 nil) (3 nil)))))
(if speed (setq cl--optimize-speed (car speed)
byte-optimize (nth 1 speed)))
(if safety (setq cl--optimize-safety (car safety)
byte-compile-delete-errors (nth 1 safety)))))
((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
(while (setq spec (cdr spec))
(if (consp (car spec))
(if (eq (cadar spec) 0)
(byte-compile-disable-warning (caar spec))
(byte-compile-enable-warning (caar spec)))))))
nil)
(defun cl-proclaim (spec)
"Record a global declaration specified by SPEC."
(if (fboundp 'cl--do-proclaim) (cl--do-proclaim spec t)
(push spec cl--proclaims-deferred))
nil)
(defmacro cl-declaim (&rest specs)
"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."
(let ((body (mapcar (lambda (x) `(cl-proclaim ',x)) specs)))
(if (macroexp-compiling-p) `(cl-eval-when (compile load eval) ,@body)
`(progn ,@body))))
;; A form that evaluates to V (self-quoting literals as-is, else (quote V)).
(defun macroexp-quote (v)
(if (and (not (consp v)) (or (not (symbolp v)) (null v) (eq v t) (keywordp v)))
v
(list 'quote v)))
;; macroexp const-ness predicates (macroexp.el:682). Used by cl-macs/cl-generic
;; to decide when a subform may be duplicated or optimized away.
(defvar byte-compile-const-variables nil)
(defun macroexp--const-symbol-p (symbol &optional any-value)
"Non-nil if SYMBOL is constant.
If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
symbol itself."
(or (memq symbol '(nil t))
(keywordp symbol)
(if any-value
(or (memq symbol byte-compile-const-variables)
(and (boundp symbol)
(condition-case nil
(progn (set symbol (symbol-value symbol)) nil)
(setting-constant t)))))))
(defun macroexp-const-p (exp)
"Return non-nil if EXP will always evaluate to the same value."
(cond ((consp exp) (or (eq (car exp) 'quote)
(and (eq (car exp) 'function)
(symbolp (cadr exp)))))
((symbolp exp) (macroexp--const-symbol-p exp))
(t t)))
(defun macroexp-copyable-p (exp)
"Return non-nil if EXP can be copied without extra cost."
(or (symbolp exp) (macroexp-const-p exp)))
;; defsubst: define an inline function. In the interpreter this is exactly a
;; `defun'; the `byte-optimizer' property is what the byte-compiler consults to
;; inline calls (byte-run.el:481). elisprs has no byte-compiler, so the
;; property is set for faithfulness but never acted upon.
(defmacro defsubst (name arglist &rest body)
"Define an inline function. The syntax is just like that of `defun'."
(declare (debug defun) (doc-string 3) (indent 2))
`(prog1
(defun ,name ,arglist ,@body)
(put ',name 'byte-optimizer 'byte-compile-inline-expand)))
;; purecopy: copy an object into pure space. elisprs has no pure space, so this
;; returns its argument unchanged — observably equal to Emacs's result.
(defun purecopy (object)
"Return a copy of OBJECT (identity — elisprs has no pure space)."
object)
;; autoloadp / autoload: mark a symbol to load its defining file on first call
;; (subr.el `autoloadp'; C `Fautoload'). elisprs installs the autoload object
;; faithfully; the on-call load trigger is the autoload subsystem (not wired).
(defun autoloadp (object)
"Non-nil if OBJECT is an autoload."
(eq 'autoload (car-safe object)))
(defun autoload-do-load (fundef &optional funname macro-only)
"If FUNDEF is an autoload form, load its file and return the new definition.
FUNNAME names the function being autoloaded; it must be defined by the file."
(if (or (not (autoloadp fundef))
(and (eq macro-only (quote macro))
(not (memq (nth 4 fundef) (quote (t macro))))))
fundef
(let ((data (match-data)))
(unwind-protect (load (car (cdr fundef)) nil t nil t)
(set-match-data data)))
(if (null funname)
nil
(let ((fun (indirect-function funname)))
(if (equal fun fundef)
(error "Autoloading file %s failed to define function %s"
(car (cdr fundef)) (symbol-name funname))
fun)))))
(defun autoload (function file &optional docstring interactive type)
"Define FUNCTION to autoload from FILE.
Does nothing if FUNCTION is already defined as something other than an
autoload. Returns FUNCTION when it installs the autoload, else nil."
(if (and (fboundp function)
(not (autoloadp (symbol-function function))))
nil
(fset function (list 'autoload file docstring interactive type))
function))
;; Advertised calling convention (byte-run.el:498). Records the SIGNATURE a
;; function advertises to the byte-compiler; cl-generic's `cl-generic-define-method'
;; preserves a generic's advertised signature across redefinition.
(defvar advertised-signature-table (make-hash-table :test 'eq :weakness 'key))
(defun set-advertised-calling-convention (function signature _when)
"Set the advertised SIGNATURE of FUNCTION."
(puthash (indirect-function function) signature
advertised-signature-table))
(defun get-advertised-calling-convention (function)
"Get the advertised SIGNATURE of FUNCTION.
Return t if there isn't any."
(gethash function advertised-signature-table t))
;; make-obsolete family (byte-run.el). These only record properties the
;; byte-compiler reads to emit warnings; in the interpreter they are inert but
;; ported so obsolete declarations in real libraries load cleanly.
(defun byte-run--constant-obsolete-warning (obsolete-name)
(if (memq obsolete-name '(nil t))
(error "Can't make `%s' obsolete; did you forget a quote mark?"
obsolete-name)))
(defun make-obsolete (obsolete-name current-name when)
"Make the byte-compiler warn that function OBSOLETE-NAME is obsolete."
(byte-run--constant-obsolete-warning obsolete-name)
(put obsolete-name 'byte-obsolete-info
(purecopy (list current-name nil when)))
obsolete-name)
(defun make-obsolete-variable (obsolete-name current-name when &optional access-type)
"Make the byte-compiler warn that OBSOLETE-NAME is obsolete."
(byte-run--constant-obsolete-warning obsolete-name)
(put obsolete-name 'byte-obsolete-variable
(purecopy (list current-name access-type when)))
obsolete-name)
(defmacro define-obsolete-function-alias (obsolete-name current-name when &optional docstring)
"Set OBSOLETE-NAME's function definition to CURRENT-NAME and mark it obsolete."
(declare (doc-string 4) (indent defun))
`(progn
(defalias ,obsolete-name ,current-name ,docstring)
(make-obsolete ,obsolete-name ,current-name ,when)))
(defmacro define-obsolete-variable-alias (obsolete-name current-name when &optional docstring)
"Make OBSOLETE-NAME a variable alias for CURRENT-NAME and mark it obsolete.
Uses `defvaralias' and `make-obsolete-variable' (byte-run.el)."
(declare (doc-string 4) (indent defun))
`(progn
(defvaralias ,obsolete-name ,current-name ,docstring)
;; See Bug#4706.
(dolist (prop '(saved-value saved-variable-comment))
(and (get ,obsolete-name prop)
(null (get ,current-name prop))
(put ,current-name prop (get ,obsolete-name prop))))
(make-obsolete-variable ,obsolete-name ,current-name ,when)))
;; eval-after-load (subr.el): register FORM to run after FILE loads; run now if
;; FILE (a feature symbol) is already provided. The string-file regexp path and
;; the fire-on-future-load path are the after-load subsystem (not wired); the
;; feature-symbol registration path used by real libraries is faithful.
(defvar after-load-alist nil)
(defun eval-after-load (file form)
"Arrange that if FILE is loaded, FORM will be run immediately afterwards."
(declare (indent 1))
(let* ((elt (assoc file after-load-alist))
(func (if (functionp form) form (eval (list 'lambda nil form) t))))
(unless elt
(setq elt (list file))
(push elt after-load-alist))
(when (and (symbolp file) (featurep file))
(funcall func))))
(defmacro with-eval-after-load (file &rest body)
"Execute BODY after FILE is loaded (see `eval-after-load')."
(declare (indent 1) (debug (form def-body)))
(list 'eval-after-load file (list 'quote (cons 'progn body))))
;; def-edebug-elem-spec (subr.el): record an Edebug spec element as a property.
;; Edebug is advisory in elisprs, but real libraries register specs at load time.
(defun def-edebug-elem-spec (name spec)
"Define a new Edebug spec element NAME as shorthand for SPEC."
(declare (indent 1))
(when (string-match "\\`[&:]" (symbol-name name))
(error "Edebug spec name cannot start with '&' or ':'"))
(unless (consp spec)
(error "Edebug spec has to be a list: %S" spec))
(put name 'edebug-elem-spec spec))
;; Declaration handler alists (byte-run.el). Declared nil here (before the
;; handler functions exist) and populated further below; the host's defun/defmacro
;; expander consults them via `elisprs--expand-defun-declarations' to process
;; `(declare ...)' specs with runtime effect (gv-setter, obsolete, indent, …).
(defvar defun-declarations-alist nil)
(defvar macro-declarations-alist nil)
(defmacro defvar-local (var val &optional doc)
(declare (debug defvar) (doc-string 3) (indent defun))
`(progn (defvar ,var ,val ,doc) (make-variable-buffer-local ',var)))
(defmacro with-demoted-errors (fmt &rest body) (declare (debug t) (indent 1)) `(condition-case --err-- (progn ,@body) (error (message ,fmt --err--) nil)))
;; macroexp.el: `macroexp-progn'. Defined this early because `setq-local' below
;; expands through it, and `setq-local' is used by functions defined long before
;; the rest of macroexp.el is.
(defun macroexp-progn (forms) (if (cdr forms) (cons 'progn forms) (car forms)))
;; subr.el (Emacs 31.1), verbatim. A macro must be defined before the first
;; function body that uses it is compiled, or the use compiles as a call.
(defmacro setq-local (&rest pairs)
"Make each VARIABLE local to current buffer and set it to corresponding VALUE.
The arguments are variable/value pairs. For each VARIABLE in a pair,
make VARIABLE buffer-local in the current buffer and assign to it the
corresponding VALUE of the pair. The VARIABLEs are literal symbols
and should not be quoted.
The VALUE of the Nth pair is not computed until after the VARIABLE
of the (N-1)th pair is set; thus, each VALUE can use the new VALUEs
of VARIABLEs set by earlier pairs.
The return value of the `setq-local' form is the VALUE of the last
pair.
In some corner cases you may need to resort to
`set-buffer-local-toplevel-value' instead, which see.
\(fn [VARIABLE VALUE]...)"
(declare (debug setq))
(unless (evenp (length pairs))
(signal 'wrong-number-of-arguments (list 'setq-local (length pairs))))
(let ((expr nil))
(while pairs
(unless (symbolp (car pairs))
(error "Attempting to set a non-symbol: %s" (car pairs)))
;; Can't use backquote here, it's too early in the bootstrap.
(setq expr
(cons
(list 'setq (car pairs)
(list 'prog1
(car (cdr pairs))
(list 'make-local-variable (list 'quote (car pairs)))))
expr))
(setq pairs (cdr (cdr pairs))))
(macroexp-progn (nreverse expr))))
(defmacro save-match-data (&rest body)
"Execute the BODY forms, restoring the global value of the match data.
The value returned is the value of the last form in BODY.
NOTE: The convention in Elisp is that any function, except for a few
exceptions like car/assoc/+/goto-char, can clobber the match data,
so `save-match-data' should normally be used to save *your* match data
rather than your caller's match data."
;; It is better not to use backquote here,
;; because that makes a bootstrapping problem
;; if you need to recompile all the Lisp files using interpreted code.
(declare (indent 0) (debug t))
(let ((saved-match-data (make-symbol "saved-match-data")))
(list 'let
(list (list saved-match-data '(match-data)))
(list 'unwind-protect
(cons 'progn body)
(list 'set-match-data saved-match-data t)))))
;;; ====================================================================
;;; Standard library — subr / subr-x / seq / cl-lib written in elisp on
;;; top of the primitives, the way Emacs bootstraps. (Buffer/marker ops,
;;; floats→int, and function-cell introspection need host primitives and
;;; are not included.)
;;; ====================================================================
;;; ---- predicates ----
(defun booleanp (x) (if (or (eq x t) (eq x nil)) t nil))
(defun characterp (x) (and (integerp x) (>= x 0) (<= x #x3FFFFF)))
(defun sequencep (x) (or (listp x) (vectorp x) (stringp x) (char-table-p x) (bool-vector-p x)))
(defun arrayp (x) (or (vectorp x) (stringp x) (char-table-p x) (bool-vector-p x)))
(defun string-or-null-p (x) (or (null x) (stringp x)))
;; nlistp is a native subr (builtins.rs): a C subr in Emacs, same identity
;; requirement as natnump.
;; ROT13: rotate ASCII letters by 13, leaving everything else unchanged.
(defun rot13-string (string)
(mapconcat (lambda (c)
(char-to-string
(cond ((and (>= c ?a) (<= c ?z)) (+ ?a (% (+ (- c ?a) 13) 26)))
((and (>= c ?A) (<= c ?Z)) (+ ?A (% (+ (- c ?A) 13) 26)))
(t c))))
(append string nil) ""))
;; elisprs has no symbols-with-position, so a symbol is always "bare".
(defun symbol-with-pos-p (_x) nil)
(defun bare-symbol (sym) sym)
(defun xor (a b) (cond ((not a) b) ((not b) a) (t nil)))
(defun proper-list-p (x)
;; Length if X is a proper (nil-terminated, acyclic) list, else nil. Floyd
;; cycle detection so a circular list returns nil instead of looping.
(let ((slow x) (fast x) (n 0))
(catch 'proper-list-p--done
(while t
(unless (consp fast) (throw 'proper-list-p--done (if (null fast) n nil)))
(setq fast (cdr fast) n (1+ n))
(unless (consp fast) (throw 'proper-list-p--done (if (null fast) n nil)))
(setq fast (cdr fast) n (1+ n) slow (cdr slow))
(when (eq fast slow) (throw 'proper-list-p--done nil))))))
;;; ---- numbers ----
;; `expt` is a primitive subr (integer power; float for fractional/negative exp).
(defun gcd (a b)
(setq a (abs a)) (setq b (abs b))
(while (> b 0) (let ((tmp b)) (setq b (% a b)) (setq a tmp)))
a)
(defun lcm (a b) (if (or (= a 0) (= b 0)) 0 (/ (abs (* a b)) (gcd a b))))
(defun isqrt (n) (let ((r 0)) (while (<= (* (1+ r) (1+ r)) n) (setq r (1+ r))) r))
(defun cl-signum (x) (cond ((> x 0) 1) ((< x 0) -1) (t 0)))
;; cl-evenp/cl-oddp are byte-compiled in Emacs, where a wrong argument count is
;; caught by exec_byte_code and signalled as ((MANDATORY . NONREST) NARGS) —
;; (wrong-number-of-arguments (1 . 1) 2) — never as the function object. Take
;; &rest and reproduce that exact error shape; the interpreter's own arity
;; check would name this interpreted closure instead.
(defun cl-evenp (&rest args)
(unless (= (length args) 1)
(signal 'wrong-number-of-arguments (list (cons 1 1) (length args))))
(let ((n (car args)))
(unless (integerp n) (signal 'wrong-type-argument (list 'integer-or-marker-p n)))
(= (% n 2) 0)))
(defun cl-oddp (&rest args)
(unless (= (length args) 1)
(signal 'wrong-number-of-arguments (list (cons 1 1) (length args))))
(let ((n (car args)))
(unless (integerp n) (signal 'wrong-type-argument (list 'integer-or-marker-p n)))
(/= (% n 2) 0)))
;; Two-value division: each returns (QUOTIENT REMAINDER) where the remainder is
;; X - QUOTIENT*Y, matching the single-value floor/ceiling/truncate/round builtins.
;; cl-extra.el's two-value division family, ported verbatim. The exact
;; expressions matter, not just the values: which argument each one touches
;; first is what names the offender in a `wrong-type-argument'. `cl-truncate'
;; tests `(>= y 0)' before dividing, so `(cl-rem 1.0e+INF '(1 2))' is
;; `(wrong-type-argument number-or-marker-p (1 2))' and never the `integerp'
;; that a division-first implementation reaches.
;;
;; They also accept FLOATS, because they are the remainder half of `cl-floor' /
;; `cl-truncate': `(cl-rem 7.5 2)' is 1.5 and `(cl-mod -7.5 2)' is 0.5. Routing
;; them through `mod'/`%' — integer-only in elisp — signalled
;; `wrong-type-argument integer-or-marker-p 7.5' on every float.
(defun cl-floor (x &optional y)
(let ((q (floor x y)))
(list q (- x (if y (* y q) q)))))
(defun cl-ceiling (x &optional y)
(let ((res (cl-floor x y)))
(if (= (car (cdr res)) 0) res
(list (1+ (car res)) (- (car (cdr res)) (or y 1))))))
(defun cl-truncate (x &optional y)
(if (eq (>= x 0) (or (null y) (>= y 0)))
(cl-floor x y) (cl-ceiling x y)))
(defun cl-round (x &optional y)
(if y
(if (and (integerp x) (integerp y))
(let* ((hy (/ y 2))
(res (cl-floor (+ x hy) y)))
(if (and (= (car (cdr res)) 0)
(= (+ hy hy) y)
(/= (% (car res) 2) 0))
(list (1- (car res)) hy)
(list (car res) (- (car (cdr res)) hy))))
(let ((q (round (/ x y))))
(list q (- x (* q y)))))
(if (integerp x) (list x 0)
(let ((q (round x)))
(list q (- x q))))))
(defun cl-mod (x y) (nth 1 (cl-floor x y)))
(defun cl-rem (x y) (nth 1 (cl-truncate x y)))
;; The Euclid loops, verbatim. `(% a (setq a b))' reads the OLD `a' and then
;; rebinds it in the same expression, which is why `(cl-lcm "" 65535)' reports
;; `integer-or-marker-p ""' from `%' — an `abs'-first paraphrase reported
;; `number-or-marker-p' instead. `(/= b 0)' likewise tests B before touching A,
;; so `(cl-gcd 100 'car)' names `car' under `number-or-marker-p'.
(defun cl-gcd (&rest args)
(let ((a (or (pop args) 0)))
(dolist (b args)
(while (/= b 0)
(setq b (% a (setq a b)))))
(abs a)))
(defun cl-lcm (&rest args)
(if (memq 0 args)
0
(let ((a (or (pop args) 1)))
(dolist (b args)
(setq a (* (/ a (cl-gcd a b)) b)))
(abs a))))
;; cl-extra.el `cl-coerce'.
(defun cl-coerce (x type)
(cond ((eq type 'list) (if (listp x) x (append x nil)))
((eq type 'vector) (if (vectorp x) x (vconcat x)))
((eq type 'bool-vector)
(if (bool-vector-p x) x (apply #'bool-vector (cl-coerce x 'list))))
((eq type 'string) (if (stringp x) x (concat x)))
((eq type 'array) (if (arrayp x) x (vconcat x)))
((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
((and (eq type 'character) (symbolp x))
(cl-coerce (symbol-name x) type))
((eq type 'float) (float x))
((cl-typep x type) x)
(t (error "Can't coerce %s to type %s" x type))))
(defvar cl--gensym-counter 0)
;; cl-macs.el: a string PREFIX replaces "G", an integer PREFIX is the number
;; itself (the counter is left alone), anything else is ignored.
(defun cl-gensym (&optional prefix)
(let ((pfix (if (stringp prefix) prefix "G"))
(num (if (integerp prefix) prefix
(prog1 cl--gensym-counter
(setq cl--gensym-counter (1+ cl--gensym-counter))))))
(make-symbol (format "%s%d" pfix num))))
(defvar cl--gentemp-counter 0)
;; cl-macs.el: an INTERNED symbol whose name no existing symbol has.
(defun cl-gentemp (&optional prefix)
(let ((pfix (if (stringp prefix) prefix "T"))
name)
(while (intern-soft (setq name (format "%s%d" pfix cl--gentemp-counter)))
(setq cl--gentemp-counter (1+ cl--gentemp-counter)))
(intern name)))
(defun cl-digit-char-p (char &optional radix)
(let ((r (or radix 10))
(v (cond ((and (>= char ?0) (<= char ?9)) (- char ?0))
((and (>= char ?a) (<= char ?z)) (+ 10 (- char ?a)))
((and (>= char ?A) (<= char ?Z)) (+ 10 (- char ?A)))
(t nil))))
(if (and v (< v r)) v nil)))
(defun cl-isqrt (n)
(if (< n 2) n
(let ((x n) (y (/ (+ n 1) 2)))
(while (< y x) (setq x y y (/ (+ x (/ n x)) 2)))
x)))
;; `string-to-number` is a primitive subr (floats, scientific notation, BASE arg).
;;; ---- key sequences (kbd) ----
;; Control-fold a character: letters/@A-Z[\]^_ map to 0–31, ? to 127, else the
;; control bit (2^26) is set.
(defun kbd--ctrl (c)
(cond ((and (>= c ?a) (<= c ?z)) (- c 96))
((eq c ??) 127)
((and (>= c ?@) (<= c ?_)) (- c ?@))
(t (logior c (ash 1 26)))))
;; Apply modifier flags to a character code (returns an int, possibly with
;; meta/shift/hyper/super/alt bits set).
(defun kbd--char (c ctrl meta shift hyper super alt)
(when ctrl (setq c (kbd--ctrl c)))
(when shift (setq c (logior c (ash 1 25))))
(when hyper (setq c (logior c (ash 1 24))))
(when super (setq c (logior c (ash 1 23))))
(when alt (setq c (logior c (ash 1 22))))
(when meta (setq c (logior c (ash 1 27))))
c)
;; Build a function-key symbol, prefixing modifiers in Emacs's canonical
;; A-C-H-M-S-s order.
(defun kbd--sym (name ctrl meta shift hyper super alt)
(when super (setq name (concat "s-" name)))
(when shift (setq name (concat "S-" name)))
(when meta (setq name (concat "M-" name)))
(when hyper (setq name (concat "H-" name)))
(when ctrl (setq name (concat "C-" name)))
(when alt (setq name (concat "A-" name)))
(intern name))
;; Parse one whitespace-delimited key token into a list of key codes/symbols.
(defun kbd--token (tok)
(let ((ctrl nil) (meta nil) (shift nil) (hyper nil) (super nil) (alt nil)
(i 0) (n (length tok)) (hadmod nil))
(while (and (< (1+ i) n) (eq (aref tok (1+ i)) ?-) (memq (aref tok i) '(?C ?M ?S ?H ?s ?A)))
(setq hadmod t)
(let ((m (aref tok i)))
(cond ((eq m ?C) (setq ctrl t)) ((eq m ?M) (setq meta t)) ((eq m ?S) (setq shift t))
((eq m ?H) (setq hyper t)) ((eq m ?s) (setq super t)) ((eq m ?A) (setq alt t))))
(setq i (+ i 2)))
(let* ((rest (substring tok i)) (rn (length rest))
(named (cond ((string= rest "RET") 13) ((string= rest "TAB") 9) ((string= rest "SPC") 32)
((string= rest "ESC") 27) ((string= rest "DEL") 127) ((string= rest "LFD") 10)
((string= rest "NUL") 0) (t nil)))
(anglesym (and (> rn 1) (eq (aref rest 0) ?<) (eq (aref rest (1- rn)) ?>))))
(cond
(anglesym (list (kbd--sym (substring rest 1 (1- rn)) ctrl meta shift hyper super alt)))
(named (list (kbd--char named ctrl meta shift hyper super alt)))
;; A plain multi-character token is a sequence of single-character keys.
((and (not hadmod) (> rn 1)) (append rest nil))
((= rn 1) (list (kbd--char (aref rest 0) ctrl meta shift hyper super alt)))
(t (list (kbd--sym rest ctrl meta shift hyper super alt)))))))
(defun kbd (keys)
"Parse a key-description string into a key sequence (string or vector)."
(let ((codes nil))
(dolist (tok (split-string keys " " t))
(setq codes (append codes (kbd--token tok))))
(if (cl-every (lambda (c) (and (integerp c) (>= c 0) (<= c 127))) codes)
(apply #'string codes)
(vconcat codes))))
;;; ---- strings (ASCII) ----
;; Emacs's string comparators accept symbols too, using their print names.
(defun string--name (x) (if (symbolp x) (symbol-name x) x))
(defun string= (a b)
;; Emacs accepts a string or a symbol on either side and signals `stringp' on
;; anything else -- it does not quietly answer nil for, say, a float.
(unless (or (stringp a) (symbolp a)) (signal 'wrong-type-argument (list 'stringp a)))
(unless (or (stringp b) (symbolp b)) (signal 'wrong-type-argument (list 'stringp b)))
(equal (string--name a) (string--name b)))
(defun string-equal (a b) (string= a b))
(defun string< (a b)
;; Like `string=': a string or a symbol on either side, `stringp' on anything
;; else — the first argument is checked first, so (string< 97 "a") names 97.
(unless (or (stringp a) (symbolp a)) (signal 'wrong-type-argument (list 'stringp a)))
(unless (or (stringp b) (symbolp b)) (signal 'wrong-type-argument (list 'stringp b)))
(let ((la (string-to-list (string--name a))) (lb (string-to-list (string--name b)))
(res nil) (done nil))
(while (not done)
(cond ((null la) (setq res (not (null lb))) (setq done t))
((null lb) (setq res nil) (setq done t))
((< (car la) (car lb)) (setq res t) (setq done t))
((> (car la) (car lb)) (setq res nil) (setq done t))
(t (setq la (cdr la)) (setq lb (cdr lb)))))
res))
(defun string-lessp (a b) (string< a b))
(defun string-greaterp (a b) (string< b a))
(defun string> (a b) (string< b a))
;; Collation: no locale support, so this is ordinary string order (with optional
;; case folding), matching the C-locale default.
(defun string-collate-lessp (s1 s2 &optional _locale ignore-case)
(if ignore-case (string-lessp (downcase s1) (downcase s2)) (string-lessp s1 s2)))
(defun string-collate-equalp (s1 s2 &optional _locale ignore-case)
(if ignore-case (string-equal (downcase s1) (downcase s2)) (string-equal s1 s2)))
;; doc.c `Ftext_quoting_style': `grave' and `straight' are taken as given; nil
;; and anything else are `curve' (startup sets `internal--text-quoting-flag' and
;; curved quotes are always displayable here).
(defvar text-quoting-style nil)
(defun text-quoting-style ()
(cond ((eq text-quoting-style 'grave) 'grave)
((eq text-quoting-style 'straight) 'straight)
(t 'curve)))
(defun string-reverse (s) (reverse s))
;; `upcase` / `downcase` are primitive subrs (accept a string or a character).
(defun char-or-string--check (s)
(unless (or (stringp s) (integerp s))
(signal 'wrong-type-argument (list 'char-or-string-p s)))
s)
(defun capitalize (s)
"Convert argument to capitalized form and return that.
This means that each word's first character is converted to either
title case or upper case, and the rest to lower case.
The argument may be a character or string. The result has the same type."
(char-or-string--check s)
;; A character argument cannot grow, so it takes the one-to-one path:
;; `(capitalize ?ß)' is ẞ, while `(capitalize "ß")' is "Ss".
(if (integerp s) (--char-titlecase-1-- s) (--casify-capitalize-- s nil)))
(defun string-trim-left (s &optional regexp)
;; Strip a leading match of REGEXP (default whitespace).
(let ((re (concat "\\`\\(?:" (or regexp "[ \t\n\r]+") "\\)")))
(if (string-match re s) (substring s (match-end 0)) s)))
(defun string-trim-right (s &optional regexp)
;; Strip a trailing match of REGEXP (default whitespace).
(let ((re (concat "\\(?:" (or regexp "[ \t\n\r]+") "\\)\\'")))
(if (string-match re s) (substring s 0 (match-beginning 0)) s)))
(defun string-trim (s &optional trim-left trim-right)
;; subr-x: (string-trim-left (string-trim-right STRING TRIM-RIGHT) TRIM-LEFT)
;; -- the RIGHT trim runs first, so with two bad regexps the right one's
;; compile error wins: (string-trim "" "\\(" "[") => (invalid-regexp
;; "Unmatched [ or [^").
(string-trim-left (string-trim-right s trim-right) trim-left))
;; Port of subr.el's Lisp definition (Emacs 31.1): `match-data--translate'
;; aims the match data at the matched substring. Re-matching REGEXP against the
;; substring lost the context a match can depend on -- `\\B' matched between
;; "a" and "b" fails on the one-character substring. Everything observable
;; falls out of the original:
;; `(length string)` rejects a non-sequence up front (`sequencep`), a nil
;; STRING flows through to `(substring nil 0 0)` (`arrayp nil`), REGEXP is only
;; type-checked/compiled when the loop runs (l > 0), REP may be a function and
;; is not looked at until a match happens, and `(< start l)` stops the
;; empty-regexp loop from appending one more replacement at end-of-string —
;; (replace-regexp-in-string "" "t" "-4.5") => "t-t4t.t5".
(defun replace-regexp-in-string (regexp rep string &optional fixedcase literal subexp start)
(let ((l (length string))
(start (or start 0))
matches str mb me)
(save-match-data
(while (and (< start l) (string-match regexp string start))
(setq mb (match-beginning 0)
me (match-end 0))
;; If we matched the empty string, make sure we advance by one char
(when (= me mb) (setq me (min l (1+ mb))))
;; Generate a replacement for the matched substring.
;; Operate on only the substring to minimize string consing.
;; Translate the match data so that it applies to the matched substring.
(match-data--translate (- mb))
(setq str (substring string mb me))
(setq matches
(cons (replace-match (if (stringp rep)
rep
(funcall rep (match-string 0 str)))
fixedcase literal str subexp)
(cons (substring string start mb) ; unmatched prefix
matches)))
(setq start me))
;; Reconstruct a string from the pieces.
(setq matches (cons (substring string start l) matches)) ; leftover
(apply #'concat (nreverse matches)))))
(defun string-blank-p (s) (string-match-p "\\`[ \t\n\r]*\\'" s))
(defun string-clean-whitespace (s)
;; Collapse internal whitespace runs to a single space and trim the ends.
(string-trim (replace-regexp-in-string "[ \t\n\r]+" " " s)))
(defun string-truncate-left (string length)
;; If STRING is longer than LENGTH, keep the rightmost characters and prepend
;; "..." (so the result may exceed the original when LENGTH is <= 3).
(let ((strlen (length string)))
(if (<= strlen length)
string
(setq length (max 0 (- length 3)))
(concat "..." (substring string (min (1- strlen)
(max 0 (- strlen length))))))))
;; Verbatim subr-x: all argument rejection falls out of `string-prefix-p' /
;; `string-suffix-p' (whose `length' calls signal `sequencep'), so
;; (string-remove-prefix "..." nil) is nil when the prefix cannot fit.
(defun string-remove-prefix (prefix s)
(if (string-prefix-p prefix s) (substring s (length prefix)) s))
(defun string-remove-suffix (suffix s)
(if (string-suffix-p suffix s) (substring s 0 (- (length s) (length suffix))) s))
;;; ---- lists ----
(defun butlast (lst &optional n)
;; All but the last N elements of LST (default 1): (butlast '(1 2 3) 2) => (1).
(setq n (or n 1))
;; subr.el: N <= 0 returns LST itself, UNVALIDATED -- (butlast 0 0) => 0.
(if (<= n 0) lst
(let ((keep (min (length lst) (- (length lst) n))) (r nil) (i 0))
(while (< i keep) (setq r (cons (nth i lst) r)) (setq i (1+ i)))
(reverse r))))
(defun nbutlast (lst &optional n)
;; Destructively drop the last N (default 1) elements.
(let ((n (or n 1)) (len (length lst)))
(cond ((<= len n) nil)
((<= n 0) lst)
(t (setcdr (nthcdr (- len n 1) lst) nil) lst))))
(defun take (n lst)
;; fns.c Ftake: N must be an integer — a float or a symbol signals `integerp`,
;; not the `number-or-marker-p` a comparison would give.
(unless (integerp n) (signal (quote wrong-type-argument) (list (quote integerp) n)))
(let ((out nil))
(while (and (> n 0) lst) (setq out (cons (car lst) out)) (setq lst (cdr lst)) (setq n (1- n)))
(reverse out)))
(defun ntake (n lst) (take n lst))
(defun flatten-tree (tree)
(cond ((null tree) nil)
((consp tree) (append (flatten-tree (car tree)) (flatten-tree (cdr tree))))
(t (list tree))))
(defun flatten-list (tree) (flatten-tree tree))
(defun copy-tree (tree &optional vectors-and-records)
"Make a copy of TREE.
If TREE is a cons cell, this recursively copies both its car and its cdr.
With VECTORS-AND-RECORDS non-nil, traverse and copy vectors and records too."
;; Ported from subr.el:877. The iterative cdr walk (rather than a plain
;; `(cons (copy-tree (car …)) (copy-tree (cdr …)))' recursion) is what keeps a
;; long list from recursing once per element, and it is the only shape that
;; copies a DOTTED tail correctly under VECTORS-AND-RECORDS.
(if (consp tree)
(let (result)
(while (consp tree)
(let ((newcar (car tree)))
(if (or (consp (car tree))
(and vectors-and-records
(or (vectorp (car tree)) (recordp (car tree)))))
(setq newcar (copy-tree (car tree) vectors-and-records)))
(push newcar result))
(setq tree (cdr tree)))
(nconc (nreverse result)
(if (and vectors-and-records (or (vectorp tree) (recordp tree)))
(copy-tree tree vectors-and-records)
tree)))
(if (and vectors-and-records (or (vectorp tree) (recordp tree)))
(let ((i (length (setq tree (copy-sequence tree)))))
(while (>= (setq i (1- i)) 0)
(aset tree i (copy-tree (aref tree i) vectors-and-records)))
tree)
tree)))
(defun copy-sequence (seq)
(cond ((listp seq) (append seq nil))
;; A string and a vector copy into FRESH objects. Returning SEQ itself
;; was a silent wrong answer twice over: `(eq seq (copy-sequence seq))'
;; answered t where Emacs answers nil, and — worse — `aset' on the
;; "copy" wrote through to the original, so `copy-tree'/`cl-copy-list'
;; and every caller that copies before mutating shared one object.
;; Emacs's `copy-sequence' does); `vconcat' copies a vector's slots.
((stringp seq) (elisprs--copy-string seq))
((vectorp seq) (vconcat seq))
;; A record is copied slot-for-slot into a fresh record (slot 0, the type,
;; is reproduced): `(copy-sequence rec)' preserves record-ness, so it is the
;; copier a cl-defstruct `copy-NAME' uses.
((recordp seq)
(let ((n (length seq)) (i 0) (args nil))
(while (< i n) (setq args (cons (aref seq i) args) i (1+ i)))
(apply #'record (nreverse args))))
;; A bool-vector copies to a fresh, independent bool-vector.
((bool-vector-p seq) (apply #'bool-vector (append seq nil)))
((char-table-p seq) (elisprs--copy-char-table seq))
(t (signal 'wrong-type-argument (list 'sequencep seq)))))
(defun ensure-list (x) (if (listp x) x (list x)))
(defun mapcan (fn lst)
;; Fmapcan = mapcar then Fnconc, NOT append: results are spliced through
;; their last cons, so dotted results are legal -- (mapcan (lambda (x)
;; (cons x x)) (list -0.0 t)) => (-0.0 t . t) -- and a non-cons non-last
;; result signals `consp': (mapcan #'downcase (make-list 5 3)) =>
;; (wrong-type-argument consp 3).
(apply (function nconc) (mapcar fn lst)))
(defun assoc-default (key alist &optional test default)
;; Faithful port of subr.el: each element (or its car) is compared to KEY via
;; (funcall (or TEST 'equal) ELEM KEY); on a hit return its cdr, else DEFAULT.
(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))
(defun assoc-delete-all (key alist &optional test)
;; Faithful subr.el port (destructive, like rassq-delete-all): `(car alist)'
;; on a non-list signals listp naming it.
(unless test (setq test #'equal))
(while (and (consp (car alist)) (funcall test (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)) (funcall test (car (car tail-cdr)) key))
(setcdr tail (cdr tail-cdr))
(setq tail tail-cdr))))
alist)
(defun assq-delete-all (key alist)
;; subr.el: assq-delete-all is assoc-delete-all with `eq'.
(assoc-delete-all key alist #'eq))
;; Minimal completion API over a list (plain or alist), or a hash-table's keys.
;; (Function collections, obarrays, and completion-ignore-case are unsupported.)
(defun completion--str (e)
(let ((c (if (consp e) (car e) e)))
(cond ((symbolp c) (symbol-name c)) ((stringp c) c) (t (format "%s" c)))))
(defun completion--common-prefix (a b)
(let ((n (min (length a) (length b))) (i 0))
(while (and (< i n) (eq (aref a i) (aref b i))) (setq i (1+ i)))
(substring a 0 i)))
(defun completion--elements (collection)
(if (hash-table-p collection) (hash-table-keys collection) collection))
(defun all-completions (string collection &optional predicate)
(let ((out nil))
(dolist (e (completion--elements collection))
(let ((c (completion--str e)))
(when (and (string-prefix-p string c) (or (null predicate) (funcall predicate e)))
(setq out (cons c out)))))
(nreverse out)))
(defun try-completion (string collection &optional predicate)
(let ((cands (all-completions string collection predicate)))
(cond
((null cands) nil)
((and (null (cdr cands)) (string= (car cands) string)) t)
(t (let ((common (car cands)))
(dolist (c (cdr cands)) (setq common (completion--common-prefix common c)))
common)))))
(defun test-completion (string collection &optional predicate)
(let ((res nil))
(dolist (e (completion--elements collection))
(when (and (string= (completion--str e) string) (or (null predicate) (funcall predicate e)))
(setq res t)))
res))
(defun nreverse (seq)
;; Reverse a list in place by relinking its cons cells; other sequences copy.
(if (listp seq)
(let ((prev nil) (cur seq))
(while (consp cur)
(let ((next (cdr cur)))
(setcdr cur prev)
(setq prev cur cur next)))
;; Fnreverse's CHECK_LIST_END fires AFTER the relinking, so a dotted
;; tail signals listp naming the (already mutated) original head cons:
;; (nreverse (cons "p" 32)) => (wrong-type-argument listp ("p")).
(when cur (signal 'wrong-type-argument (list 'listp seq)))
prev)
;; Non-list: only arrays are reversible in place; else signal arrayp (Emacs).
(if (arrayp seq) (reverse seq)
(signal 'wrong-type-argument (list 'arrayp seq)))))
;;; ---- sort ----
;; `sort' itself is native: `host::call_function' intercepts it so PRED and :key
;; can re-enter elisp, and it handles the Emacs-30 keyword form and vectors,
;; neither of which the two-argument merge sort below ever did. Defining a Lisp
;; `sort' here only overwrote the subr's function cell, so `(func-arity 'sort)'
;; answered `(2 . 2)' where Emacs says `(1 . many)' and `(subrp (symbol-function
;; 'sort))' answered nil — while every actual call still went to the intercept.
;; The merge-sort helpers stay: `std--merge' is the stable merge other list code
;; uses directly.
(defun std--merge (a b pred)
(cond ((null a) b)
((null b) a)
((funcall pred (car b) (car a)) (cons (car b) (std--merge a (cdr b) pred)))
(t (cons (car a) (std--merge (cdr a) b pred)))))
(defun std--halves (lst)
(let ((slow lst) (fast lst) (front nil))
(while (and fast (cdr fast))
(setq front (cons (car slow) front)) (setq slow (cdr slow)) (setq fast (cdr (cdr fast))))
(cons (reverse front) slow)))
;;; ---- seq.el (list-oriented) ----
;; seq-generic: coerce to a list, then restore SEQ's own type (vector/string).
(defun seq-take (seq n)
;; seq.el: a list goes through `take`, whose N must be an integer; every other
;; sequence reaches a comparison first, which signals number-or-marker-p.
;; (seq-take nil 1.5) => integerp 1.5; (seq-take "abc" (quote x)) => number-or-marker-p x.
(unless (listp seq)
(unless (number-or-marker-p n) (signal (quote wrong-type-argument) (list (quote number-or-marker-p) n))))
(if (or (stringp seq) (vectorp seq))
(seq-subseq seq 0 (min (max n 0) (length seq)))
(seq-into (take n (append seq nil)) (seq--type-of seq))))
(defun seq-drop (seq n)
;; seq.el: the list method is literally (nthcdr n list) -- so a non-integer
;; N signals `integerp' via nthcdr -- while other sequences go through the
;; generic (<= n 0) path, whose comparison signals number-or-marker-p:
;; (seq-drop '(1) "s") => integerp "s"; (seq-drop "abc" 's) =>
;; number-or-marker-p s.
(if (listp seq)
(nthcdr n seq)
(if (<= n 0) seq
(let ((len (seq-length seq)))
(seq-subseq seq (min n len) len)))))
(defun seq-subseq (seq start &optional end)
;; Faithful seq.el: strings and vectors defer to `substring' (so a
;; non-integer index signals `integerp' and out-of-range signals
;; args-out-of-range); the list branch is subr.el's arithmetic walk, whose
;; out-of-range report is a plain `error'.
(cond
((or (stringp seq) (vectorp seq)) (substring seq start end))
((listp seq)
(let (len (orig-start start) (orig-end end))
(and end (< end 0) (setq end (+ end (setq len (length seq)))))
(if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
(unless (>= start 0)
(error "Start index out of bounds: %s" orig-start))
(when (> start 0)
(setq seq (nthcdr (1- start) seq))
(unless seq
(error "Start index out of bounds: %s" orig-start))
(setq seq (cdr seq)))
(if end
(let ((n (- end start)))
(when (or (< n 0)
(if len
(> end len)
(and (> n 0) (null (nthcdr (1- n) seq)))))
(error "End index out of bounds: %s" orig-end))
(take n seq))
(copy-sequence seq))))
(t (error "Unsupported sequence: %s" seq))))
(defun seq-uniq (seq &optional testfn)
(if (null testfn)
(delete-dups (append seq nil))
(let ((out nil))
(dolist (x (append seq nil))
(unless (let ((f nil)) (dolist (y out) (when (funcall testfn x y) (setq f t))) f)
(setq out (cons x out))))
(nreverse out))))
(defun seq-min (seq) (apply (function min) (append seq nil)))
(defun seq-max (seq) (apply (function max) (append seq nil)))
(defun seq-first (seq) (elt seq 0))
(defun seq-rest (seq) (seq-drop seq 1))
(defun seq-position (seq elt &optional testfn)
(let ((test (or testfn #'equal)) (i 0) (res nil))
(setq seq (append seq nil))
(while (and seq (null res)) (if (funcall test (car seq) elt) (setq res i)) (setq seq (cdr seq)) (setq i (1+ i)))
res))
(defun seq-into (seq type)
;; seq.el dispatches on TYPE with a `pcase' FIRST and only then touches
;; SEQUENCE (each arm calls its own `seq--into-*'), so an unknown TYPE is
;; reported even when SEQ is not a sequence at all:
;; (seq-into 0 'foo) => (error "Not a sequence type name: foo"), NOT
;; (wrong-type-argument sequencep 0). Coercing SEQ up front reversed that.
;; Each `seq--into-*' hands back SEQUENCE itself when it already has the
;; target type — (eq l (seq-into l 'list)) is t, and a dotted list is
;; returned whole rather than walked — and only converts otherwise.
(cond ((eq type 'vector) (if (vectorp seq) seq (vconcat seq)))
((eq type 'string) (if (stringp seq) seq (concat seq)))
((eq type 'list) (if (listp seq) seq (append seq nil)))
(t (error "Not a sequence type name: %S" type))))
(defun seq-difference (a b &optional testfn)
(seq-filter (lambda (x) (not (seq-contains-p b x testfn))) a))
(defun seq-intersection (a b &optional testfn)
(seq-filter (lambda (x) (seq-contains-p b x testfn)) a))
(defun seq-union (a b &optional testfn)
;; Emacs reduces an accumulator over both sequences, skipping an element it
;; already holds -- so duplicates *within* A are dropped too:
;; (seq-union '(1 1 2) '(2 3)) => (1 2 3), not (1 1 2 3).
(let ((acc nil))
(dolist (e (append a nil))
(unless (seq-contains-p acc e testfn) (setq acc (cons e acc))))
(dolist (e (append b nil))
(unless (seq-contains-p acc e testfn) (setq acc (cons e acc))))
(nreverse acc)))
(defun seq-sort (pred seq) (seq-into (sort (append seq nil) pred) (seq--type-of seq)))
(defun seq-partition (seq n)
;; Each chunk keeps SEQ's type (string→strings, vector→vectors, list→lists).
;; seq.el guards with (unless (< n 1)): N < 1 returns nil WITHOUT touching
;; SEQ at all -- (seq-partition 0 0) => nil, and (seq-partition "ab" 0) is
;; nil, not an infinite zero-progress loop.
(unless (< n 1)
(let ((out nil) (type (seq--type-of seq)) (l (append seq nil)))
(while l
(setq out (cons (seq-into (take n l) type) out))
(setq l (nthcdr n l)))
(reverse out))))
(defun seq-split (sequence length)
;; NOT an alias for `seq-partition': seq.el gives `seq-split' its own body, and
;; the guard is the opposite one. `seq-partition' returns nil for N < 1;
;; `seq-split' SIGNALS -- (seq-split '("a") 0) is
;; (error "Sub-sequence length must be larger than zero").
(when (< length 1)
(error "Sub-sequence length must be larger than zero"))
(let ((result nil) (seq-length (length sequence)) (start 0))
(while (< start seq-length)
(setq result
(cons (seq-subseq sequence start
(setq start (min seq-length (+ start length))))
result)))
(nreverse result)))
(defun seq-set-equal-p (seq1 seq2 &optional testfn)
(and (seq-every-p (lambda (x) (seq-contains-p seq2 x testfn)) seq1)
(seq-every-p (lambda (x) (seq-contains-p seq1 x testfn)) seq2)))
(defun seq-into-sequence (seq)
(if (sequencep seq) seq (error "Cannot convert %S into a sequence" seq)))
(defun seq-sort-by (fn pred seq)
(seq-sort (lambda (a b) (funcall pred (funcall fn a) (funcall fn b))) seq))
(defun seq-positions (seq elt &optional testfn)
(let ((test (or testfn 'equal)) (i 0) (out nil) (l (append seq nil)))
(while l
(when (funcall test (car l) elt) (setq out (cons i out)))
(setq i (1+ i) l (cdr l)))
(nreverse out)))
(defun seq-remove-at-position (sequence n)
(seq-concatenate
(if (listp sequence) (quote list) (type-of sequence))
(seq-subseq sequence 0 n)
(seq-subseq sequence (1+ n))))
(defun seq--type-of (seq)
(cond ((listp seq) 'list) ((vectorp seq) 'vector) ((stringp seq) 'string) (t 'list)))
(defun seq-take-while (pred seq)
;; Leading run of SEQ for which PRED holds, returned as SEQ's own type.
(let ((lst (append seq nil)) (acc nil) (go t))
(while (and lst go)
(if (funcall pred (car lst))
(setq acc (cons (car lst) acc) lst (cdr lst))
(setq go nil)))
(seq-into (nreverse acc) (seq--type-of seq))))
(defun seq-drop-while (pred seq)
;; SEQ with its leading PRED-satisfying run removed, in SEQ's own type.
(let ((lst (append seq nil)) (go t))
(while (and lst go)
(if (funcall pred (car lst)) (setq lst (cdr lst)) (setq go nil)))
(seq-into lst (seq--type-of seq))))
(defun seq-contains (seq elt &optional testfn)
;; Deprecated in Emacs but still provided: returns the matching element.
(let ((test (or testfn #'equal)) (l (append seq nil)) (res nil))
(while (and l (null res))
(when (funcall test elt (car l)) (setq res (car l)))
(setq l (cdr l)))
res))
;;; ---- cl-lib (subset) ----
(defun cl-mapcar (fn &rest seqs)
(apply (function seq-mapn) fn (mapcar (lambda (s) (append s nil)) seqs)))
(defun cl-map (type fn &rest seqs)
"Map FN over SEQS in parallel, collecting results into a sequence of TYPE.
TYPE nil maps for side effects only and returns nil."
(let ((result (apply (function cl-mapcar) fn seqs)))
(if (null type) nil (cl-coerce result type))))
(defun cl-subseq (seq start &optional end) (seq-subseq seq start end))
(defun cl-pairlis (the-keys the-values &optional alist)
;; Pair KEYS with VALUES (stopping at the shorter list), prepended to ALIST.
(nconc (cl-mapcar 'cons the-keys the-values) alist))
(defun cl-remprop (symbol propname)
;; Remove the first PROPNAME/value pair from SYMBOL's plist; return t if one
;; was removed, else nil. Rebuilds the plist rather than splicing in place.
(let ((plist (symbol-plist symbol)) (out nil) (found nil))
(while plist
(if (and (not found) (eq (car plist) propname))
(setq found t)
(setq out (append out (list (car plist) (car (cdr plist))))))
(setq plist (cdr (cdr plist))))
(when found (setplist symbol out))
found))
(defun lax-plist-get (plist prop)
(let ((res nil) (found nil))
(while (and plist (not found))
(if (equal (car plist) prop) (setq res (car (cdr plist)) found t)
(setq plist (cdr (cdr plist)))))
res))
(defun cl-tailp (sublist list)
(let ((res nil))
(while (and (consp list) (not res))
(if (eq list sublist) (setq res t) (setq list (cdr list))))
(or res (eq list sublist))))
(defun cl-ldiff (list sublist)
(let ((res nil))
(while (and (consp list) (not (eq list sublist)))
(setq res (cons (car list) res) list (cdr list)))
(nreverse res)))
(defun cl-getf (plist key &optional default)
(let ((m (plist-member plist key))) (if m (cadr m) default)))
;; Remove the FIRST KEY/value pair from PLIST (eq comparison), like Emacs.
(defun cl--plist-remove-first (plist tag)
(let ((out nil) (removed nil))
(while plist
(if (and (not removed) (eq (car plist) tag))
(setq removed t)
(setq out (cons (cadr plist) (cons (car plist) out))))
(setq plist (cddr plist)))
(nreverse out)))
(defmacro cl-remf (place tag)
"Remove the property TAG from the plist stored in PLACE; return t if present."
`(let ((--cl-remf-- (plist-member ,place ,tag)))
(when --cl-remf-- (setf ,place (cl--plist-remove-first ,place ,tag)))
(and --cl-remf-- t)))
;;; ---- subr-x macros ----
;; Build nested `(let ((VAR VAL)) (if VAR <inner> ELSE))` for a list of BINDINGS,
;; short-circuiting to ELSE the first time a bound value is nil.
(defun if-let--chain (bindings then else)
(if (null bindings) then
(let* ((b (car bindings))
;; Clause forms: SYMBOL (test its value), (SYMBOL VALUE) (bind+test),
;; or (VALUE) — a single-element list that is only tested, not bound.
(test-only (and (consp b) (null (cdr b))))
(var (cond ((not (consp b)) b)
(test-only (make-symbol "if-let"))
(t (car b))))
(val (cond ((not (consp b)) b)
(test-only (car b))
(t (car (cdr b))))))
(list 'let (list (list var val))
(list 'if var (if-let--chain (cdr bindings) then else) else)))))
;; Accept the old single-binding spelling `(VAR VAL)` as well as a binding list.
(defun if-let--norm (spec)
(if (and (consp spec) (symbolp (car spec))) (list spec) spec))
(defmacro if-let* (bindings then &rest else)
(declare (indent 2))
(if-let--chain bindings then (cons 'progn else)))
(defmacro when-let* (bindings &rest body)
(declare (indent 1) (debug if-let*))
(if-let--chain bindings (cons 'progn body) nil))
(defmacro if-let (bindings then &rest else)
(declare (indent 2))
(if-let--chain (if-let--norm bindings) then (cons 'progn else)))
(defmacro when-let (bindings &rest body)
(declare (indent 1) (debug if-let))
(if-let--chain (if-let--norm bindings) (cons 'progn body) nil))
(defmacro named-let (name bindings &rest body)
;; A self-recursive local loop: (named-let f ((i 0)) (if … (f (1+ i)) i)).
(let ((vars (mapcar (function car) bindings))
(vals (mapcar (lambda (b) (car (cdr b))) bindings)))
`(progn (defun ,name ,vars ,@body) (,name ,@vals))))
;; cl-block / cl-return-from (cl-macs.el, 31.1): a LEXICALLY scoped escape. The
;; catch tag is a fresh cons bound to the variable `--cl-block-NAME--', so only
;; a `cl-return-from' written inside BODY can reach it: one in a function called
;; from BODY sees no such variable (`void-variable'), and a closure that outlives
;; its block throws to a tag no `catch' is waiting for (`no-catch'). A body with
;; no side effects drops the block outright, and the `cl--block-wrapper' compiler
;; macro (defined with `cl-define-compiler-macro', below) drops a block nothing
;; returns from. cl-return / cl-dolist / cl-dotimes use the nil block.
(defconst cl--simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
car-safe cdr-safe progn prog1 prog2))
(defconst cl--safe-funcs '(* / % length memq list vector vectorp
< > <= >= = error))
(defun cl--safe-expr-p (x)
"Check if no side effects."
(or (not (and (consp x) (not (memq (car x) '(quote function cl-function)))))
(and (symbolp (car x))
(or (memq (car x) cl--simple-funcs)
(memq (car x) cl--safe-funcs)
(get (car x) 'side-effect-free))
(progn
(while (and (setq x (cdr x)) (cl--safe-expr-p (car x))))
(null x)))))
;; cl-lib.el: `(defalias 'cl--block-wrapper #'identity)' and
;; `(defalias 'cl--block-throw #'throw)'; `defalias' is not defined yet here.
(fset 'cl--block-wrapper 'identity)
(fset 'cl--block-throw 'throw)
(defmacro cl-block (name &rest body)
(declare (indent 1) (debug (symbolp body)))
(if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
(let ((var (intern (format "--cl-block-%s--" name))))
`(cl--block-wrapper
;; Build a unique "tag" in the form of a fresh cons.
;; We include `var' in the cons, just in case it help debugging.
(let ((,var (cons ',var nil)))
(catch ,var
,@body))))))
(defmacro cl-return-from (name &optional result)
(declare (indent 1) (debug (symbolp &optional form)))
(let ((name2 (intern (format "--cl-block-%s--" name))))
`(cl--block-throw ,name2 ,result)))
(defmacro cl-return (&optional value) `(cl-return-from nil ,value))
(defmacro cl-dolist (spec &rest body) `(cl-block nil (dolist ,spec ,@body)))
(defmacro cl-dotimes (spec &rest body) `(cl-block nil (dotimes ,spec ,@body)))
(defmacro cl-pushnew (x place &rest _keys)
;; Add X to the front of PLACE unless already present (by eql). The place is
;; mentioned three times, so its subforms go through `setf--place-once' first.
(let* ((xb (setf--bind1 x))
(b (setf--place-once place))
(p (cdr b))
(xv (cdr xb)))
(list 'let* (append (car xb) (car b))
(list 'if (list 'memql xv p) p
(list 'setf p (list 'cons xv p))))))
;;; ---- help.el usage/docstring helpers (help-add-fundoc-usage &c) ----
;; Faithful ports from lisp/help.el (30.2). cl-defgeneric/cl-defmethod expansion
;; in cl-generic.el calls `help-add-fundoc-usage' to append the "(fn ARGS)" line
;; to a method's docstring; these are the (formerly help-fns.el) helpers it needs.
(defun help--docstring-quote (string)
"Return a doc string that represents STRING.
The result, when formatted by `substitute-command-keys', should equal STRING."
(replace-regexp-in-string "['\\`‘’]" "\\\\=\\&" string))
(defun help--make-usage (function arglist)
(cons (if (symbolp function) function 'anonymous)
(mapcar (lambda (arg)
(cond
;; Parameter name.
((symbolp arg)
(let ((name (symbol-name arg)))
(cond
((string-match "\\`&" name) (bare-symbol arg))
((string-match "\\`_." name)
(intern (upcase (substring name 1))))
(t (intern (upcase name))))))
;; Parameter with a default value (from cl-defgeneric etc).
((and (consp arg)
(symbolp (car arg)))
(cons (intern (upcase (symbol-name (car arg)))) (cdr arg)))
;; Something else.
(t arg)))
arglist)))
;; (define-obsolete-function-alias 'help-make-usage ...) lives after `defalias'
;; is defined below — the alias body calls `defalias' at load time.
(defun help--make-usage-docstring (fn arglist)
(let ((print-escape-newlines t))
(help--docstring-quote (format "%S" (help--make-usage fn arglist)))))
;; `help-split-fundoc' is defined after `pcase' (below) since its body uses it
;; and elisprs expands macros at `defun'-definition time.
(defun help-add-fundoc-usage (docstring arglist)
"Add the usage info to DOCSTRING.
If DOCSTRING already has a usage info, then just return it unchanged.
The usage info is built from ARGLIST. DOCSTRING can be nil.
ARGLIST can also be t or a string of the form \"(FUN ARG1 ARG2 ...)\"."
(unless (stringp docstring) (setq docstring ""))
(if (or (string-match "\n\n(fn\\(\\( .*\\)?)\\)\\'" docstring)
(eq arglist t))
docstring
(concat docstring
(if (string-match "\n?\n\\'" docstring)
(if (< (- (match-end 0) (match-beginning 0)) 2) "\n" "")
"\n\n")
(if (stringp arglist)
(if (string-match "\\`[^ ]+\\(.*\\))\\'" arglist)
(concat "(fn" (match-string 1 arglist) ")")
(error "Unrecognized usage format"))
(help--make-usage-docstring 'fn arglist)))))
;; cl-defstruct registries: --slots maps NAME -> full slot specs (read at
;; macroexpansion to inherit via :include); --parent maps child-tag -> parent-tag
;; (walked at runtime so a subtype satisfies a parent's predicate).
(defvar cl-struct--slots nil)
(defvar cl-struct--parent nil)
;; NAME -> index of its first slot: 1 for a named struct (a record, or a
;; `:type'd one with `:named'), 0 for an unnamed `:type list'/`:type vector'.
(defvar cl-struct--base nil)
;; NAME -> its `:type' option: `list', `vector', or nil for a record. This is
;; cl-macs.el's `cl--struct-class-type', read by `cl-struct-sequence-type' and
;; `cl-struct-slot-info'.
(defvar cl-struct--type nil)
(defun cl-struct--is-a (tag target)
(let ((res nil))
(while (and tag (not res))
(if (eq tag target) (setq res t) (setq tag (cdr (assq tag cl-struct--parent)))))
res))
;; cl-defstruct: a struct is a record #s(NAME slot1 slot2 ...) whose slot 0 is the
;; bare type symbol NAME (so `type-of'/printing/`aref …0' all report NAME, exactly
;; like an Emacs record). Generates the `make-NAME' keyword constructor (with
;; per-slot defaults), `NAME-p' predicate, `NAME-SLOT' accessors (setf-able), and
;; `copy-NAME' copier. Parentage is tracked by bare NAME in `cl-struct--parent'.
(defmacro cl-defstruct (name-spec &rest slots)
(declare (doc-string 2) (indent 1))
;; An optional docstring may precede the slot specs (cl-macs.el pops it via
;; `(if (stringp (car descs)) (pop descs))'). Record it on the struct's plist
;; and drop it so it is not mistaken for a slot.
(let* ((--doc-- (and (stringp (car slots)) (car slots)))
(slots (if --doc-- (cdr slots) slots))
(name (if (consp name-spec) (car name-spec) name-spec))
(sname (symbol-name name))
;; The record's slot-0 type tag is the bare struct NAME (Emacs records).
(tag name)
;; Options: (:constructor NAME) renames the make-NAME constructor;
;; (:conc-name P) overrides the NAME- accessor prefix.
;; Constructors, as cl-macs.el reads the `:constructor' options in
;; order: `(:constructor NAME)' renames the keyword constructor (nil
;; suppresses it); `(:constructor NAME ARGLIST [DOC])' adds a BOA
;; constructor and, when NAME is the keyword constructor's name,
;; replaces it instead. CTOR-OPTS is each option's `(cdr opt)'.
(ctor-opts (let ((os nil))
(when (consp name-spec)
(dolist (opt (cdr name-spec))
(when (and (consp opt) (eq (car opt) :constructor))
(setq os (cons (cdr opt) os)))))
(reverse os)))
;; The keyword constructor's name, or nil when suppressed.
(constructor (let ((c (intern (concat "make-" sname))))
(dolist (args ctor-opts)
(cond ((cdr args) (when (eq (car args) c) (setq c nil)))
(args (setq c (car args)))))
c))
(conc (let ((p (concat sname "-")))
(when (consp name-spec)
(dolist (opt (cdr name-spec))
(when (and (consp opt) (eq (car opt) :conc-name))
(let ((v (car (cdr opt))))
(setq p (cond ((null v) "") ((symbolp v) (symbol-name v)) (t v)))))))
p))
;; (:copier NAME) renames the copy-NAME copier; (:copier nil) suppresses it.
(copier (let ((c (concat "copy-" sname)))
(when (consp name-spec)
(dolist (opt (cdr name-spec))
(when (and (consp opt) (eq (car opt) :copier))
(setq c (and (car (cdr opt)) (symbol-name (car (cdr opt))))))))
c))
;; (:predicate NAME) renames the NAME-p predicate.
(pred (let ((c (concat sname "-p")))
(when (consp name-spec)
(dolist (opt (cdr name-spec))
(when (and (consp opt) (eq (car opt) :predicate) (car (cdr opt)))
(setq c (symbol-name (car (cdr opt)))))))
c))
;; (:include PARENT) inherits PARENT's slots (prepended, same order) and
;; records the tag parentage so the predicate accepts subtypes.
(parent (let ((p nil))
(when (consp name-spec)
(dolist (opt (cdr name-spec))
(when (and (consp opt) (eq (car opt) :include))
(setq p (car (cdr opt))))))
p))
;; (:type list)/(:type vector) select an untagged list or vector
;; representation instead of a record; a bare `:named' in the options
;; puts the type symbol back in slot 0. A record is always named, so
;; without `:type' both of these are fixed. cl-macs.el only generates
;; a predicate for a named struct, and only a named struct's slots are
;; offset by the tag -- BASE is that offset, and it is what makes an
;; unnamed `(:type list)' accessor `(nth 0 x)' rather than `(nth 1 x)'.
(stype (let ((ty nil))
(when (consp name-spec)
(dolist (opt (cdr name-spec))
(when (and (consp opt) (eq (car opt) :type))
(setq ty (car (cdr opt))))))
ty))
(named (or (null stype)
(and (consp name-spec) (memq :named (cdr name-spec)) t)))
(base (if named 1 0))
(parent-slots (and parent (boundp 'cl-struct--slots)
(cdr (assq parent cl-struct--slots))))
(all-slots (append parent-slots slots))
(snames (mapcar (lambda (s) (if (consp s) (car s) s)) all-slots))
(defaults (mapcar (lambda (s) (if (consp s) (car (cdr s)) nil)) all-slots))
;; Per-slot options plist is (cddr SLOT): (:type T :read-only R :documentation D).
;; `:type'/`:documentation' are parsed and ignored for storage (Emacs does
;; not enforce :type at runtime); `:read-only' non-nil makes the slot's
;; setf-expander error, matching cl-macs.el:3257.
(readonly (mapcar (lambda (s) (and (consp s) (plist-get (cdr (cdr s)) :read-only)))
all-slots))
;; cl-macs.el's DESCS: every slot as a `(NAME DEFAULT . OPTS)' spec,
;; led by the tag slot of a named struct. A constructor's lambda list
;; carries it as `&cl-defs (nil . DESCS)', which is how an argument
;; named like a slot defaults to that slot's initform.
(descs (append (and named '((cl-tag-slot)))
(mapcar (lambda (s) (if (consp s) s (list s))) all-slots)))
;; Every constructor as `(NAME ARGLIST DOC)': the BOA constructors in
;; option order, then the keyword constructor over all slots.
(constrs (let ((cs nil))
(dolist (args ctor-opts)
(when (cdr args) (setq cs (cons args cs))))
(when constructor
(setq cs (cons (list constructor (cons '&key (copy-sequence snames))) cs)))
cs))
(forms nil)
;; How an instance is built and how slot J is read and written.
(build (cond ((eq stype 'list) 'list) ((eq stype 'vector) 'vector) (t 'record)))
(tag-args (if named (list (list 'quote tag)) nil)))
;; Record this struct's full (inherited + own) slot specs at macroexpansion
;; time so a later (:include this) can read them.
(setq cl-struct--slots (cons (cons name all-slots) cl-struct--slots))
(setq cl-struct--base (cons (cons name base) cl-struct--base))
(setq cl-struct--type (cons (cons name stype) cl-struct--type))
;; cl-macs.el: a constructor is a `cl-defun' whose lambda list is the
;; option's (or `&key' over every slot for the keyword constructor) behind
;; `&cl-defs (nil . DESCS)'. `cl--transform-lambda' then gives it Emacs's
;; argument semantics: an unsupplied argument named like a slot takes that
;; slot's initform, evaluated only then and in slot order (so an initform
;; may read an earlier slot); an unknown or value-less keyword signals
;; unless `&allow-other-keys'; `&optional (b 7)', `&rest', `&key' and
;; `&aux' mean what they do in any cl lambda list. A slot that is not an
;; argument is filled from its initform. (cl-macs.el uses `cl-defsubst'
;; unless `:noinline'; elisprs has no `cl-defsubst', so the constructor is
;; never inlined and behaves as `(funcall #'make-NAME ...)' does in Emacs.)
(dolist (constr constrs)
(let* ((cname (nth 0 constr)) (args (nth 1 constr)) (doc (nth 2 constr))
(anames (cl--arglist-args args))
(make (let ((ms nil) (sn snames) (df defaults))
(while sn
(setq ms (cons (if (memq (car sn) anames) (car sn) (car df)) ms))
(setq sn (cdr sn) df (cdr df)))
(reverse ms))))
(setq forms
(cons `(cl-defun ,cname (&cl-defs (nil ,@descs) ,@args)
,(if (stringp doc) doc
(format "Constructor for objects of type `%s'." name))
,@(if (cl--safe-expr-p `(progn ,@defaults))
'((declare (side-effect-free t))))
(,build ,@tag-args ,@make))
forms))))
;; cl-macs.el generates a predicate only for a NAMED struct: an unnamed
;; `(:type list)' instance carries nothing to recognize it by, so
;; `(fboundp 'NAME-p)' is nil in Emacs and must be here too.
(when named
;; cl-macs.el registers the predicate as the atomic type's test.
(setq forms (cons `(define-symbol-prop ',name 'cl-deftype-satisfies ',(intern pred)) forms))
(setq forms
(cons (cond
((eq stype 'list)
`(defun ,(intern pred) (--o--)
(and (consp --o--) (cl-struct--is-a (car --o--) ',tag))))
((eq stype 'vector)
`(defun ,(intern pred) (--o--)
(and (vectorp --o--) (> (length --o--) 0)
(cl-struct--is-a (aref --o-- 0) ',tag))))
(t
`(defun ,(intern pred) (--o--)
(and (recordp --o--) (> (length --o--) 0)
(cl-struct--is-a (aref --o-- 0) ',tag)))))
forms)))
;; Record the tag's parent so the predicate accepts subtypes. With an
;; explicit `:include' the parent is that struct; otherwise every "normal"
;; struct implicitly roots at `cl-structure-object' (cl-macs.el defaults
;; `parent-type' to it), which is what makes `cl-struct-p' — the predicate
;; for `cl-structure-object' — accept any struct. The root itself is skipped
;; so it has no self-parent.
(let ((ptag (cond (parent parent)
((not (eq name 'cl-structure-object)) 'cl-structure-object))))
(when ptag
(setq forms (cons `(setq cl-struct--parent
(cons (cons ',tag ',ptag) cl-struct--parent))
forms))))
(when copier
(setq forms (cons `(defun ,(intern copier) (--s--) (copy-sequence --s--)) forms)))
;; Register a `cl-structure-class' so cl-generic's typeof generalizer can
;; dispatch on this struct type (cl-preloaded.el:205). Guarded so the many
;; structs defined before the class registry is bootstrapped are skipped.
(setq forms
(cons `(when (and (fboundp 'cl--struct-new-class)
(cl--find-class 'cl-structure-object))
(put ',name 'cl--class
(cl--struct-new-class
',name ,--doc--
(list (or ,(if parent `(cl--find-class ',parent))
(cl--find-class 'cl-structure-object)))
nil nil nil nil nil nil nil)))
forms))
(let ((j base) (ros readonly))
(dolist (sn snames)
(let ((acc (intern (concat conc (symbol-name sn)))))
(setq forms (cons (if (eq stype 'list)
`(defun ,acc (--s--) (nth ,j --s--))
`(defun ,acc (--s--) (aref --s-- ,j)))
forms))
;; A list-typed slot's setter is `(setcar (nthcdr J S) V)', not `aset',
;; so the two representations need separate registries for `setf'.
(setq forms (cons (if (eq stype 'list)
`(setq cl-struct--slot-list-index
(cons (cons ',acc ,j) cl-struct--slot-list-index))
`(setq cl-struct--slot-index
(cons (cons ',acc ,j) cl-struct--slot-index)))
forms))
(when (car ros)
(setq forms (cons `(setq cl-struct--slot-readonly
(cons ',acc cl-struct--slot-readonly))
forms))))
(setq ros (cdr ros))
(setq j (1+ j))))
`(progn ,@(reverse forms) ',name)))
;; Generic struct-slot introspection (cl-macs.el). Slots are stored as bare
;; symbols (no default) or `(NAME DEFAULT . OPTS)' specs; CL-STRUCT--BASE is the
;; index of the first one. An unknown STRUCT-TYPE is `cl--struct-get-class''s
;; "%S is not a struct name" error.
(defun cl-struct--slots-of (struct-type)
(let ((e (assq struct-type cl-struct--slots)))
(unless e (error "%S is not a struct name" struct-type))
(cdr e)))
(defun cl-struct-sequence-type (struct-type)
"Return the sequence used to build STRUCT-TYPE: `vector', `list', or nil."
(cl-struct--slots-of struct-type)
(cdr (assq struct-type cl-struct--type)))
(defun cl-struct-slot-offset (struct-type slot-name)
(let ((slots (cl-struct--slots-of struct-type))
(i (or (cdr (assq struct-type cl-struct--base)) 1))
(idx nil))
(dolist (s slots)
(when (eq (if (consp s) (car s) s) slot-name) (setq idx i))
(setq i (1+ i)))
(or idx (signal 'cl-struct-unknown-slot (list struct-type slot-name)))))
(defun cl-struct-slot-value (struct-type slot-name inst)
(aref inst (cl-struct-slot-offset struct-type slot-name)))
;; A record's info starts with the bare `(cl-tag-slot)' entry; a `:named'
;; `:type'd struct carries the tag as a real slot, `(cl-tag-slot nil)'; an
;; unnamed one has no tag entry at all.
(defun cl-struct-slot-info (struct-type)
(let ((slots (mapcar (lambda (s) (if (consp s) s (list s nil)))
(cl-struct--slots-of struct-type))))
(cond ((null (cdr (assq struct-type cl-struct--type))) (cons '(cl-tag-slot) slots))
((eq (cdr (assq struct-type cl-struct--base)) 1) (cons '(cl-tag-slot nil) slots))
(t slots))))
(defmacro and-let* (bindings &rest body)
(declare (indent 1) (debug if-let*))
;; Like when-let* but with no body returns the last bound value (SRFI-2).
(if (null bindings)
(cons 'let* (cons nil (or body '(t))))
(if-let--chain bindings
(if body (cons 'progn body)
(let ((lastb (car (last bindings))))
(if (consp lastb) (car lastb) lastb)))
nil)))
;; let-alist (lisp/emacs-lisp/let-alist.el): bind every `.KEY' symbol in BODY to
;; the corresponding value in ALIST. A DOTTED CHAIN descends: `.a.b.c' reads
;; (cdr (assq 'c (cdr (assq 'b (cdr (assq 'a ALIST)))))), so an intermediate
;; that is not a list signals `listp' rather than answering nil. A name with a
;; SECOND leading dot escapes the mechanism: `..a' is the ordinary symbol `.a'.
(defun let-alist--dots (form acc)
(cond
((and (symbolp form) form)
(let ((n (symbol-name form)))
(if (and (> (length n) 1) (eq (aref n 0) ?.) (not (memq form acc)))
(cons form acc) acc)))
((consp form)
(if (eq (car form) 'quote) acc
(let-alist--dots (cdr form) (let-alist--dots (car form) acc))))
(t acc)))
(defun let-alist--remove-dot (symbol)
"SYMBOL without its leading dot."
(let ((name (symbol-name symbol)))
(if (string-prefix-p "." name) (intern (substring name 1)) symbol)))
(defun let-alist--list-to-sexp (list var)
"Turn the key LIST into nested `(cdr (assq KEY ...))' reads of VAR."
(list 'cdr (list 'assq (list 'quote (car list))
(if (cdr list) (let-alist--list-to-sexp (cdr list) var) var))))
(defun let-alist--access-sexp (symbol variable)
"The form that reads SYMBOL's value out of VARIABLE."
(let* ((clean (let-alist--remove-dot symbol))
(name (symbol-name clean)))
;; Still dotted after removing one: `..a' means the plain symbol `.a'.
(if (string-prefix-p "." name)
clean
(let-alist--list-to-sexp
(mapcar #'intern (nreverse (split-string name "[.]"))) variable))))
(defmacro let-alist (alist &rest body)
(let ((var (make-symbol "alist")))
(list 'let (list (list var alist))
(cons 'let
(cons (mapcar (lambda (d) (list d (let-alist--access-sexp d var)))
(let-alist--dots body nil))
body)))))
;; cl-flet / cl-labels: lexical local functions. Rewrite calls to a NAME and
;; #'NAME in BODY into `funcall'/refs of a let-bound lambda. cl-labels also walks
;; the function bodies (so they can recurse / call each other) and binds via
;; setq so the lambdas capture the (by-reference) gensym vars.
;; Drop NAMES from ALIST — the local-function bindings a nested binding form
;; shadows for the extent of its body.
(defun cl-flet--shadow (alist names)
(let ((out nil))
(dolist (a alist) (unless (memq (car a) names) (setq out (cons a out))))
(reverse out)))
(defun cl-flet--walk (form alist)
(cond
((not (consp form)) form)
((eq (car form) 'quote) form)
((eq (car form) 'function)
(let ((a (assq (car (cdr form)) alist)))
(if a (cdr a) form)))
;; A nested cl-flet/cl-flet*/cl-labels rebinds function names. Two things must
;; happen that the generic descent got wrong:
;; 1. its BINDING LIST is not a list of call sites. `(cl-flet ((f (n) …)) …)'
;; nested inside an outer `cl-flet' binding `f' had its own binding head
;; rewritten to `(funcall G_outer (n) …)', which then failed to compile
;; with "malformed lambda list".
;; 2. the names it binds SHADOW ours inside it, so calls in its body must be
;; left for the nested form's own walk to rewrite.
;; A `cl-flet' binding's body sees the OUTER functions (the new names are not
;; in scope yet); a `cl-labels' binding's body sees the inner ones, so it can
;; recurse.
((memq (car form) '(cl-flet cl-flet* cl-labels))
(let* ((binds (car (cdr form)))
(names (mapcar (function car) binds))
(inner (cl-flet--shadow alist names))
(bind-scope (if (eq (car form) 'cl-labels) inner alist)))
(cons (car form)
(cons (mapcar (lambda (b) (cons (car b) (cl-flet--walk (cdr b) bind-scope))) binds)
(cl-flet--walk (cdr (cdr form)) inner)))))
((and (symbolp (car form)) (assq (car form) alist))
(cons 'funcall (cons (cdr (assq (car form) alist)) (cl-flet--walk (cdr form) alist))))
(t (cons (cl-flet--walk (car form) alist) (cl-flet--walk (cdr form) alist)))))
(defun cl-flet--cl-argp (arglist)
;; Non-nil when ARGLIST uses cl-lambda-list features a plain `lambda' can't
;; take: per-arg defaults (cons elements) or &key/&aux/&whole/&allow-other-keys.
(let ((cl nil))
(while (consp arglist)
(when (or (consp (car arglist))
(memq (car arglist) '(&key &aux &whole &allow-other-keys)))
(setq cl t))
(setq arglist (cdr arglist)))
cl))
(defun cl-flet--lambda (spec)
;; SPEC is (ARGLIST . BODY). Build the local-function lambda, routing through
;; `cl-destructuring-bind' when ARGLIST needs full cl-lambda-list handling
;; (matching Emacs cl-flet/cl-labels, which accept cl-lambda-lists).
(if (cl-flet--cl-argp (car spec))
(list 'lambda '(&rest --cl-flet-args--)
(cons 'cl-destructuring-bind
(cons (car spec) (cons '--cl-flet-args-- (cdr spec)))))
(cons 'lambda spec)))
(defun cl-flet--binding-value (spec)
;; SPEC is (cdr BINDING). Per cl-macs.el:2098, a length-1 SPEC is the
;; `(FUNC EXP)' form: EXP is an expression returning the function value to
;; bind (used by cl-generic's `(cl-flet ((cl-call-next-method CNM)) ...)').
;; Otherwise SPEC is `(ARGLIST BODY...)', shorthand for a local lambda.
(if (= (length spec) 1)
(car spec)
(cl-flet--lambda spec)))
(defmacro cl-flet (bindings &rest body)
(let* ((gs (mapcar (lambda (b) (make-symbol (symbol-name (car b)))) bindings))
(alist (cl-mapcar (lambda (b g) (cons (car b) g)) bindings gs)))
`(let ,(cl-mapcar (lambda (b g) (list g (cl-flet--binding-value (cdr b)))) bindings gs)
,@(cl-flet--walk body alist))))
(defmacro cl-flet* (bindings &rest body)
;; Sequential cl-flet: each local function sees the earlier ones.
(if (null bindings)
(cons 'progn body)
`(cl-flet (,(car bindings)) (cl-flet* ,(cdr bindings) ,@body))))
(defmacro cl-labels (bindings &rest body)
(let* ((gs (mapcar (lambda (b) (make-symbol (symbol-name (car b)))) bindings))
(alist (cl-mapcar (lambda (b g) (cons (car b) g)) bindings gs)))
`(let ,(mapcar (lambda (g) (list g nil)) gs)
,@(cl-mapcar (lambda (b g) (list 'setq g (cl-flet--binding-value (cl-flet--walk (cdr b) alist)))) bindings gs)
,@(cl-flet--walk body alist))))
;; cl-macrolet: local macros. Expand calls to them throughout BODY at expansion
;; time (re-walking each expansion), then leave the rest for the normal pass.
(defun cl-macrolet--walk (form expanders)
(cond
((not (consp form)) form)
((eq (car form) 'quote) form)
((and (symbolp (car form)) (assq (car form) expanders))
(cl-macrolet--walk (apply (cdr (assq (car form) expanders)) (cdr form)) expanders))
(t (cons (cl-macrolet--walk (car form) expanders)
(cl-macrolet--walk (cdr form) expanders)))))
(defmacro cl-macrolet (bindings &rest body)
;; eval each local-macro lambda into a real closure (apply needs a closure,
;; not a raw lambda list), then expand calls to them in BODY.
(let ((expanders (mapcar (lambda (b) (cons (car b) (eval (cons 'lambda (cdr b)) t))) bindings)))
(cons 'progn (cl-macrolet--walk body expanders))))
;; cl-symbol-macrolet: substitute each NAME with its EXPANSION in value position
;; throughout BODY; `(setq NAME v)` becomes `(setf EXPANSION v)`. (No shadowing
;; handling — don't rebind a symbol-macro name with let inside the body.)
(defun cl-symbol-macrolet--setq (pairs alist)
(when pairs
(let* ((sym (car pairs)) (a (assq sym alist)) (place (if a (car (cdr a)) sym)))
(cons place (cons (cl-symbol-macrolet--walk (car (cdr pairs)) alist)
(cl-symbol-macrolet--setq (cdr (cdr pairs)) alist))))))
(defun cl-symbol-macrolet--walk (form alist)
(cond
((symbolp form) (let ((a (assq form alist))) (if a (car (cdr a)) form)))
((not (consp form)) form)
((eq (car form) 'quote) form)
((eq (car form) 'setq) (cons 'setf (cl-symbol-macrolet--setq (cdr form) alist)))
(t (cons (cl-symbol-macrolet--walk (car form) alist)
(cl-symbol-macrolet--walk (cdr form) alist)))))
(defmacro cl-symbol-macrolet (bindings &rest body)
(cons 'progn (cl-symbol-macrolet--walk body bindings)))
(defmacro letrec (bindings &rest body)
(declare (debug let) (indent 1))
;; Bind to nil, then assign — so the (by-reference) closures can recurse / refer
;; to each other.
`(let ,(mapcar (lambda (b) (list (car b) nil)) bindings)
,@(mapcar (lambda (b) (list 'setq (car b) (car (cdr b)))) bindings)
,@body))
(defmacro dlet (bindings &rest body)
(declare (indent 1) (debug let))
;; Dynamic let. (No buffer-local distinction here, so a plain `let'.)
`(let ,bindings ,@body))
(defmacro cl-letf (bindings &rest body)
;; Temporarily set generalized places, restoring them on exit. Each binding is
;; (PLACE [VALUE]); with no VALUE the place is just saved and restored.
;;
;; cl-macs.el special-cases a PLAIN SYMBOL place to an ordinary `let' binding,
;; and that case has to stay a `let': saving the old value first means READING
;; the symbol, so `(cl-letf ((x 1)) x)' on an unbound `x' signalled
;; `void-variable x' instead of answering 1. Symbol places are split out here
;; and bound directly; only generalized places take the save/set/restore path.
(let ((simple nil) (general nil))
(dolist (b bindings)
(if (symbolp (car b)) (setq simple (cons b simple)) (setq general (cons b general))))
(setq simple (reverse simple) general (reverse general))
(let ((olds (mapcar (lambda (_b) (make-symbol "old")) general))
(saves nil) (sets nil) (restores nil))
(cl-mapcar (lambda (b o)
(setq saves (cons (list o (car b)) saves))
(when (cdr b) (setq sets (cons (list 'setf (car b) (car (cdr b))) sets)))
(setq restores (cons (list 'setf (car b) o) restores)))
general olds)
(let ((core (if general
`(let ,(reverse saves)
(unwind-protect (progn ,@(reverse sets) ,@body)
,@(reverse restores)))
`(progn ,@body))))
(if simple `(let ,simple ,core) core)))))
(defmacro cl-letf* (bindings &rest body)
;; Sequential cl-letf: each binding's place is set before the next is saved.
(if (null bindings)
`(progn ,@body)
`(cl-letf (,(car bindings)) (cl-letf* ,(cdr bindings) ,@body))))
(defmacro thread-first (x &rest forms)
(let ((acc x))
(while forms
(let ((form (car forms)))
(setq acc (if (consp form) (cons (car form) (cons acc (cdr form))) (list form acc))))
(setq forms (cdr forms)))
acc))
(defmacro thread-last (x &rest forms)
(let ((acc x))
(while forms
(let ((form (car forms)))
(setq acc (if (consp form) (append form (list acc)) (list form acc))))
(setq forms (cdr forms)))
acc))
;;; ---- more cl-lib / seq / subr-x / functional ----
;; cl-lib.el: a plain-variable place goes straight to `setq', and an omitted
;; increment uses `1+'/`1-' rather than `(+ PLACE 1)'. Routing everything through
;; `setf' printed `(progn (setq x (+ x 1)))' where Emacs prints `(setq x (1+ x))'.
;; cl-macs.el emits `1+'/`1-' for the no-DELTA symbol case, which is what
;; `(macroexpand '(cl-incf x))' => `(setq x (1+ x))' pins. Every other case goes
;; through `setf--rmw', so the place's subforms are evaluated once.
(defmacro cl-incf (place &rest amt)
(if (symbolp place)
(list 'setq place (if amt (list '+ place (car amt)) (list '1+ place)))
(setf--rmw place (lambda (g) (list '+ g (if amt (car amt) 1))))))
(defmacro cl-decf (place &rest amt)
(if (symbolp place)
(list 'setq place (if amt (list '- place (car amt)) (list '1- place)))
(setf--rmw place (lambda (g) (list '- g (if amt (car amt) 1))))))
;; cl-callf: (cl-callf FUNC PLACE ARGS...) -> (setf PLACE (FUNC PLACE ARGS...)).
;; cl-callf2 puts a fixed ARG1 before PLACE in the call.
(defmacro cl-callf (func place &rest args)
(setf--rmw place (lambda (g) (cons func (cons g args)))))
(defmacro cl-callf2 (func arg1 place &rest args)
(setf--rmw place (lambda (g) (cons func (cons arg1 (cons g args))))))
(defmacro cl-locally (&rest body) (cons 'progn body))
;; cl-psetf: evaluate all values first, then assign all places (parallel setf).
(defmacro cl-psetf (&rest pairs)
(let ((binds nil) (sets nil) (ps pairs))
(while ps
(let ((tv (make-symbol "ps")))
(setq binds (cons (list tv (cadr ps)) binds))
(setq sets (cons (list 'setf (car ps) tv) sets))
(setq ps (cddr ps))))
`(let ,(reverse binds) ,@(reverse sets) nil)))
;; cl-psetq is cl-psetf restricted to variables; cl-lib.el defines it as the same
;; expander, so forward to it rather than duplicating the parallel-assign logic.
(defmacro cl-psetq (&rest pairs) `(cl-psetf ,@pairs))
;; cl-rotatef: rotate place values left (last gets the first's old value).
(defmacro cl-rotatef (&rest places)
(if (cdr places)
(let ((tv (make-symbol "rot")) (forms nil) (ps places))
(while (cdr ps)
(setq forms (cons (list 'setf (car ps) (cadr ps)) forms))
(setq ps (cdr ps)))
`(let ((,tv ,(car places)))
,@(reverse forms)
(setf ,(car ps) ,tv)
nil))
nil))
;; cl-shiftf: shift place values left, the last place taking NEWVAL (the final
;; argument); returns the first place's old value.
(defmacro cl-shiftf (&rest args)
(let* ((places (butlast args)) (newval (car (last args)))
(tv (make-symbol "shf")) (forms nil) (ps places))
(while (cdr ps)
(setq forms (cons (list 'setf (car ps) (cadr ps)) forms))
(setq ps (cdr ps)))
`(let ((,tv ,(car places)))
,@(reverse forms)
(setf ,(car ps) ,newval)
,tv)))
(defun cl-first (x) (car x))
(defun cl-fourth (x) (nth 3 x))
(defun cl-fifth (x) (nth 4 x))
(defun cl-sixth (x) (nth 5 x))
(defun cl-seventh (x) (nth 6 x))
(defun cl-eighth (x) (nth 7 x))
(defun cl-ninth (x) (nth 8 x))
(defun cl-tenth (x) (nth 9 x))
(defun cl-mapcan (fn &rest seqs) (apply 'nconc (apply 'cl-mapcar fn seqs)))
(defun cl-acons (key val alist) (cons (cons key val) alist))
(defun cl-list* (&rest args)
(if (null (cdr args)) (car args) (cons (car args) (apply (function cl-list*) (cdr args)))))
(defun seq-map-indexed (fn seq)
(let ((i 0) (out nil) (l (append seq nil)))
(while l (setq out (cons (funcall fn (car l) i) out)) (setq l (cdr l)) (setq i (1+ i)))
(reverse out)))
(defun seq-do-indexed (fn seq)
(let ((i 0) (l (append seq nil)))
(while l (funcall fn (car l) i) (setq l (cdr l)) (setq i (1+ i))))
nil)
(defun seq-keep (fn seq) (seq-filter (function identity) (mapcar fn seq)))
(defun seq-mapcat (fn seq &optional type)
(apply 'seq-concatenate (or type 'list) (mapcar fn (append seq nil))))
(defun seq-mapn (fn &rest seqs)
;; Apply FN across N sequences in parallel, stopping at the shortest:
;; (seq-mapn #'+ '(1 2) '(3 4)) => (4 6). Accepts any sequence types.
(let ((r nil))
;; seq.el converts with `(seq-into s 'list)', which leaves a list as it
;; is: a dotted tail is reached by the `car' walk below, not by `append'.
(setq seqs (mapcar (lambda (s) (seq-into s 'list)) seqs))
(while (not (memq nil seqs))
(setq r (cons (apply fn (mapcar (function car) seqs)) r))
(setq seqs (mapcar (function cdr) seqs)))
(reverse r)))
;; Curve-quote a format TEMPLATE: grave accent => left single quote, apostrophe
;; => right single quote. This is `styled_format's message half (editfns.c), and
;; it is NOT `substitute-command-keys': the two differ on `\=', which
;; `substitute-command-keys' honors as an escape and `format-message' does not.
;; Measured on GNU Emacs 30.2:
;; (format-message "a \\=`b") => "a \\=‘b"
;; (substitute-command-keys "a \\=`b") => "a `b"
(defun --curve-quotes-- (string)
;; help.el `substitute-quotes', which `styled_format' agrees with.
;; The replacement is character for character, so the template's text
;; properties stay where they were.
(and string
(elisprs--carry-text-properties
string
(cond ((eq (text-quoting-style) 'curve)
(string-replace "'" "’" (string-replace "`" "‘" string)))
((eq (text-quoting-style) 'straight) (string-replace "`" "'" string))
(t string)))))
(defun format-message (fmt &rest args)
(apply (function format) (--curve-quotes-- fmt) args))
;; `substitute-command-keys' without a keymap database: the key-substitution
;; constructs need `where-is-internal' (no interactive keymaps here), but the
;; quote translation half is what callers and error reporting actually rely on,
;; and it is exactly the default `text-quoting-style' of `curve'.
;;
;; `\=' quotes the following character and is discarded, so `\=\=' yields `\=',
;; `\=\[' yields `\[', and `\=' + apostrophe yields a plain apostrophe rather
;; than a curved one. A trailing `\=' with nothing after it stays literal.
;; NAMED limitation: \\[COMMAND] / \\{MAP} / \\<MAP> are passed through unchanged.
(defun substitute-command-keys (string &optional _no-face _include-menus)
;; A nil STRING comes back as nil, never as an error: `print_error_message'
;; funnels `(get ERRNAME 'error-message)' through here unconditionally, and an
;; unregistered error symbol has none.
(when string
(let ((i 0) (n (length string)) (out nil) c)
(while (< i n)
(setq c (aref string i))
(cond
((and (eq c ?\\) (< (+ i 2) n) (eq (aref string (1+ i)) ?=))
(push (aref string (+ i 2)) out)
(setq i (+ i 3)))
((and (eq c ?`) (eq (text-quoting-style) 'curve)) (push ?‘ out) (setq i (1+ i)))
((and (eq c ?') (eq (text-quoting-style) 'curve)) (push ?’ out) (setq i (1+ i)))
((and (eq c ?`) (eq (text-quoting-style) 'straight)) (push ?' out) (setq i (1+ i)))
(t (push c out) (setq i (1+ i)))))
(apply (function string) (nreverse out)))))
;; help.el `substitute-quotes'.
(defun substitute-quotes (string)
(cond ((eq (text-quoting-style) 'curve)
(string-replace "`" "‘"
(string-replace "'" "’" string)))
((eq (text-quoting-style) 'straight)
(string-replace "`" "'" string))
(t string)))
;; minibuffer.el `format-prompt' and its format.
(defvar minibuffer-default-prompt-format " (default %s)")
(defun format-prompt (prompt default &rest format-args)
(concat
(if (null format-args)
(substitute-command-keys prompt)
(apply #'format (substitute-command-keys prompt) format-args))
(and default
(or (not (stringp default))
(length> default 0))
(format (substitute-command-keys minibuffer-default-prompt-format)
(if (consp default)
(car default)
default)))
": "))
(defun cl--digitp (c) (and (>= c ?0) (<= c ?9)))
;; value<: a canonical total order within a type (numbers/strings/symbols/lists/
;; vectors); cross-type comparison signals an error, like Emacs 30.
(defun value<--class (x)
(cond ((numberp x) 'number) ((stringp x) 'string)
((or (consp x) (null x)) 'list) ((symbolp x) 'symbol)
((vectorp x) 'vector) (t 'other)))
(defun value< (a b)
(let ((ca (value<--class a)) (cb (value<--class b)))
(unless (eq ca cb) (signal (quote type-mismatch) (list a b)))
(cond
((eq ca 'number) (< a b))
((eq ca 'string) (string< a b))
((eq ca 'symbol) (string< (symbol-name a) (symbol-name b)))
((eq ca 'list)
(cond ((null a) (not (null b)))
((null b) nil)
((value< (car a) (car b)) t)
((value< (car b) (car a)) nil)
(t (value< (cdr a) (cdr b)))))
((eq ca 'vector)
(let ((n (min (length a) (length b))) (i 0) (res 'eq))
(while (and (< i n) (eq res 'eq))
(cond ((value< (aref a i) (aref b i)) (setq res t))
((value< (aref b i) (aref a i)) (setq res nil)))
(setq i (1+ i)))
(if (eq res 'eq) (< (length a) (length b)) res)))
(t (signal (quote type-mismatch) (list a b))))))
;; ── filevercmp ───────────────────────────────────────────────────────────────
;; `string-version-lessp' is `filevercmp (S1, S2) < 0' in Emacs, and filevercmp
;; is gnulib's Debian version-sort, NOT a byte comparison with numeric runs.
;; Comparing raw character codes got the digit runs right and everything else
;; wrong: `(string-version-lessp "a" " ")' is t in Emacs (punctuation sorts
;; AFTER letters) and `(string-version-lessp "." "9")' is t (a lone "." sorts
;; before every other name). The three helpers below are statement-for-statement
;; ports of gnulib lib/filevercmp.c so those rules come out of the algorithm
;; instead of being special-cased.
(defun filevercmp--alpha-p (c) (or (and (>= c ?A) (<= c ?Z)) (and (>= c ?a) (<= c ?z))))
(defun filevercmp--alnum-p (c) (or (cl--digitp c) (filevercmp--alpha-p c)))
;; gnulib `order': the sort weight of the byte at POS. Past the end sorts first,
;; then `~', then any digit (all digits tie — runs are compared numerically
;; below), then letters by code, then every other byte AFTER the letters.
(defun filevercmp--order (s pos len)
(if (= pos len)
-1
(let ((c (aref s pos)))
(cond ((cl--digitp c) 0)
((filevercmp--alpha-p c) c)
((eq c ?~) -2)
;; c + UCHAR_MAX + 1: pushes punctuation past every letter.
(t (+ c 256))))))
;; gnulib `verrevcmp': the Debian version-comparison algorithm. Alternates
;; between a non-digit stretch compared through `filevercmp--order' and a digit
;; run compared numerically (leading zeros skipped, longer run wins).
(defun filevercmp--verrevcmp (s1 n1 s2 n2)
(let ((p1 0) (p2 0) (result nil) (first-diff 0))
(while (and (null result) (or (< p1 n1) (< p2 n2)))
(setq first-diff 0)
(while (and (null result)
(or (and (< p1 n1) (not (cl--digitp (aref s1 p1))))
(and (< p2 n2) (not (cl--digitp (aref s2 p2))))))
(let ((c1 (filevercmp--order s1 p1 n1))
(c2 (filevercmp--order s2 p2 n2)))
(if (/= c1 c2)
(setq result (- c1 c2))
(setq p1 (1+ p1) p2 (1+ p2)))))
(unless result
(while (and (< p1 n1) (eq (aref s1 p1) ?0)) (setq p1 (1+ p1)))
(while (and (< p2 n2) (eq (aref s2 p2) ?0)) (setq p2 (1+ p2)))
(while (and (< p1 n1) (< p2 n2)
(cl--digitp (aref s1 p1)) (cl--digitp (aref s2 p2)))
(when (= first-diff 0)
(setq first-diff (- (aref s1 p1) (aref s2 p2))))
(setq p1 (1+ p1) p2 (1+ p2)))
;; A digit left over on one side means that run is longer, so larger.
(cond ((and (< p1 n1) (cl--digitp (aref s1 p1))) (setq result 1))
((and (< p2 n2) (cl--digitp (aref s2 p2))) (setq result -1))
((/= first-diff 0) (setq result first-diff)))))
(or result 0)))
;; gnulib `file_prefixlen': length of S up to its file suffixes, where a suffix
;; matches "(\.[A-Za-z~][A-Za-z0-9~]*)*$". Comparing prefixes first is why
;; "foo2.png" sorts before "foo12.png".
(defun filevercmp--prefixlen (s n)
(let ((i 0) (prefixlen 0) (done nil))
(while (not done)
(if (= i n)
(setq done t)
(setq i (1+ i))
(setq prefixlen i)
(while (and (< (1+ i) n) (eq (aref s i) ?.)
(let ((c (aref s (1+ i))))
(or (filevercmp--alpha-p c) (eq c ?~))))
(setq i (+ i 2))
(while (and (< i n)
(let ((c (aref s i)))
(or (filevercmp--alnum-p c) (eq c ?~))))
(setq i (1+ i))))))
prefixlen))
;; gnulib `filenvercmp'.
(defun filevercmp--cmp (a b)
(let ((alen (length a)) (blen (length b)))
(cond
;; Empty sorts before everything.
((= alen 0) (if (= blen 0) 0 -1))
((= blen 0) 1)
;; Leading ".": "." sorts first, then "..", then other dotted names, then
;; everything else.
((and (eq (aref a 0) ?.) (not (eq (aref b 0) ?.))) -1)
((and (eq (aref b 0) ?.) (not (eq (aref a 0) ?.))) 1)
((and (eq (aref a 0) ?.) (= alen 1)) (if (= blen 1) 0 -1))
((and (eq (aref b 0) ?.) (= blen 1)) 1)
((and (eq (aref a 0) ?.) (> alen 1) (eq (aref a 1) ?.) (= alen 2))
(if (and (> blen 1) (eq (aref b 1) ?.) (= blen 2)) 0 -1))
((and (eq (aref b 0) ?.) (> blen 1) (eq (aref b 1) ?.) (= blen 2)) 1)
(t
(let* ((ap (filevercmp--prefixlen a alen))
(bp (filevercmp--prefixlen b blen))
;; With both suffixes empty the second pass would repeat the first.
(one-pass (and (= ap alen) (= bp blen)))
(result (filevercmp--verrevcmp a ap b bp)))
(if (or (/= result 0) one-pass)
result
(filevercmp--verrevcmp a alen b blen)))))))
(defun string-version-lessp (s1 s2)
;; `filevercmp (S1, S2) < 0' — see `filevercmp--cmp' above. NOT `string-lessp'
;; with numeric runs: the byte order is `filevercmp--order''s, not ASCII's.
;; fns.c `Fstring_version_lessp' takes SYMBOLP first and uses the print name,
;; then CHECK_STRINGs both operands -- so `t' and `car' are legal arguments
;; ((string-version-lessp "ab" t) => t, comparing "ab" against "t"), while a
;; number is (wrong-type-argument stringp 0), not `sequencep'. Reading the
;; operands with `length'/`aref' alone reported `sequencep' for both.
(if (symbolp s1) (setq s1 (symbol-name s1)))
(if (symbolp s2) (setq s2 (symbol-name s2)))
(unless (stringp s1) (signal 'wrong-type-argument (list 'stringp s1)))
(unless (stringp s2) (signal 'wrong-type-argument (list 'stringp s2)))
(< (filevercmp--cmp s1 s2) 0))
(defun seq-concatenate (type &rest seqs)
;; Concatenate SEQS into one sequence of TYPE (`list', `vector', or `string').
(let ((all nil))
(dolist (s seqs) (setq all (append all (append s nil))))
(cond ((eq type 'list) all)
((eq type 'vector) (vconcat all))
((eq type 'string) (apply (function string) all))
(t (error "Not a sequence type name: %S" type)))))
(defun cl-concatenate (type &rest seqs) (apply #'seq-concatenate type seqs))
;; cl-equalp: like equal but numbers compare with `=' (1 = 1.0) and strings
;; case-insensitively; recurses through conses and vectors. (Characters are
;; integers in elisp, so they compare numerically, like Emacs.)
(defun cl-equalp (x y)
(cond
((and (numberp x) (numberp y)) (= x y))
((and (stringp x) (stringp y)) (string-equal-ignore-case x y))
((and (consp x) (consp y)) (and (cl-equalp (car x) (car y)) (cl-equalp (cdr x) (cdr y))))
((and (vectorp x) (vectorp y))
(and (= (length x) (length y)) (cl-equalp (append x nil) (append y nil))))
(t (equal x y))))
(defun copy-alist (al)
(mapcar (lambda (p) (if (consp p) (cons (car p) (cdr p)) p)) al))
;; substring-no-properties is a native subr (builtins.rs): it is a C subr in
;; Emacs, so `#'substring-no-properties` must print `#<subr …>`, and the subr
;; checks `stringp` before the indices.
;; The human-readable message for an error object (ERROR-SYMBOL . DATA) — a
;; statement-for-statement port of print.c `print_error_message', because every
;; corner of it is observable and none of it follows from the happy path:
;;
;; * ERRNAME is `(car ERR)', so a non-list ERR is `(wrong-type-argument listp ERR)'.
;; * The `error' symbol is special-cased BEFORE any property lookup: DATA
;; becomes `(cdr ERR)' and the MESSAGE is its car, so `(error 1 2)' has the
;; non-string message 1 and reads "peculiar error: 2".
;; * Every other ERRNAME goes through `get', whose CHECK_SYMBOL is what makes
;; `(error-message-string '(1 2))' signal `(wrong-type-argument symbolp 1)'.
;; * TAIL is `cdr-safe', and the loop runs while TAIL is a cons — a dotted tail
;; is dropped, never an error: `(error-message-string '(foo 1 . 2))' is
;; "peculiar error: 1".
;; * A non-string message prints "peculiar error"; an EMPTY message suppresses
;; the separator entirely, so `(error-message-string '(error "" 1 2))' is
;; "1, 2" and not ": 1, 2".
;; * For a `file-error' condition the FIRST datum becomes the message and the
;; rest print with `princ' — as do `end-of-file' and `user-error' data,
;; which is the whole difference between `(user-error "a" "b")' => "a, b"
;; and a *child* of user-error with the same data => "\"a\", \"b\"".
(defun error-message-string (err)
(let ((errname (car err)) (errmsg nil) (file-error nil)
(data err) (tail nil) (out "") (sep ": "))
(if (eq errname 'error)
(progn
(setq data (cdr err))
(unless (consp data) (setq data nil))
(setq errmsg (car data) file-error nil))
(setq errmsg (get errname 'error-message))
;; The substitution result replaces ERRMSG only when it is non-nil.
(let ((subs (substitute-command-keys errmsg)))
(when subs (setq errmsg subs)))
(setq file-error (memq 'file-error (get errname 'error-conditions))))
(setq tail (cdr-safe data))
(when (and file-error (consp tail))
(setq errmsg (car tail) tail (cdr tail)))
(cond
((not (stringp errmsg)) (setq out "peculiar error"))
((> (length errmsg) 0) (setq out errmsg))
(t (setq sep nil)))
(let ((princy (or file-error
(eq errname 'end-of-file)
(eq errname 'user-error))))
(while (consp tail)
(when sep (setq out (concat out sep)))
(setq sep ", ")
(let ((obj (car tail)))
(setq out (concat out (if princy (format "%s" obj) (prin1-to-string obj)))))
(setq tail (cdr tail))))
out))
(defun seq-group-by (fn seq)
;; Faithful port of Emacs `seq-group-by' (seq.el): fold over the REVERSED
;; sequence, prepending newly-seen keys and pushing each element onto its
;; group's cdr. This yields groups in reverse first-encounter order with
;; items in forward order.
(seq-reduce
(lambda (acc elt)
(let* ((key (funcall fn elt)) (cell (assoc key acc)))
(if cell (setcdr cell (cons elt (cdr cell)))
(setq acc (cons (list key elt) acc)))
acc))
(reverse (append seq nil))
nil))
(defun plist-put (plist prop val &optional predicate)
;; Fplist_put: step by two, breaking BEFORE the key test when the cdr is not
;; a cons; overwrite in place on a match; CHECK_TYPE names the WHOLE plist
;; under `plistp' when the walk ends on a non-nil tail -- so both
;; (plist-put '(1) 1 9) and (plist-put '(1 . 2) 1 9) are plistp errors even
;; though the key is present. Otherwise splice a fresh (PROP VAL) cell onto
;; the last pair (nil PLIST returns the new cell bare).
(let ((test (or predicate #'eq)) (prev nil) (tail plist) (r nil) (done nil))
(while (and (not done) (consp tail))
(cond
((not (consp (cdr tail))) (setq done t))
((funcall test (car tail) prop) (setcar (cdr tail) val) (setq r plist done t))
(t (setq prev tail tail (cddr tail)))))
(cond
(r r)
(t
(unless (null tail) (signal 'wrong-type-argument (list 'plistp plist)))
(let ((newcell (cons prop (cons val (if prev (cddr prev) plist)))))
(if (null prev) newcell
(progn (setcdr (cdr prev) newcell) plist)))))))
;; Symbol property lists, backed by a hash table (we have no per-symbol plist
;; slot). Enough for `get`/`put`/`define-error` and the error-condition system.
(defvar symbol-plist--table (make-hash-table :test 'eq))
;; Fget/Fput/Fsymbol_plist/Fsetplist all open with CHECK_SYMBOL, so a non-symbol
;; is `(wrong-type-argument symbolp X)' and never a quiet nil. That check is the
;; whole reason `(error-message-string '(1 2))' signals: print_error_message asks
;; `(get ERRNAME 'error-conditions)' before it can decide anything about ERRNAME.
(defun symbol-plist--check (sym)
(unless (symbolp sym) (signal 'wrong-type-argument (list 'symbolp sym))))
;; A `compiler-macro' property changes how `macroexpand-all' treats every call
;; to SYM, so the host keeps a set of the symbols that have one and only looks
;; the property up for those (see `ElispHost::compiler_macros'). The note is
;; taken here, not in `function-put', because `cl-define-compiler-macro'
;; stores the property with `define-symbol-prop' and plain `put' is just as
;; valid a way to install one: `macroexp--compiler-macro' reads the plist.
(defun put (sym prop val)
(symbol-plist--check sym)
(when (eq prop 'compiler-macro) (--note-compiler-macro sym))
(puthash sym (plist-put (gethash sym symbol-plist--table) prop val) symbol-plist--table)
val)
(defun get (sym prop)
(symbol-plist--check sym)
(plist-get (gethash sym symbol-plist--table) prop))
;; The command line, defined after `put' because a `defvar' docstring is
;; stored with it. `elisp FILE a b c' models `emacs -l FILE a b c', where
;; `command-line-args' is the whole invocation and `command-line-args-left' is
;; what follows the script. Both are (re)set per run by the entry point, since
;; the bytecode cache would otherwise replay the *previous* run's arguments; the
;; values here are the `emacs --eval' answers (nil args-left), which is what
;; `elisp -e' models. `argv' is an alias, not a copy -- startup.el does
;; `(defvaralias 'argv 'command-line-args-left)', so `(setq argv ...)' is visible
;; through both names.
(defvar command-line-args nil
"List of command line arguments, as they were given to this process.")
(defvar command-line-args-left nil
"List of command line arguments not yet processed.")
(defvaralias 'argv 'command-line-args-left
"List of command line arguments not yet processed.")
;; backquote.el marks the two unquote symbols as reader constructs.
(put '\, 'reader-construct t)
(put '\,@ 'reader-construct t)
;; `Fdefine_hash_table_test' (fns.c) is exactly this `put': the declaration
;; lives on NAME's `hash-table-test' property as (TESTFN HASHFN), and
;; `make-hash-table' reads it back. The value is the property list `put'
;; returns, not NAME.
(defun define-hash-table-test (name test hash)
"Define a new hash table test named NAME.
TEST compares two keys; HASH maps a key to a hash value. A table made with
`:test NAME' calls them -- so both are ordinary elisp and may do anything a
function may, `gethash' on such a table included."
(put name 'hash-table-test (list test hash)))
(defun symbol-plist (sym)
(symbol-plist--check sym)
(gethash sym symbol-plist--table))
(defun setplist (sym plist)
(symbol-plist--check sym)
(puthash sym plist symbol-plist--table) plist)
;; Function properties share the symbol plist table. subr.el's `function-get'
;; walks the function-cell alias chain and its `(symbolp f)' guard is what keeps
;; a non-symbol from reaching `get' — `(function-get 1 'x)' is nil, not an error.
(defun function-get (f prop &optional autoload)
(let ((val nil))
(while (and (symbolp f)
(null (setq val (get f prop)))
(fboundp f))
(let ((fundef (symbol-function f)))
(if (and autoload (autoloadp fundef)
(not (equal fundef (autoload-do-load fundef f))))
nil
(setq f fundef))))
val))
(defun function-put (f prop value)
(put f prop value))
(defun define-symbol-prop (symbol prop value) (put symbol prop value))
;; `record'/`make-record' are `Obj::Record' primitives (see builtins.rs); a record
;; is a distinct type from a vector, with the type symbol in slot 0.
(defun define-error (name message &optional parent)
"Define NAME as a new error signal (subr.el).
PARENT is either a signal or a list of signals from which it inherits.
Defaults to `error'. The conditions are de-duplicated, so two parents that
share `error' list it once."
(unless parent (setq parent 'error))
(let ((conditions
(if (consp parent)
(apply #'append
(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))))
;; Seed the standard error symbols (so `error-message-string' / `get' match Emacs).
(define-error 'error "error" nil)
(put 'error 'error-conditions '(error))
(define-error 'user-error "")
(define-error 'quit "Quit" nil)
;; `quit' is NOT an `error': data.c seeds it with `error-conditions' = (quit)
;; alone, which is why `(condition-case nil (signal 'quit nil) (error 'caught))'
;; does not catch it while a `t' handler does. `define-error' defaults a nil
;; PARENT to `error', so the chain has to be overridden here (same shape as the
;; `error' seed above).
(put 'quit 'error-conditions '(quit))
(define-error 'minibuffer-quit "Quit" 'quit)
(define-error 'args-out-of-range "Args out of range")
(define-error 'cl-struct-unknown-slot "struct has no slot")
(define-error 'arith-error "Arithmetic error")
(define-error 'type-mismatch "Types do not match")
(define-error 'wrong-type-argument "Wrong type argument")
(define-error 'wrong-number-of-arguments "Wrong number of arguments")
(define-error 'void-variable "Symbol's value as variable is void")
(define-error 'void-function "Symbol's function definition is void")
(define-error 'invalid-function "Invalid function")
(define-error 'wrong-length-argument "Wrong length argument")
(define-error 'invalid-regexp "Invalid regexp")
(define-error 'cyclic-variable-indirection "Symbol's chain of variable indirections contains a loop")
(define-error 'cl-assertion-failed "Assertion failed")
(define-error 'end-of-file "End of file during parsing")
;; The rest of the data.c/fileio.c seed table, verbatim (messages and parents as
;; `emacs -Q' reports them). Without these an unregistered symbol has no
;; `error-conditions' chain, so `error-message-string' called it a "peculiar
;; error" and `condition-case' could not dispatch a `file-error' handler onto
;; `file-missing' or an `arith-error' handler onto `overflow-error'. The
;; `file-error' family also selects print.c's concatenating branch, where the
;; first datum becomes the message and string data print unquoted.
(define-error 'file-error "File error")
(define-error 'file-missing "File is missing" 'file-error)
(define-error 'file-already-exists "File already exists" 'file-error)
(define-error 'file-date-error "Cannot set file date" 'file-error)
(define-error 'file-notify-error "File notification error" 'file-error)
(define-error 'permission-denied "Cannot access file or directory" 'file-error)
(define-error 'remote-file-error "Remote file error" 'file-error)
(define-error 'range-error "Arithmetic range error" 'arith-error)
(define-error 'overflow-error "Arithmetic overflow error" 'range-error)
(define-error 'search-failed "Search failed")
(define-error 'scan-error "Scan error")
(define-error 'circular-list "List contains a loop")
(define-error 'buffer-read-only "Buffer is read-only")
(define-error 'text-read-only "Text is read-only" 'buffer-read-only)
(define-error 'beginning-of-buffer "Beginning of buffer")
(define-error 'end-of-buffer "End of buffer")
(define-error 'no-catch "No catch for tag")
(define-error 'invalid-read-syntax "Invalid read syntax")
(define-error 'setting-constant "Attempt to set a constant symbol")
(define-error 'recursion-error "Excessive recursive calling error")
(define-error 'excessive-lisp-nesting "Lisp nesting exceeds `max-lisp-eval-depth'" 'recursion-error)
;; The remaining standard error symbols `emacs -Q' seeds (data.c, eval.c,
;; json.c, search.c, ...), messages and parents as Emacs 31.1 reports them.
;; `signal' refuses a symbol with no `error-conditions', so every condition
;; a builtin or library raises must be registered.
(define-error 'excessive-variable-binding "Variable binding depth exceeds max-specpdl-size" 'recursion-error)
(define-error 'domain-error "Arithmetic domain error" 'arith-error)
(define-error 'singularity-error "Arithmetic singularity error" 'domain-error)
(define-error 'underflow-error "Arithmetic underflow error" 'range-error)
(define-error 'cyclic-function-indirection "Symbol's chain of function indirections contains a loop")
(define-error 'inhibited-interaction "User interaction while inhibited")
(define-error 'invalid-arity "Invalid function arity")
(define-error 'malformed-keyword-arg-list "Keyword lacks a corresponding value")
(define-error 'mark-inactive "The mark is not active now")
(define-error 'protected-field "Attempt to modify a protected field")
(define-error 'trapping-constant "Attempt to trap writes to a constant symbol")
(define-error 'user-search-failed "Search failed" '(user-error search-failed))
;; search.c seeds this list literally; `define-error' would put `error' second.
(put 'user-search-failed 'error-conditions '(user-search-failed user-error search-failed error))
(define-error 'json-error "generic JSON error")
(define-error 'json-parse-error "could not parse JSON stream" 'json-error)
(define-error 'json-end-of-file "end of JSON stream" 'json-parse-error)
(define-error 'json-trailing-content "trailing content after JSON stream" 'json-parse-error)
(define-error 'json-escape-sequence-error "invalid escape sequence" 'json-parse-error)
(define-error 'json-invalid-surrogate-error "invalid surrogate pair" 'json-error)
(define-error 'json-number-out-of-range-error "number out of range" 'json-error)
(define-error 'json-object-too-deep "object cyclic or Lisp evaluation too deep" 'json-error)
(define-error 'json-out-of-memory "not enough memory for creating JSON object" 'json-error)
(define-error 'json-utf8-decode-error "invalid utf-8 encoding" 'json-error)
;; eval.c's recursion guard. Reached before the native stack is, so runaway
;; recursion signals `(excessive-lisp-nesting DEPTH)' — which `condition-case'
;; can catch — instead of aborting the process on a stack overflow.
(defvar max-lisp-eval-depth 1600)
;; `when'/`unless' are lowered by the compiler (compiler.rs `compile_when'), so
;; they own no function cell — but in Emacs they are ordinary subr.el macros, and
;; introspection sees that: `(type-of (symbol-function 'when))' is `cons', not
;; `symbol'. Register the same `(macro . FUNCTION)' pair the byte-compiler would
;; have produced, for `symbol-function' / `fboundp' / `indirect-function' only.
;; The bodies are subr.el's:
;; (defmacro when (cond &rest body) (list 'if cond (cons 'progn body)))
;; (defmacro unless (cond &rest body) (cons 'if (cons cond (cons nil body))))
(--set-intrinsic-macro-cell
'when (cons 'macro (lambda (cond &rest body) (list 'if cond (cons 'progn body)))))
(--set-intrinsic-macro-cell
'unless (cons 'macro (lambda (cond &rest body) (cons 'if (cons cond (cons nil body))))))
;; subr.el: (defmacro lambda (&rest cdr) (list 'function (cons 'lambda cdr)))
(--set-intrinsic-macro-cell
'lambda (cons 'macro (lambda (&rest cdr) (list 'function (cons 'lambda cdr)))))
;; byte-run.el's `defmacro' and `defun' are compiler special forms here; their
;; properties are the ones byte-run.el puts and declares.
(function-put 'defmacro 'doc-string-elt 3)
(function-put 'defmacro 'lisp-indent-function 2)
(function-put 'defmacro 'autoload-macro 'expand)
(function-put 'defun 'doc-string-elt 3)
(function-put 'defun 'lisp-indent-function 2)
(function-put 'defun 'autoload-macro 'expand)
;; The subr.el `declare's of the three intrinsic macros above: when/unless
;; `(indent 1) (debug t)', lambda `(doc-string 2) (indent defun) (debug ...)'.
(function-put 'when 'lisp-indent-function 1)
(put 'when 'edebug-form-spec t)
(function-put 'unless 'lisp-indent-function 1)
(put 'unless 'edebug-form-spec t)
(function-put 'lambda 'doc-string-elt 2)
(function-put 'lambda 'lisp-indent-function 'defun)
(put 'lambda 'edebug-form-spec
'(&define lambda-list lambda-doc [&optional ("interactive" interactive)] def-body))
(defun add-to-list (var elt &optional append compare-fn)
"Add ELT to VAR's list value unless it is already there.
VAR should not name a lexical variable -- the compiler macro below rewrites
those call sites, and this function cannot: it reads and writes the SYMBOL's
value cell.
Faithful to subr.el, membership included: the default test is `member', an
explicit `eq'/`eql' COMPARE-FN uses `memq'/`memql', and any other is walked by
hand until it matches. Which of the four runs is observable through a
COMPARE-FN with side effects, and through how many times it is called."
;; subr.el declares the compiler macro here. This prelude is ONE file, and
;; the `declare' bridge (`byte-run--set-compiler-macro') is not defined until
;; much further down -- in Emacs byte-run.el is a separate file loaded first --
;; so a `declare' here would be silently dropped. It is registered by hand
;; below instead; see `add-to-list--anon-cmacro'.
(if (cond
((null compare-fn) (member elt (symbol-value var)))
((eq compare-fn #'eq) (memq elt (symbol-value var)))
((eq compare-fn #'eql) (memql elt (symbol-value var)))
(t (let ((lst (symbol-value var)))
(while (and lst (not (funcall compare-fn elt (car lst))))
(setq lst (cdr lst)))
lst)))
(symbol-value var)
(set var (if append
(append (symbol-value var) (list elt))
(cons elt (symbol-value var))))))
;; equal-including-properties compares text as `equal' does, and additionally
;; requires matching text properties on strings.
(defun equal-including-properties (a b)
(and (equal a b)
(or (not (stringp a))
;; `compare_string_intervals': interval by interval, property values
;; compared with `equal', whatever the two strings' splits are.
(let ((i 0) (n (length a)) (ok t))
(while (and ok (< i n))
(let ((pa (text-properties-at i a)) (pb (text-properties-at i b)))
(unless (and (= (length pa) (length pb))
(let ((p pa) (same t))
(while (and same p)
(let ((cell (plist-member pb (car p))))
(unless (and cell (equal (cadr cell) (cadr p)))
(setq same nil)))
(setq p (cddr p)))
same))
(setq ok nil)))
(setq i (1+ i)))
ok))))
;; `Ftext_property_any' / `Ftext_property_not_all' (textprop.c): the first
;; position in [START, END) where PROP is -- or is not -- `eq' to VALUE, nil if
;; there is none. OBJECT is a buffer or a string, defaulting to the current
;; buffer. An empty range answers nil for both, and a range outside OBJECT is
;; `(args-out-of-range START END)' -- which `get-text-property' already reports.
(defun text-property--validate-range (start end object)
"Signal unless [START, END] lies within OBJECT, as `validate_interval_range' does.
The datum names START and END as GIVEN, which is why the walk cannot just let
`get-text-property' report the first bad position it reaches."
(let ((lo 0) (hi 0))
(if (stringp object)
(setq lo 0 hi (length object))
;; `set-buffer' + `unwind-protect' rather than `with-current-buffer':
;; that macro is defined further down this file, and a macro used before
;; its definition compiles as a CALL ("macro called as a function").
(if (bufferp object)
(let ((old (current-buffer)))
(unwind-protect
(progn (set-buffer object) (setq lo (point-min) hi (point-max)))
(set-buffer old)))
(setq lo (point-min) hi (point-max))))
(unless (and (<= lo (min start end)) (<= (max start end) hi))
(signal 'args-out-of-range (list start end)))))
(defun text-property-any (start end prop value &optional object)
"Return the first position in [START, END) where PROP is `eq' to VALUE."
(text-property--validate-range start end object)
(let ((pos start) (found nil))
(while (and (null found) (< pos end))
(if (eq (get-text-property pos prop object) value)
(setq found pos)
(setq pos (1+ pos))))
found))
(defun text-property-not-all (start end prop value &optional object)
"Return the first position in [START, END) where PROP is not `eq' to VALUE."
(text-property--validate-range start end object)
(let ((pos start) (found nil))
(while (and (null found) (< pos end))
(if (eq (get-text-property pos prop object) value)
(setq pos (1+ pos))
(setq found pos)))
found))
;; `listify-key-sequence' (subr.el). A key sequence may be a vector of events
;; or a string of characters; a UNIBYTE string encodes the meta bit as the high
;; bit, so a character above 127 is converted back to the meta modifier. A
;; multibyte string holds real characters and is taken as-is.
(defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
(defun listify-key-sequence (key)
"Convert the key sequence KEY to a list of events."
(if (or (vectorp key) (multibyte-string-p key))
(append key nil)
(mapcar (lambda (c) (if (> c 127) (logxor c listify-key-sequence-1) c))
key)))
(defun apply-partially (fn &rest args) (lambda (&rest more) (apply fn (append args more))))
(defun complement (fn) (lambda (&rest args) (not (apply fn args))))
(defun cl-constantly (x) (lambda (&rest --ignore--) x))
(defun string-chop-newline (s) (if (string-suffix-p "\n" s) (substring s 0 (- (length s) 1)) s))
(defun pp-to-string (object) (concat (prin1-to-string object) "\n"))
(defun pp (object &optional _stream) (princ (pp-to-string object)) nil)
;; cl-print: elisprs has no special struct/closure rendering, so these fall back
;; to the ordinary printer.
(defun cl-prin1-to-string (object) (prin1-to-string object))
(defun cl-prin1 (object &optional stream) (prin1 object stream))
(defun subst-char-in-string (from to string &optional _inplace)
(concat (mapcar (lambda (c) (if (eq c from) to c)) string)))
(defun string-bytes (s)
;; Number of bytes in the UTF-8 encoding of S.
(let ((n 0) (l (string-to-list s)))
(while l
(let ((c (car l)))
(setq n (+ n (cond ((< c 128) 1) ((< c 2048) 2) ((< c 65536) 3) (t 4)))))
(setq l (cdr l)))
n))
;; `char-width' is a subr (`builtins::char_width_fn'), matching Emacs's
;; `Fchar_width' in indent.c. `format' measures its field width and `%.Ns'
;; precision in display columns and needs the same table from Rust, so keeping a
;; second copy here would have been two implementations of one answer.
(defun string-width (s &optional from to)
;; `string-to-list' accepts any sequence, so the string check has to be explicit:
;; Emacs signals `stringp', not `sequencep'.
(unless (stringp s) (signal 'wrong-type-argument (list 'stringp s)))
;; character.c validates FROM and TO with `validate_subarray', as `substring' does.
(let ((w 0) (l (string-to-list (substring s from to))))
(while l (setq w (+ w (char-width (car l))) l (cdr l)))
w))
(defun cl-type-of (obj)
(cond ((null obj) 'null)
((integerp obj) 'fixnum)
((floatp obj) 'float)
((symbolp obj) 'symbol)
((stringp obj) 'string)
((consp obj) 'cons)
(t (type-of obj))))
(defun number-or-marker-p (x) (or (numberp x) (markerp x)))
(defun integer-or-marker-p (x) (or (integerp x) (markerp x)))
(defun string-pad (s len &optional padding start)
;; Pad S to LENGTH chars with PADDING (default space); pad on the left when
;; START is non-nil, otherwise on the right.
(unless (natnump len) (signal 'wrong-type-argument (list 'natnump len)))
(let ((pad (or padding 32)) (cur (length s)))
(if (>= cur len) s
(let ((fill (make-string (- len cur) pad)))
(if start (concat fill s) (concat s fill))))))
;; A horizontal rule: LENGTH dashes (default 79, the batch text width) + newline.
;; (Emacs returns a string with a face applied; the plain text is returned here.)
(defun make-separator-line (&optional length)
(concat (make-string (or length 79) ?-) "\n"))
(defun string-lines (string &optional omit-nulls keep-newlines)
;; Split STRING into a list of lines on newline. When OMIT-NULLS, drop empty
;; lines; when KEEP-NEWLINES, retain the trailing newline on each line.
(if (equal string "")
(list "")
(let ((lines nil) (start 0) (len (length string)))
(while (< start len)
(let ((nl (string-search "\n" string start)))
(if nl
(progn
(let ((line (substring string start (if keep-newlines (1+ nl) nl))))
(when (or (not omit-nulls) (not (string= line "")))
(push line lines)))
(setq start (1+ nl)))
(let ((line (substring string start)))
(when (or (not omit-nulls) (not (string= line "")))
(push line lines))
(setq start len)))))
(nreverse lines))))
(defun string-glyph-split (string)
;; Split STRING into its glyphs. Without composition tables this is a
;; per-character split, which matches Emacs for non-composed text.
(mapcar #'char-to-string (string-to-list string)))
(defun string-limit (string length &optional end _coding-system)
;; First LENGTH chars of STRING (or last LENGTH when END is non-nil); the whole
;; string if it is already short enough. (Byte-based CODING-SYSTEM unsupported.)
(let ((len (length string)))
(if (<= len length)
string
(if end
(substring string (- len length) len)
(substring string 0 length)))))
(defun string-fill (s len)
;; Greedily wrap S so no line exceeds LEN columns, breaking only at spaces.
(let ((words (split-string s)) (lines nil) (cur ""))
(dolist (w words)
(cond ((string= cur "") (setq cur w))
((<= (+ (length cur) 1 (length w)) len) (setq cur (concat cur " " w)))
(t (push cur lines) (setq cur w))))
(unless (string= cur "") (push cur lines))
(mapconcat 'identity (reverse lines) "\n")))
(defun string-equal-ignore-case (a b)
;; Unlike `string=', this is `compare-strings' underneath in Emacs, which
;; takes only actual strings: (string-equal-ignore-case nil "x") signals
;; `stringp nil' rather than comparing the symbol's name.
(unless (stringp a) (signal 'wrong-type-argument (list 'stringp a)))
(unless (stringp b) (signal 'wrong-type-argument (list 'stringp b)))
(string= (downcase a) (downcase b)))
(defun upcase-initials (s)
"Convert the initial of each word in the argument to upper case.
This means that each word's first character is converted to either
title case or upper case, and the rest are left unchanged.
The argument may be a character or string. The result has the same type."
(char-or-string--check s)
(if (integerp s) (--char-titlecase-1-- s) (--casify-capitalize-- s t)))
(defun string-replace (from to s)
;; Emacs signals on an empty FROMSTRING rather than looping forever.
(if (string-empty-p from) (signal 'wrong-length-argument (list 0))
(let ((out "") (pos (string-search from s)))
(while pos
(setq out (concat out (substring s 0 pos) to))
(setq s (substring s (+ pos (length from)) (length s)))
(setq pos (string-search from s)))
(concat out s))))
;; Shell-like quoting (subr.el): combine strings into one quoted command line and
;; split one back, respecting double-quoted segments (read as elisp string literals).
(defun combine-and-quote-strings (strings &optional separator)
(let* ((sep (or separator " "))
(re (concat "[\\\"]\\|" (regexp-quote sep))))
(mapconcat
(lambda (str)
(if (or (= (length str) 0) (string-match re str))
(concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
str))
strings sep)))
(defun split-string-and-unquote (string &optional separator)
(let ((sep (or separator "[ \t\n\r\f]+"))
(i (string-search "\"" string)))
(if (null i)
(split-string string sep t)
(append (unless (= i 0) (split-string (substring string 0 i) sep t))
(let ((rfs (read-from-string string i)))
(cons (car rfs)
(split-string-and-unquote (substring string (cdr rfs)) sep)))))))
;;; ---- json.el (encode subset) ----
;; Encode elisp data to a JSON string (the forgiving json.el `json-encode' API,
;; not the strict native `json-serialize'). Lists are objects when they look like
;; an alist/plist, else arrays; nil encodes as null; symbols as their name.
(defun json-encode-string (s)
(let ((out "\""))
(dolist (c (string-to-list s))
(setq out (concat out
(cond ((eq c 34) "\\\"")
((eq c 92) "\\\\")
((eq c 8) "\\b")
((eq c 9) "\\t")
((eq c 10) "\\n")
((eq c 12) "\\f")
((eq c 13) "\\r")
((< c 32) (format "\\u%04x" c))
(t (char-to-string c))))))
(concat out "\"")))
(defun json-alist-p (l)
(and (consp l) (let ((ok t)) (dolist (e l) (unless (consp e) (setq ok nil))) ok)))
(defun json-plist-p (l) (and (consp l) (keywordp (car l))))
(defun json--encode-key (k)
(json-encode-string (cond ((stringp k) k)
((keywordp k) (substring (symbol-name k) 1))
((symbolp k) (symbol-name k))
(t (format "%s" k)))))
(defun json--encode-kv (k v) (concat (json--encode-key k) ":" (json-encode v)))
(defun json-encode (object)
(cond
((eq object t) "true")
((eq object json-false) "false")
((eq object json-null) "null")
((null object) "null")
((stringp object) (json-encode-string object))
((keywordp object) (json-encode-string (substring (symbol-name object) 1)))
((numberp object) (number-to-string object))
((hash-table-p object)
(let ((parts nil))
(maphash (lambda (k v) (setq parts (cons (json--encode-kv k v) parts))) object)
(concat "{" (mapconcat (function identity) (nreverse parts) ",") "}")))
((vectorp object)
(concat "[" (mapconcat (function json-encode) (append object nil) ",") "]"))
((json-alist-p object)
(concat "{" (mapconcat (lambda (p) (json--encode-kv (car p) (cdr p))) object ",") "}"))
((json-plist-p object)
(let ((parts nil) (l object))
(while l (setq parts (cons (json--encode-kv (car l) (car (cdr l))) parts)) (setq l (cddr l)))
(concat "{" (mapconcat (function identity) (nreverse parts) ",") "}")))
((listp object) (concat "[" (mapconcat (function json-encode) object ",") "]"))
((symbolp object) (json-encode-string (symbol-name object)))
(t (error "Unknown JSON object: %S" object))))
;; json.el reading (json-read-from-string). Defaults: objects → alists with
;; symbol keys, arrays → vectors, true→t, false→json-false, null→json-null.
(defvar json-object-type 'alist)
(defvar json-array-type 'vector)
(defvar json-key-type nil)
(defvar json-null nil)
(defvar json-false :json-false)
(defun json--skip-ws (s i)
(let ((n (length s)))
(while (and (< i n) (memq (aref s i) '(32 9 10 13))) (setq i (1+ i)))
i))
(defun json--lookahead (s i word)
(and (<= (+ i (length word)) (length s)) (string= (substring s i (+ i (length word))) word)))
(defun json--read-string (s i)
(setq i (1+ i))
(let ((out "") (done nil))
(while (not done)
(let ((c (aref s i)))
(cond
((eq c 34) (setq i (1+ i) done t))
((eq c 92)
(setq i (1+ i))
(let ((e (aref s i)))
(if (eq e ?u)
(setq out (concat out (char-to-string (string-to-number (substring s (1+ i) (+ i 5)) 16)))
i (+ i 5))
(setq out (concat out (char-to-string
(cond ((eq e ?n) 10) ((eq e ?t) 9) ((eq e ?r) 13)
((eq e ?b) 8) ((eq e ?f) 12) ((eq e ?/) 47)
(t e))))
i (1+ i)))))
(t (setq out (concat out (char-to-string c)) i (1+ i))))))
(cons out i)))
(defun json--read-number (s i)
(let ((start i) (n (length s)))
(while (and (< i n) (memq (aref s i) '(?- ?+ ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?. ?e ?E)))
(setq i (1+ i)))
(cons (string-to-number (substring s start i)) i)))
(defun json--read-array (s i)
(setq i (json--skip-ws s (1+ i)))
(let ((items nil))
(if (eq (aref s i) ?\])
(setq i (1+ i))
(let ((done nil))
(while (not done)
(let ((r (json--read s i)))
(setq items (cons (car r) items) i (json--skip-ws s (cdr r))))
(cond ((eq (aref s i) ?,) (setq i (json--skip-ws s (1+ i))))
((eq (aref s i) ?\]) (setq i (1+ i) done t))
(t (error "json-read: malformed array"))))))
(setq items (nreverse items))
(cons (if (eq json-array-type 'list) items (vconcat items)) i)))
(defun json--object-key (k)
(cond ((eq json-key-type 'string) k)
((eq json-key-type 'keyword) (intern (concat ":" k)))
(t (intern k))))
(defun json--build-object (pairs)
(cond
((eq json-object-type 'hash-table)
(let ((h (make-hash-table :test 'equal))) (dolist (p pairs) (puthash (car p) (cdr p) h)) h))
((eq json-object-type 'plist)
(let ((out nil)) (dolist (p pairs) (setq out (cons (cdr p) (cons (intern (concat ":" (car p))) out)))) (nreverse out)))
(t (mapcar (lambda (p) (cons (json--object-key (car p)) (cdr p))) pairs))))
(defun json--read-object (s i)
(setq i (json--skip-ws s (1+ i)))
(let ((pairs nil))
(if (eq (aref s i) ?})
(setq i (1+ i))
(let ((done nil))
(while (not done)
(let ((kr (json--read-string s i)))
(setq i (json--skip-ws s (cdr kr)))
(setq i (json--skip-ws s (1+ i))) ; skip the ':'
(let ((vr (json--read s i)))
(setq pairs (cons (cons (car kr) (car vr)) pairs) i (json--skip-ws s (cdr vr)))))
(cond ((eq (aref s i) ?,) (setq i (json--skip-ws s (1+ i))))
((eq (aref s i) ?}) (setq i (1+ i) done t))
(t (error "json-read: malformed object"))))))
(cons (json--build-object (nreverse pairs)) i)))
(defun json--read (s i)
(setq i (json--skip-ws s i))
(let ((c (aref s i)))
(cond
((eq c ?{) (json--read-object s i))
((eq c ?\[) (json--read-array s i))
((eq c 34) (json--read-string s i))
((or (eq c ?-) (and (>= c ?0) (<= c ?9))) (json--read-number s i))
((json--lookahead s i "true") (cons t (+ i 4)))
((json--lookahead s i "false") (cons json-false (+ i 5)))
((json--lookahead s i "null") (cons json-null (+ i 4)))
(t (error "json-read: unexpected character")))))
(defun json-read-from-string (s) (car (json--read s 0)))
;; The native JSON API (`json-parse-string', `json-parse-buffer',
;; `json-serialize', `json-insert') is json.c's, in Rust: src/json.rs.
;;; ---- file names ----
;; `file-name-directory', `file-name-nondirectory', `file-name-as-directory',
;; `directory-file-name', `directory-name-p', `file-name-concat',
;; `file-name-absolute-p' and `expand-file-name' are fileio.c's, in Rust:
;; src/fileio.rs. The Lisp ones below are files.el's (Emacs 31.1) without the
;; file-name-handler dispatch.
(defun file-name-sans-extension (filename)
(save-match-data
(let ((file (file-name-sans-versions (file-name-nondirectory filename)))
directory)
(if (and (string-match "\\.[^.]*\\'" file)
(not (eq 0 (match-beginning 0))))
(if (setq directory (file-name-directory filename))
(concat directory (substring file 0 (match-beginning 0)))
(substring file 0 (match-beginning 0)))
filename))))
(defun file-name-extension (filename &optional period)
(save-match-data
(let ((file (file-name-sans-versions (file-name-nondirectory filename))))
(if (and (string-match "\\.[^.]*\\'" file)
(not (eq 0 (match-beginning 0))))
(substring file (+ (match-beginning 0) (if period 0 1)))
(if period
"")))))
(defun file-name-base (&optional filename)
(file-name-sans-extension
(file-name-nondirectory (or filename (buffer-file-name)))))
;; `temporary-file-directory' (Vtemporary_file_directory, callproc.c
;; `init_callproc') is a C variable read at load time by stock lisp (files.el,
;; jka-compr.el, url-*.el, ...). The Rust primitive returns the raw dir
;; ($TMPDIR if present -- even empty -- else the macOS Darwin per-user temp dir
;; from confstr(_CS_DARWIN_USER_TEMP_DIR), else "/tmp/"); `file-name-as-directory'
;; adds the trailing slash exactly as the C `Ffile_name_as_directory' call does.
;; Values verified against GNU Emacs 30.2 for TMPDIR set/unset/empty.
(defvar temporary-file-directory
(file-name-as-directory (--temp-directory--)))
;; No separate small-file temp dir by default, matching `emacs -Q'.
(defvar small-temporary-file-directory nil)
;; `make-temp-name' (Fmake_temp_name, fileio.c) delegates to
;; `make-temp-file-internal' with DIR-FLAG 0, which calls the gnulib
;; `gen_tempname' (tempname.c) in its GT_NOCREATE mode: it replaces a run of
;; 6 `X's with random characters drawn from the 62-char base
;; "a..zA..Z0..9", and loops (up to 62^3 = 238328 attempts) until the name
;; belongs to no existing file (glibc `try_nocreate' uses lstat, so a broken
;; symlink also counts as existing). The random suffix makes the result
;; non-deterministic, so this matches Emacs's observable contract -- PREFIX +
;; 6 base62 chars naming a nonexistent file -- rather than a fixed value.
(defvar make-temp-name--letters
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
"The 62-char base gnulib `gen_tempname' draws temp-name suffix chars from.")
(defun make-temp-name (prefix)
"Generate temporary file name (string) starting with PREFIX (a string).
This function tries to choose a name that has no existing file.
For this to work, PREFIX should be an absolute file name, and PREFIX
and the returned string should both be non-magic."
(unless (stringp prefix)
(signal 'wrong-type-argument (list 'stringp prefix)))
(let ((attempts 238328) ; 62 * 62 * 62, gnulib ATTEMPTS_MIN
(result nil))
(while (and (null result) (> attempts 0))
(setq attempts (1- attempts))
(let ((candidate prefix)
(i 0))
(while (< i 6)
(setq candidate
(concat candidate
(char-to-string
(aref make-temp-name--letters (random 62)))))
(setq i (1+ i)))
;; lstat semantics: a real file OR a (possibly broken) symlink counts.
(unless (or (file-exists-p candidate) (file-symlink-p candidate))
(setq result candidate))))
(unless result
(signal 'file-error (list "Creating file name with prefix" prefix)))
result))
(defun file-name-split (filename)
(let ((components nil))
(when (directory-name-p filename)
(push "" components)
(setq filename (directory-file-name filename)))
(while (length> filename 0)
(push (file-name-nondirectory filename) components)
(let ((dir (file-name-directory filename)))
(setq filename (and dir (directory-file-name dir)))
(when (and dir (equal dir filename))
(push (if (equal dir "") ""
(substring dir 0 -1))
components)
(setq filename nil))))
components))
(defun file-name-with-extension (filename extension)
(let ((extn (string-trim-left extension "[.]")))
(cond ((string-empty-p filename) (error "Empty filename"))
((string-empty-p extn) (error "Malformed extension: %s" extension))
((directory-name-p filename) (error "Filename is a directory: %s" filename))
(t (concat (file-name-sans-extension filename) "." extn)))))
(defun file-name-parent-directory (filename)
(let* ((expanded (expand-file-name filename))
(parent (file-name-directory (directory-file-name expanded))))
(cond ((or (null parent) (equal parent expanded)) nil)
((not (file-name-absolute-p filename)) (file-relative-name parent))
(t parent))))
(defun file-name-quoted-p (name &optional top)
(let ((file-name-handler-alist (unless top file-name-handler-alist)))
(string-prefix-p "/:" (file-local-name name))))
(defun file-name-quote (name &optional top)
(let ((file-name-handler-alist (unless top file-name-handler-alist)))
(if (file-name-quoted-p name top)
name
(concat (file-remote-p name) "/:" (file-local-name name)))))
(defun file-name-unquote (name &optional top)
(let* ((file-name-handler-alist (unless top file-name-handler-alist))
(localname (file-local-name name)))
(when (file-name-quoted-p localname top)
(setq
localname (if (= (length localname) 2) "/" (substring localname 2))))
(concat (file-remote-p name) localname)))
(defun file-local-name (file)
(or (file-remote-p file 'localname) file))
;; env.el (Emacs 31.1).
;; callproc.c's environment lists (set at startup by src/lib.rs
;; `install_process_environment') and env.el's accessors over them.
;; `locale-coding-system' is UTF-8 here, so env.el's encode/decode steps
;; are the identity and are left out.
(defvar process-environment nil
"List of overridden environment variables for subprocesses to inherit.")
(defvar initial-environment nil
"List of environment variables inherited from the parent process.")
(defun setenv-internal (env variable value keep-empty)
"Set VARIABLE to VALUE in ENV, adding empty entries if KEEP-EMPTY.
Changes ENV by side-effect, and returns its new value."
(declare (important-return-value t))
(let ((pattern (concat "\\`" (regexp-quote variable) "\\(=\\|\\'\\)"))
(case-fold-search nil)
(scan env)
prev found)
;; Handle deletions from the beginning of the list specially.
(if (and (null value)
(not keep-empty)
env
(stringp (car env))
(string-match-p pattern (car env)))
(cdr env)
;; Try to find existing entry for VARIABLE in ENV.
(while (and scan (stringp (car scan)))
(when (string-match-p pattern (car scan))
(if value
(setcar scan (concat variable "=" value))
(if keep-empty
(setcar scan variable)
(setcdr prev (cdr scan))))
(setq found t
scan nil))
(setq prev scan
scan (cdr scan)))
(if (and (not found) (or value keep-empty))
(cons (if value
(concat variable "=" value)
variable)
env)
env))))
(defun setenv (variable &optional value substitute-env-vars)
"Set the value of the environment variable named VARIABLE to VALUE.
VARIABLE should be a string. VALUE is optional; if not provided or
nil, the environment variable VARIABLE will be removed.
SUBSTITUTE-ENV-VARS, if non-nil, means to substitute environment
variables in VALUE with `substitute-env-vars', which see.
The return value is the new value of VARIABLE, or nil if
it was removed from the environment.
This function works by modifying `process-environment'.
As a special case, setting variable `TZ' calls `set-time-zone-rule' as
a side-effect."
(and value
substitute-env-vars
(setq value (substitute-env-vars value)))
(if (string-search "=" variable)
(error "Environment variable name `%s' contains `='" variable))
(if (string-equal "TZ" variable)
(set-time-zone-rule value))
(setq process-environment (setenv-internal process-environment
variable value t))
value)
(defun getenv (variable &optional frame)
"Get the value of environment variable VARIABLE.
VARIABLE should be a string. Value is nil if VARIABLE is undefined in
the environment. Otherwise, value is a string.
If optional parameter FRAME is non-nil, then it should be a
frame. This function will look up VARIABLE in FRAME's `environment'
parameter.
Otherwise, this function searches `process-environment' for
VARIABLE and returns its value if found. If not found, and VARIABLE
is \"DISPLAY\", the function uses the `display' parameter of the selected
frame, and if that is also nil, it searches the `initial-environment' list."
(declare (side-effect-free t))
(getenv-internal variable
(and frame
(assq 'environment
(frame-parameters frame)))))
(defmacro with-environment-variables (variables &rest body)
"Set VARIABLES in the environment and execute BODY.
VARIABLES is a list of variable settings of the form (VAR VALUE),
where VAR is the name of the variable (a string) and VALUE
is its value (also a string).
The previous values will be restored upon exit."
(declare (indent 1) (debug (sexp body)))
(unless (consp variables)
(error "Invalid VARIABLES: %s" variables))
`(let ((process-environment (copy-sequence process-environment)))
,@(mapcar (lambda (elem)
`(setenv ,(car elem) ,(cadr elem)))
variables)
,@body))
(defconst env--substitute-vars-regexp
"\\$\\(?:\\(?1:[[:alnum:]_]+\\)\\|{\\(?1:[^{}]+\\)}\\|\\$\\)")
(defun substitute-env-vars (string &optional when-undefined)
(let ((start 0))
(while (string-match env--substitute-vars-regexp string start)
(cond ((match-beginning 1)
(let* ((var (match-string 1 string))
(value (getenv var)))
(if (and (null value)
(if (functionp when-undefined)
(null (setq value (funcall when-undefined var)))
when-undefined))
(setq start (match-end 0))
(setq string (replace-match (or value "") t t string)
start (+ (match-beginning 0) (length value))))))
(t
(setq string (replace-match "$" t t string)
start (+ (match-beginning 0) 1)))))
string))
(defun substitute-env-in-file-name (filename)
(substitute-env-vars filename
(if (memq system-type '(windows-nt ms-dos))
(lambda (var) (getenv (upcase var)))
t)))
;; fileio.c `search_embedded_absfilename': the index of an absolute file name
;; ("//foo", "/~", "/~user") that follows a `/' inside NM, or nil.
(defun substitute-in-file-name--embedded (nm)
(let ((p 1) (end (length nm)) (found nil))
(while (and (not found) (< p end))
(when (and (eq (aref nm (1- p)) ?/) (file-name-absolute-p (substring nm p)))
(setq found p))
(setq p (1+ p)))
found))
;; fileio.c `Fsubstitute_in_file_name', Unix branch.
(defun substitute-in-file-name (filename)
(unless (stringp filename) (signal 'wrong-type-argument (list 'stringp filename)))
(let ((p (substitute-in-file-name--embedded filename)))
(if p
(substitute-in-file-name (substring filename p))
(let ((tmp (substitute-env-in-file-name filename)))
(unless (stringp tmp) (signal 'wrong-type-argument (list 'stringp tmp)))
(if (eq tmp filename)
filename
(let ((start 0) q)
(while (setq q (substitute-in-file-name--embedded (substring tmp start)))
(setq start (+ start q)))
(if (= start 0) tmp (substring tmp start))))))))
;; POSIX: standard file names need no conversion.
(defun convert-standard-filename (filename) filename)
(defvar default-directory (file-name-as-directory (--current-directory--)))
;; `file-name-handler-alist' (C `Vfile_name_handler_alist', fileio.c): alist of
;; (REGEXP . HANDLER) pairs consulted by file-name operations to dispatch magic
;; file names. The C variable is initialized to nil; the batch default below is
;; the post-loadup set Emacs 30.2 reports under `emacs -Q --batch' — the epa,
;; jka-compr, tramp, and `file-name-non-special' handlers installed at startup.
;; elisprs handles compressed loads in Rust (no dispatch through this alist), so
;; this is data other code reads/rebinds, matching the oracle value-for-value.
(defvar file-name-handler-alist
'(("\\.gpg\\(~\\|\\.~[0-9]+~\\)?\\'" . epa-file-handler)
("\\(?:\\.tzst\\|\\.zst\\|\\.dz\\|\\.txz\\|\\.xz\\|\\.lzma\\|\\.lz\\|\\.g?z\\|\\.\\(?:tgz\\|svgz\\|sifz\\)\\|\\.tbz2?\\|\\.bz2\\|\\.Z\\)\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)?\\'" . jka-compr-handler)
("\\`/\\(?:-\\|[^/:|]\\{2,\\}\\):" . tramp-autoload-file-name-handler)
("\\`/:" . file-name-non-special)))
;; `load' machinery. These are dynamic (special) variables the `load' builtin
;; rebinds around a file's evaluation and restores afterward. At top level
;; `load-file-name'/`load-true-file-name' are nil and `load-in-progress' is nil,
;; matching Emacs. `load-path' is searched for a bare (directory-less) FILE;
;; `load-suffixes' are the extensions tried (elisprs has no bytecode, so `.elc'
;; is never found); crossed with `load-file-rep-suffixes' = `("" ".gz")', so
;; `.el', `.el.gz', the exact name, and its `.gz' variant all resolve.
(defvar load-path nil)
(defvar load-file-name nil)
(defvar load-true-file-name nil)
(defvar load-in-progress nil)
(defvar load-suffixes '(".elc" ".el"))
;; jka-compr (auto-compression-mode, on by default) sets this to `("" ".gz")' so
;; `load' transparently finds and gunzips compressed libraries — the stock Emacs
;; lisp tree ships as `*.el.gz'. The `load' builtin honors the `.gz' rep-suffix.
(defvar load-file-rep-suffixes '("" ".gz"))
;; get-load-suffixes (C `Fget_load_suffixes', lread.c): the cross product of
;; `load-suffixes' with `load-file-rep-suffixes', in the same order the C loop
;; conses then nreverses — suffix0+rep0, suffix0+rep1, suffix1+rep0, ...
(defun get-load-suffixes ()
"Return the list of suffixes that `load' should try, in order."
(let ((lst nil))
(dolist (suffix load-suffixes)
(dolist (ext load-file-rep-suffixes)
(setq lst (cons (concat suffix ext) lst))))
(nreverse lst)))
;; locate-library (subr.el:3153): resolve LIBRARY to the file `load' would pick,
;; searching `load-path' (or PATH) with the load + rep suffixes.
(defun locate-library (library &optional nosuffix path interactive-call)
"Show the precise file name of Emacs library LIBRARY.
LIBRARY should be a relative file name of the library, a string.
Optional second arg NOSUFFIX non-nil means don't add suffixes.
Optional third arg PATH is a list of directories to search instead
of `load-path'."
(let ((file (locate-file library
(or path load-path)
(append (unless nosuffix (get-load-suffixes))
load-file-rep-suffixes))))
(if interactive-call
(if file
(message "Library is file %s" (abbreviate-file-name file))
(message "No library %s in search path" library)))
file))
;; Emacs startup variables (startup.el). `init-file-debug' gates verbose init
;; error reporting; nil by default. `user-init-file'/`user-emacs-directory' are
;; set by real Emacs before init loads — nil here until a caller binds them.
(defvar init-file-debug nil)
(defvar user-init-file nil)
;; custom.el:1216 — searched by `load-theme'/`customize-themes'. Faithful port of
;; the preloaded defvar; value is the literal list `(custom-theme-directory t)'
;; (the two symbols are quoted, not evaluated), matching the real Emacs default.
(defvar custom-theme-load-path (list 'custom-theme-directory t)
"List of directories to search for custom theme files.")
;; files.el (Emacs 31.1). No file name handlers or remote files here, and no
;; DOS drive letters; case folding follows minibuffer.el's default for
;; `read-file-name-completion-ignore-case', which is what files.el consults.
(defvar read-file-name-completion-ignore-case
(if (memq system-type '(ms-dos windows-nt darwin cygwin)) t nil))
(defvar file-name-version-regexp
"\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)")
(defun file-name-sans-versions (name &optional keep-backup-version)
(substring name 0
(unless keep-backup-version
(string-match (concat file-name-version-regexp "\\'")
name))))
(defun file-relative-name (filename &optional directory)
(save-match-data
(setq directory
(file-name-as-directory (expand-file-name (or directory
default-directory))))
(setq filename (expand-file-name filename))
(let ((fold-case read-file-name-completion-ignore-case)
(ancestor ".")
(filename-dir (file-name-as-directory filename)))
(while (not
(or (string-prefix-p directory filename-dir fold-case)
(string-prefix-p directory filename fold-case)))
(setq directory (file-name-directory (substring directory 0 -1))
ancestor (if (equal ancestor ".")
".."
(concat "../" ancestor))))
(if (string-prefix-p directory filename fold-case)
(let ((rest (substring filename (length directory))))
(if (and (equal ancestor ".") (not (equal rest "")))
rest
(concat (file-name-as-directory ancestor) rest)))
ancestor))))
;; files.el (Emacs 31.1), without the file-name-handler dispatch. elisprs
;; strings are all multibyte, so `directory-abbrev-make-regexp' never takes
;; its `decode-coding-string' branch.
(defvar directory-abbrev-alist nil)
(defun directory-abbrev-make-regexp (directory)
(concat "\\`" (regexp-quote directory) "\\(/\\|\\'\\)"))
(defun directory-abbrev-apply (filename)
(dolist (dir-abbrev directory-abbrev-alist filename)
(when (string-match (car dir-abbrev) filename)
(setq filename (concat (cdr dir-abbrev)
(substring filename (match-end 0)))))))
(defvar abbreviated-home-dir nil)
(defun abbreviate-file-name (filename)
(save-match-data
(let ((case-fold-search (file-name-case-insensitive-p filename)))
(setq filename (directory-abbrev-apply filename))
(unless abbreviated-home-dir
(put 'abbreviated-home-dir 'home (expand-file-name "~"))
(setq abbreviated-home-dir
(directory-abbrev-make-regexp
(let ((abbreviated-home-dir "\\`\\'."))
(abbreviate-file-name
(get 'abbreviated-home-dir 'home))))))
(let (mb1)
(if (and (string-match abbreviated-home-dir filename)
(setq mb1 (match-beginning 1))
(not (and (= (match-end 0) 1)
(= (aref filename 0) ?/)))
(not (and (memq system-type '(ms-dos windows-nt cygwin))
(string-match "\\`[a-zA-`]:/\\'" filename)))
(equal (get 'abbreviated-home-dir 'home)
(expand-file-name "~")))
(setq filename
(concat "~"
(substring filename mb1))))
filename))))
;; files.el (Emacs 31.1), without the file-name-handler dispatch. The one
;; `mkdir' is `make-directory-internal' (a Rust subr, fileio.c's).
(defun files--ensure-directory (dir)
"Make directory DIR if it is not already a directory.
Return non-nil if DIR is already a directory."
(condition-case err
(make-directory-internal dir)
(error
(or (file-directory-p dir)
(signal err)))))
(defun make-directory (dir &optional parents)
"Create the directory DIR and optionally any nonexistent parent dirs.
Return non-nil if PARENTS is non-nil and DIR already exists as a
directory, and nil if DIR did not already exist but was created.
Signal an error if unsuccessful."
(setq dir (expand-file-name dir))
(if (not parents)
(make-directory-internal dir)
(let ((dir (directory-file-name (expand-file-name dir)))
already-dir create-list parent)
(while (progn
(setq parent (directory-file-name
(file-name-directory dir)))
(condition-case ()
(ignore (setq already-dir
(files--ensure-directory dir)))
(error
;; Do not loop if root does not exist (Bug#2309).
(not (string= dir parent)))))
(setq create-list (cons dir create-list)
dir parent))
(dolist (dir create-list)
(setq already-dir (files--ensure-directory dir)))
already-dir)))
(defun directory-files (dir &optional full match nosort)
;; Names in DIR (incl. "." ".."), sorted unless NOSORT, filtered by MATCH regexp;
;; with FULL, each name is prefixed with DIR's expanded path (uncollapsed).
(let ((names (--directory-files-- dir match nosort)))
(if full
(let ((d (file-name-as-directory (expand-file-name dir))))
(mapcar (lambda (n) (concat d n)) names))
names)))
;; ── exec-path / file-location subsystem ──────────────────────────────────
;; Faithful port of the process/file-search machinery Emacs builds on:
;; `path-separator', `exec-suffixes', `exec-directory', `exec-path',
;; `invocation-name'/`invocation-directory', `executable-find', `locate-file'
;; (the last two are verbatim from files.el; `locate-file-internal' reimplements
;; the C `openp' search from lread.c). Values match `emacs -Q --batch' on unix
;; for the parts that are OS-defined (path-separator, exec-suffixes) and mirror
;; Emacs's structure for the rest.
(defvar path-separator ":"
"The directory separator in search paths, as a string.")
(defvar exec-suffixes '("")
"List of suffixes to try to find executable file names (empty on POSIX).")
;; Emacs's `exec-directory' is the libexec dir holding its C helper programs;
;; elisprs has none, so it points at the directory of the running `elisp'
;; binary — a sensible, real directory that keeps `exec-path's structure
;; (PATH dirs + exec-directory) intact. `invocation-name'/`invocation-directory'
;; are the binary's basename and directory, mirroring Emacs's C-level values.
(defvar invocation-name (file-name-nondirectory (--invocation-file--))
"The program name that was used to run this instance of elisprs.")
(defvar invocation-directory (file-name-directory (--invocation-file--))
"The directory in which the elisprs executable was found, to run subprocesses.")
(defvar exec-directory (file-name-as-directory (file-name-directory (--invocation-file--)))
"Directory of architecture-dependent files that come with elisprs.")
;; Emacs's `data-directory' is the `etc/' dir of the installation (a string,
;; used by libraries such as `shadow' via `expand-file-name'); elisprs ships no
;; `etc/', so — like `exec-directory' — it points at the running binary's
;; directory, keeping it a real, absolute string.
(defvar data-directory (file-name-as-directory (file-name-directory (--invocation-file--)))
"Directory of machine-independent files that come with elisprs.")
;; Built exactly like Emacs's `init_callproc' (callproc.c): `decode_env_path'
;; on $PATH (splitting on `path-separator', empty elements → ".") followed by
;; `exec-directory' with its trailing slash removed (`directory-file-name').
(defvar exec-path
(append (mapcar (lambda (d) (if (string= d "") "." d))
(split-string (or (getenv "PATH") "") path-separator))
(list (directory-file-name exec-directory)))
"List of directories to search programs to run in subprocesses.")
;; callproc.c; set per run from $SHELL by src/builtins.rs `install_exec_path'.
(defvar shell-file-name "/bin/sh"
"File name to load inferior shells from.
Initialized from the SHELL environment variable, or to a system-dependent
default if SHELL is unset. See Info node `(elisp)Security Considerations'.")
;; simple.el.
(defvar shell-command-switch "-c"
"Switch used to have the shell execute its command line argument.")
;; elisprs models no remote/TRAMP files, so every file name is local: this
;; returns nil for all inputs (Emacs returns nil for local names too), which
;; makes `executable-find's remote branch dead code (as intended here).
(defun file-remote-p (file &optional _identification _connected)
"Test whether FILE specifies a location on a remote system.
elisprs has no remote-file support, so this is always nil."
(ignore file) nil)
(defun locate-file-internal (filename path &optional suffixes predicate)
"Faithful reimplementation of the C `openp' search backing `locate-file'.
Search each directory in PATH, trying each suffix in SUFFIXES (defaulting to
`(\"\")'), for FILENAME. Return the first absolute candidate satisfying
PREDICATE, else nil. PREDICATE nil means `file-readable-p'; an integer is a
POSIX access(2) mode bitmask (1=X_OK 2=W_OK 4=R_OK, 0=existence); a function is
called on the candidate. Directories are skipped unless PREDICATE is a function
that returns the symbol `dir-ok'. An absolute or `~'-prefixed FILENAME is tried
once regardless of PATH."
(let ((suffixes (or suffixes '("")))
(absolute (and (> (length filename) 0) (memq (aref filename 0) '(?/ ?~)))))
(catch 'found
(dolist (dir (if absolute '(nil) path))
(dolist (suffix suffixes)
(let* ((candidate (expand-file-name (concat filename suffix) dir))
(isdir (file-directory-p candidate)))
(cond
((integerp predicate)
(when (and (not isdir) (locate-file--access-ok candidate predicate))
(throw 'found candidate)))
((functionp predicate)
(let ((res (funcall predicate candidate)))
(when (and res (or (not isdir) (eq res 'dir-ok)))
(throw 'found candidate))))
(t
(when (and (not isdir) (file-readable-p candidate))
(throw 'found candidate)))))))
nil)))
(defun locate-file--access-ok (file mode)
"Non-nil if FILE passes the POSIX access(2) MODE bitmask (see `locate-file-internal')."
(and (or (zerop (logand mode 1)) (file-executable-p file))
(or (zerop (logand mode 2)) (file-writable-p file))
(or (zerop (logand mode 4)) (file-readable-p file))
(file-exists-p file)))
(defun locate-file (filename path &optional suffixes predicate)
"Search for FILENAME through PATH.
If found, return the absolute file name of FILENAME; otherwise return nil.
PATH should be a list of directories to look in, like the lists in `exec-path'
or `load-path'. If SUFFIXES is non-nil, it should be a list of suffixes to
append to file name when searching. If SUFFIXES is nil, it is equivalent to
`(\"\")'. If non-nil, PREDICATE is used instead of `file-readable-p'.
PREDICATE can also be an integer access(2) mode, or one of the symbols
`executable', `readable', `writable', `exists', or a list of them."
(if (and predicate (symbolp predicate) (not (functionp predicate)))
(setq predicate (list predicate)))
(when (and (consp predicate) (not (functionp predicate)))
(setq predicate
(logior (if (memq 'executable predicate) 1 0)
(if (memq 'writable predicate) 2 0)
(if (memq 'readable predicate) 4 0))))
(locate-file-internal filename path suffixes predicate))
(defun executable-find (command &optional remote)
"Search for COMMAND in `exec-path' and return the absolute file name.
Return nil if COMMAND is not found anywhere in `exec-path'.
If REMOTE is non-nil, search on a remote host if `default-directory' is
remote, otherwise search locally."
(if (and remote (file-remote-p default-directory))
(let ((res (locate-file
command
(mapcar
(lambda (x) (concat (file-remote-p default-directory) x))
(exec-path))
exec-suffixes 'file-executable-p)))
(when (stringp res) (file-local-name res)))
;; Use 1 rather than file-executable-p to better match the
;; behavior of call-process.
(let ((default-directory (file-name-quote default-directory 'top)))
(locate-file command exec-path exec-suffixes 1))))
;; save-current-buffer: restore the current buffer after BODY (if it is still live).
(defmacro save-current-buffer (&rest body)
`(let ((--scb-- (current-buffer)))
(unwind-protect (progn ,@body)
(when (buffer-live-p --scb--) (set-buffer --scb--)))))
;; with-current-buffer: evaluate BODY with BUFFER-OR-NAME current, restoring after.
(defmacro with-current-buffer (buffer-or-name &rest body)
(declare (indent 1) (debug t))
`(save-current-buffer (set-buffer ,buffer-or-name) ,@body))
;; subr.el (Emacs 31.1), verbatim.
(defmacro with-temp-buffer (&rest body)
"Create a temporary buffer, and evaluate BODY there like `progn'.
The buffer does not run the hooks `kill-buffer-hook',
`kill-buffer-query-functions', and `buffer-list-update-hook'.
See also `with-temp-file' and `with-output-to-string'."
(declare (indent 0) (debug t))
(let ((temp-buffer (make-symbol "temp-buffer")))
`(let ((,temp-buffer (generate-new-buffer " *temp*" t)))
;; `kill-buffer' can change current-buffer in some odd cases.
(with-current-buffer ,temp-buffer
(unwind-protect
(progn ,@body)
(and (buffer-name ,temp-buffer)
(kill-buffer ,temp-buffer)))))))
;; subr.el's `with-output-to-string': BODY prints into a fresh buffer bound as
;; `standard-output', whose text is the value.
(defmacro with-output-to-string (&rest body)
"Execute BODY, return the text it sent to `standard-output', as a string."
(declare (indent 0) (debug t))
`(let ((standard-output (generate-new-buffer " *string-output*" t)))
(unwind-protect
(progn
(let ((standard-output standard-output))
,@body)
(with-current-buffer standard-output
(buffer-string)))
(kill-buffer standard-output))))
;; subr.el (Emacs 31.1): `process-lines' runs PROGRAM through `call-process'.
(defun process-lines-handling-status (program status-handler &rest args)
"Execute PROGRAM with ARGS, returning its output as a list of lines.
If STATUS-HANDLER is non-nil, it must be a function with one
argument, which will be called with the exit status of the
program before the output is collected. If STATUS-HANDLER is
nil, an error is signaled if the program returns with a non-zero
exit status."
(with-temp-buffer
(let ((status (apply #'call-process program nil (current-buffer) nil args)))
(if status-handler
(funcall status-handler status)
(unless (eq status 0)
(error "%s exited with status %s" program status)))
(goto-char (point-min))
(let (lines)
(while (not (eobp))
(setq lines (cons (buffer-substring-no-properties
(line-beginning-position)
(line-end-position))
lines))
(forward-line 1))
(nreverse lines)))))
(defun process-lines (program &rest args)
"Execute PROGRAM with ARGS, returning its output as a list of lines.
Signal an error if the program returns with a non-zero exit status.
Also see `process-lines-ignore-status'."
(apply #'process-lines-handling-status program nil args))
(defun process-lines-ignore-status (program &rest args)
"Execute PROGRAM with ARGS, returning its output as a list of lines.
The exit status of the program is ignored.
Also see `process-lines'."
(apply #'process-lines-handling-status program #'ignore args))
;;; ---- format-spec.el ----
;; Faithful port of format-spec.el (Emacs 30.2). The previous implementation
;; substituted %CHAR and nothing else: it dropped the flag/width/precision
;; syntax silently, so `(format-spec "%-5a|" '((?a . "x")))' answered "5a|" —
;; the width digits fell through as literal text.
(defun format-spec (format specification &optional ignore-missing split)
"Return a string based on FORMAT and SPECIFICATION.
Each %-spec may carry flags, a width and a precision:
%<flags><width><precision>character
Flags: 0 pad with zeros, - pad on the right, < truncate on the left,
> truncate on the right, ^ upcase, _ downcase.
IGNORE-MISSING nil signals on a %-spec with no entry in SPECIFICATION;
`ignore' leaves it verbatim, `delete' removes it. With SPLIT, return the
list of pieces instead of one string."
(with-temp-buffer
(let ((split-start (point-min))
(split-result nil))
(insert format)
(goto-char (point-min))
(while (search-forward "%" nil t)
(cond
;; Quoted percent sign.
((= (following-char) ?%)
(when (memq ignore-missing '(nil ignore delete))
(delete-char 1)))
;; Valid format spec.
((looking-at "\\([ 0<>^_-]+\\)?\\([0-9]+\\)?\\(\\.[0-9]+\\)?\\([[:alpha:]]\\)")
(let* ((beg (point))
(end (match-end 0))
(flags (match-string 1))
(width (match-string 2))
(trunc (match-string 3))
(char (string-to-char (match-string 4)))
(text (let ((res (cdr (assq char specification))))
(if (functionp res) (funcall res) res))))
(when (and split (not (= (1- beg) split-start)))
(push (buffer-substring split-start (1- beg)) split-result))
(cond (text
(setq text (format-spec--do-flags
(format "%s" text)
(format-spec--parse-flags flags)
(and width (string-to-number width))
(and trunc (car (read-from-string trunc 1)))))
;; Insert first, to preserve text properties.
(insert-and-inherit text)
;; Delete the specifier body.
(delete-region (point) (+ end (length text)))
;; Delete the percent sign.
(delete-region (1- beg) beg))
((eq ignore-missing 'delete)
(delete-region (1- beg) end))
((not ignore-missing)
(error "Invalid format character: `%%%c'" char)))
(when split
(push (buffer-substring (1- beg) (point)) split-result)
(setq split-start (point)))))
;; Signal an error on bogus format strings.
((not ignore-missing)
(error "Invalid format string"))))
(if (not split)
(buffer-string)
(unless (= split-start (point-max))
(push (buffer-substring split-start (point-max)) split-result))
(nreverse split-result)))))
(defun format-spec--do-flags (str flags width trunc)
"Return STR formatted according to FLAGS, WIDTH, and TRUNC."
(let (diff str-width)
;; Truncate original string first, like `format' does.
(when trunc
(setq str-width (string-width str))
(when (> (setq diff (- str-width trunc)) 0)
(setq str (if (memq :chop-left flags)
(truncate-string-to-width str str-width diff)
(format (format "%%.%ds" trunc) str))
str-width trunc)))
;; Pad or chop to width.
(when width
(setq str-width (or str-width (string-width str))
diff (- width str-width))
(cond ((zerop diff))
((> diff 0)
(let ((pad (make-string diff (if (memq :pad-zero flags) ?0 ?\s))))
(setq str (if (memq :pad-right flags)
(concat str pad)
(concat pad str)))))
((memq :chop-left flags)
(setq str (truncate-string-to-width str str-width (- diff))))
((memq :chop-right flags)
(setq str (format (format "%%.%ds" width) str))))))
;; Fiddle case.
(cond ((memq :upcase flags) (upcase str))
((memq :downcase flags) (downcase str))
(str)))
(defun format-spec--parse-flags (flags)
"Convert sequence of FLAGS to list of human-readable keywords."
(mapcan (lambda (char)
(cond ((eq char ?0) (list :pad-zero))
((eq char ?-) (list :pad-right))
((eq char ?<) (list :chop-left))
((eq char ?>) (list :chop-right))
((eq char ?^) (list :upcase))
((eq char ?_) (list :downcase))))
flags))
(defun format-spec-make (&rest pairs)
"Return an alist suitable for use in `format-spec' based on PAIRS.
PAIRS is a property list with characters as keys."
(let (alist)
(while pairs
(unless (cdr pairs)
(error "Invalid list of pairs"))
(push (cons (car pairs) (cadr pairs)) alist)
(setq pairs (cddr pairs)))
(nreverse alist)))
;; save-excursion: restore the current buffer AND point after BODY. Point is saved
;; as a marker-like position that tracks insertions/deletions during BODY.
(defmacro save-excursion (&rest body)
`(let ((--se-b-- (current-buffer)))
(--se-push--)
(unwind-protect (progn ,@body)
(when (buffer-live-p --se-b--) (set-buffer --se-b--))
(--se-pop--))))
;; save-restriction: restore the buffer's narrowing after BODY (the saved bounds
;; track edits made in BODY, like Emacs markers).
;; ---- overlays: the subr.el layer over the primitives ----
;; `overlay-recenter' was an optimisation hint for Emacs's old overlay
;; representation; it has been a no-op there since the interval tree landed, and
;; elisprs scans a per-buffer list, so it is one here too.
(defun overlay-recenter (_pos) nil)
(defun copy-overlay (o)
"Return a copy of overlay O, with the same range, buffer and properties."
(let ((o1 (if (overlay-buffer o)
(make-overlay (overlay-start o) (overlay-end o) (overlay-buffer o) nil nil)
;; A detached overlay copies to a detached overlay.
(let ((tmp (make-overlay (point-min) (point-min))))
(delete-overlay tmp)
tmp)))
(props (overlay-properties o)))
(while props
(overlay-put o1 (pop props) (pop props)))
o1))
(defun remove-overlays (&optional beg end name val)
"Remove overlays between BEG and END whose property NAME is `eq' to VAL.
An overlay that only partly overlaps the range is MOVED out of it rather than
removed, and one that spans the range is split in two -- which is why this needs
`copy-overlay' and cannot just delete what `overlays-in' reports."
(unless beg (setq beg (point-min)))
(unless end (setq end (point-max)))
(overlay-recenter end)
(if (< end beg) (setq beg (prog1 end (setq end beg))))
(save-excursion
(dolist (o (overlays-in beg end))
(when (eq (overlay-get o name) val)
(if (< (overlay-start o) beg)
(if (> (overlay-end o) end)
(progn
(move-overlay (copy-overlay o) (overlay-start o) beg)
(move-overlay o end (overlay-end o)))
(move-overlay o (overlay-start o) beg))
(if (> (overlay-end o) end)
(move-overlay o end (overlay-end o))
(delete-overlay o)))))))
(defmacro save-restriction (&rest body)
`(progn (--save-restriction--)
(unwind-protect (progn ,@body) (--restore-restriction--))))
;; Region case conversion: rewrite [BEG,END) through FN. A length-preserving
;; result overwrites the text in place, as casefiddle.c's `casify_region'
;; does (markers, point and text properties stay; one `modify_text' of the
;; whole region); a result of another length is deleted and re-inserted.
(defun buffer--map-region (beg end fn)
(let* ((lo (min beg end)) (hi (max beg end))
(new (funcall fn (buffer-substring-no-properties lo hi))))
(unless (elisprs--replace-chars-in-place lo hi new)
(save-excursion
(let ((s (buffer-substring lo hi)))
(delete-region lo hi)
(goto-char lo)
(insert (funcall fn s)))))))
(defun upcase-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'upcase) nil)
(defun downcase-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'downcase) nil)
(defun capitalize-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'capitalize) nil)
;; casefiddle.c `Fupcase_initials_region': CASE_CAPITALIZE_UP, like `capitalize-region'
;; but leaving the rest of each word as it is.
(defun upcase-initials-region (beg end &optional _region) (interactive (list (region-beginning) (region-end) (region-noncontiguous-p))) (buffer--map-region beg end #'upcase-initials) nil)
;; editfns.c `Fsubst_char_in_region': the text from the first FROMCHAR to END
;; is rewritten in place (one `modify_text' from there), and nothing at all
;; happens when FROMCHAR does not occur.
;; Case-convert ARG words forward from point, leaving point after them.
(defun buffer--case-word (arg fn)
(let ((beg (point)))
(forward-word arg)
(let* ((end (point)) (lo (min beg end)) (hi (max beg end)) (s (buffer-substring lo hi)))
(delete-region lo hi)
(goto-char lo)
(insert (funcall fn s))
(goto-char (+ lo (length s))))))
(defun upcase-word (arg) (interactive "p") (buffer--case-word arg #'upcase) nil)
(defun downcase-word (arg) (interactive "p") (buffer--case-word arg #'downcase) nil)
(defun capitalize-word (arg) (interactive "p") (buffer--case-word arg #'capitalize) nil)
;; The kill ring, ported from simple.el / subr.el (Emacs 31.1). There is no
;; window system here, so the interprogram cut/paste hooks start nil (in
;; `emacs --batch' they are `gui-select-text'/`gui-selection-value', which do
;; nothing there either), and no command loop, so `last-command' stays nil
;; and successive kills never append.
(defvar kill-ring nil)
(defvar kill-ring-max 120)
(defvar kill-ring-yank-pointer nil)
(defvar kill-do-not-save-duplicates nil)
(defvar kill-transform-function nil)
(defvar kill-read-only-ok nil)
(defvar kill-whole-line nil)
(defvar kill-append-merge-undo nil)
(defvar show-trailing-whitespace nil)
(defvar interprogram-cut-function nil)
(defvar interprogram-paste-function nil)
(defvar save-interprogram-paste-before-kill nil)
(defvar yank-pop-change-selection nil)
(defvar yank-excluded-properties
'(category field follow-link fontified font-lock-face help-echo intangible
invisible keymap local-map mouse-face read-only yank-handler))
(defvar yank-transform-functions nil)
(defvar yank-undo-function nil)
(defvar this-command nil)
(defvar last-command nil)
(defvar history-length 100)
(defvar history-delete-duplicates nil)
(defvar-local mark-ring nil)
(defvar mark-ring-max 16)
(defvar filter-buffer-substring-function #'buffer-substring--filter)
(defun add-to-history (history-var newelt &optional maxelt keep-all)
(unless maxelt
(setq maxelt (or (get history-var 'history-length)
history-length)))
(let ((history (symbol-value history-var))
tail)
(when (and (listp history)
(or keep-all
(not (stringp newelt))
(> (length newelt) 0))
(or keep-all
(not (equal (car history) newelt))))
(if history-delete-duplicates
(setq history (delete newelt history)))
(setq history (cons newelt history))
(when (integerp maxelt)
(if (>= 0 maxelt)
(setq history nil)
(setq tail (nthcdr (1- maxelt) history))
(when (consp tail)
(setcdr tail nil))))
(set history-var history))))
(defun remove-list-of-text-properties (start end list-of-properties &optional object)
(remove-text-properties start end
(mapcan (lambda (p) (list p nil)) list-of-properties)
object))
(defun remove-yank-excluded-properties (beg end)
(let ((inhibit-read-only t))
(if (eq yank-excluded-properties t)
(set-text-properties beg end nil)
(remove-list-of-text-properties beg end yank-excluded-properties))))
(defun buffer-substring--filter (beg end &optional delete)
(cond
(delete
(save-excursion
(goto-char beg)
(delete-and-extract-region beg end)))
(t
(buffer-substring beg end))))
(defun filter-buffer-substring (beg end &optional delete)
(funcall filter-buffer-substring-function beg end delete))
(defun kill-new (string &optional replace)
(when (or (not kill-transform-function)
(setq string (funcall kill-transform-function string)))
(unless (and kill-do-not-save-duplicates
(equal-including-properties string (car kill-ring)))
(if (and replace kill-ring)
(setcar kill-ring string)
(let ((history-delete-duplicates nil))
(add-to-history 'kill-ring string kill-ring-max t))))
(setq kill-ring-yank-pointer kill-ring)
(if interprogram-cut-function
(funcall interprogram-cut-function string))))
(defun kill-append (string before-p)
(let ((cur (car kill-ring)))
(kill-new (if before-p (concat string cur) (concat cur string))
(or (= (length cur) 0)
(null (get-text-property 0 'yank-handler cur))))))
(defun current-kill (n &optional do-not-move)
(let ((interprogram-paste (and (= n 0)
interprogram-paste-function
(funcall interprogram-paste-function))))
(if interprogram-paste
(progn
(let ((interprogram-cut-function nil)
(interprogram-paste-function nil))
(if (listp interprogram-paste)
(mapc #'kill-new (reverse interprogram-paste))
(kill-new interprogram-paste)))
(car kill-ring))
(or kill-ring (error "Kill ring is empty"))
(let ((ARGth-kill-element
(nthcdr (mod (- n (length kill-ring-yank-pointer))
(length kill-ring))
kill-ring)))
(unless do-not-move
(setq kill-ring-yank-pointer ARGth-kill-element)
(when (and yank-pop-change-selection
(> n 0)
interprogram-cut-function)
(funcall interprogram-cut-function (car ARGth-kill-element))))
(car ARGth-kill-element)))))
(defun rotate-yank-pointer (arg) (current-kill arg))
(defun kill-region (beg end &optional region)
(condition-case nil
(let ((string (if region
(filter-buffer-substring (region-beginning) (region-end) 'delete)
(filter-buffer-substring beg end 'delete))))
(when string
(if (eq last-command 'kill-region)
(kill-append string (< end beg))
(kill-new string)))
(when (or string (eq last-command 'kill-region))
(setq this-command 'kill-region))
(setq deactivate-mark t)
nil)
((buffer-read-only text-read-only)
(copy-region-as-kill beg end region)
(setq this-command 'kill-region)
(if kill-read-only-ok
(progn (message "Read only text copied to kill ring") nil)
(barf-if-buffer-read-only)
(signal 'text-read-only (list (current-buffer)))))))
(defun copy-region-as-kill (beg end &optional region)
(let ((str (if region
(filter-buffer-substring (region-beginning) (region-end))
(filter-buffer-substring beg end))))
(if (eq last-command 'kill-region)
(kill-append str (< end beg))
(kill-new str)))
(setq deactivate-mark t)
nil)
(defun kill-ring-save (beg end &optional region)
(copy-region-as-kill beg end region)
nil)
(defun barf-if-buffer-read-only (&optional position)
(when (and buffer-read-only
(not inhibit-read-only)
(not (and position (get-text-property position 'inhibit-read-only))))
(signal 'buffer-read-only (list (current-buffer)))))
(defun forward-visible-line (arg)
(condition-case nil
(if (> arg 0)
(while (> arg 0)
(or (zerop (forward-line 1))
(signal 'end-of-buffer nil))
(setq arg (1- arg)))
(let ((first t))
(while (or first (<= arg 0))
(if first
(beginning-of-line)
(or (zerop (forward-line -1))
(signal 'beginning-of-buffer nil)))
(unless (bobp)
(setq arg (1+ arg)))
(setq first nil))))
((beginning-of-buffer end-of-buffer)
nil)))
(defun end-of-visible-line () (end-of-line))
(defun kill-line (&optional arg)
(kill-region (point)
(progn
(if arg
(forward-visible-line (prefix-numeric-value arg))
(if (eobp)
(signal 'end-of-buffer nil))
(let ((end
(save-excursion
(end-of-visible-line) (point))))
(if (or (save-excursion
(unless show-trailing-whitespace
(skip-chars-forward " \t" end))
(= (point) end))
(and kill-whole-line (bolp)))
(forward-visible-line 1)
(goto-char end))))
(point))))
(defun kill-word (arg)
(kill-region (point) (progn (forward-word arg) (point))))
(defun backward-kill-word (arg)
(kill-word (- arg)))
;;; ---- the mark (simple.el, Emacs 31.1) ----
;; `mark-marker' is a Rust subr (the buffer's marker); `region-beginning' and
;; `region-end' are editfns.c's. The C variables keep their batch values.
(defvar transient-mark-mode nil)
(defvar mark-even-if-inactive t)
(defvar select-active-regions t)
(defvar saved-region-selection nil)
(defvar executing-kbd-macro nil)
(defvar last-input-event nil)
(defvar global-mark-ring nil)
(defvar global-mark-ring-max 16)
(defvar use-empty-active-region nil)
(defvar exchange-point-and-mark-highlight-region t)
(defvar activate-mark-hook nil)
(defvar deactivate-mark-hook nil)
(define-error 'mark-inactive "The mark is not active now")
(defun mouse-movement-p (object)
(eq (car-safe object) 'mouse-movement))
;; minibuf.c: no minibuffer is ever active in batch.
(defun minibuffer-depth () 0)
(defvar region-extract-function
(lambda (method)
(let ((beg (region-beginning)))
(cond
((eq method 'bounds)
(list (cons beg (region-end))))
((eq method 'delete-only)
(delete-region beg (region-end)))
(t
(filter-buffer-substring beg (region-end) method))))))
(defun mark (&optional force)
(if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
(marker-position (mark-marker))
(signal 'mark-inactive nil)))
;; Not followed: the PRIMARY-selection update (guarded by
;; `display-selections-p', nil without a window system) and the region
;; highlight of `redisplay--update-region-highlight' (elisprs has no windows).
(defun deactivate-mark (&optional force)
(when (or (region-active-p) force)
(when mark-active (force-mode-line-update))
(cond
((eq (car-safe transient-mark-mode) 'only)
(setq transient-mark-mode (cdr transient-mark-mode))
(if (eq transient-mark-mode (default-value 'transient-mark-mode))
(kill-local-variable 'transient-mark-mode)))
((eq transient-mark-mode 'lambda)
(kill-local-variable 'transient-mark-mode)))
(setq mark-active nil)
(run-hooks 'deactivate-mark-hook)))
(defun activate-mark (&optional no-tmm)
(when (mark t)
(unless (region-active-p)
(force-mode-line-update)
(setq mark-active t)
(unless (or transient-mark-mode no-tmm)
(setq-local transient-mark-mode 'lambda))
(run-hooks 'activate-mark-hook))))
(defun set-mark (pos)
(if pos
(progn
(set-marker (mark-marker) pos (current-buffer))
(activate-mark 'no-tmm))
(deactivate-mark t)
(setq mark-active nil)
(set-marker (mark-marker) nil)))
(defun use-region-p ()
(and (region-active-p)
(or (> (region-end) (region-beginning))
(and use-empty-active-region
(not (eq (car-safe last-input-event) 'down-mouse-1))
(not (mouse-movement-p last-input-event))))))
(defun use-region-beginning ()
(and (use-region-p) (region-beginning)))
(defun use-region-end ()
(and (use-region-p) (region-end)))
(defun use-region-noncontiguous-p ()
(and (use-region-p) (region-noncontiguous-p)))
(defun region-bounds ()
(funcall region-extract-function 'bounds))
(defun region-noncontiguous-p ()
(let ((bounds (region-bounds))) (and (cdr bounds) bounds)))
(defun push-mark (&optional location nomsg activate)
(when (mark t)
(let ((old (nth mark-ring-max mark-ring))
(history-delete-duplicates nil))
(add-to-history 'mark-ring (copy-marker (mark-marker)) mark-ring-max t)
(when old
(set-marker old nil))))
(set-marker (mark-marker) (or location (point)) (current-buffer))
(unless (and global-mark-ring
(eq (marker-buffer (car global-mark-ring)) (current-buffer)))
(let ((old (nth global-mark-ring-max global-mark-ring))
(history-delete-duplicates nil))
(add-to-history
'global-mark-ring (copy-marker (mark-marker)) global-mark-ring-max t)
(when old
(set-marker old nil))))
(or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
(message "Mark set"))
(if (or activate (not transient-mark-mode))
(set-mark (mark t)))
nil)
(defun pop-mark ()
(when mark-ring
(setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
(set-marker (mark-marker) (car mark-ring))
(set-marker (car mark-ring) nil)
(pop mark-ring))
(deactivate-mark))
(defun save-mark-and-excursion--save ()
(cons
(let ((mark (mark-marker)))
(and (marker-position mark) (copy-marker mark)))
mark-active))
(defun save-mark-and-excursion--restore (saved-mark-info)
(let ((saved-mark (car saved-mark-info))
(omark (marker-position (mark-marker)))
(nmark nil)
(saved-mark-active (cdr saved-mark-info)))
(if (null saved-mark)
(set-marker (mark-marker) nil)
(setf nmark (marker-position saved-mark))
(set-marker (mark-marker) nmark)
(set-marker saved-mark nil))
(let ((cur-mark-active mark-active))
(setq mark-active saved-mark-active)
(if saved-mark-active
(when (or (not cur-mark-active)
(not (eq omark nmark)))
(run-hooks 'activate-mark-hook))
(when cur-mark-active
(run-hooks 'deactivate-mark-hook))))))
(defmacro save-mark-and-excursion (&rest body)
(declare (indent 0) (debug t))
(let ((saved-marker-sym (make-symbol "saved-marker")))
`(let ((,saved-marker-sym (save-mark-and-excursion--save)))
(unwind-protect
(save-excursion ,@body)
(save-mark-and-excursion--restore ,saved-marker-sym)))))
;; keyboard.c's `translation-table-for-input' is nil in batch.
(defvar translation-table-for-input nil)
(defun zap-to-char (arg char &optional interactive)
(with-no-warnings
(if (char-table-p translation-table-for-input)
(setq char (or (aref translation-table-for-input char) char))))
(let ((case-fold-search (if (and interactive (char-uppercase-p char))
nil
case-fold-search)))
(kill-region (point) (search-forward (char-to-string char) nil nil arg))))
;; misc.el
(defun zap-up-to-char (arg char &optional interactive)
(let ((direction (if (>= arg 0) 1 -1))
(case-fold-search (if (and interactive (char-uppercase-p char))
nil
case-fold-search)))
(kill-region (point)
(progn
(forward-char direction)
(unwind-protect
(search-forward (char-to-string char) nil nil arg)
(backward-char direction))
(point)))))
(defun kill-whole-line (&optional arg)
(or arg (setq arg 1))
(if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
(signal 'end-of-buffer nil))
(if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
(signal 'beginning-of-buffer nil))
(unless (eq last-command 'kill-region)
(kill-new "")
(setq last-command 'kill-region))
(let ((regions-begin (point-marker))
(region1-end (cond ((zerop arg)
(prog1 (save-excursion
(forward-visible-line 0)
(point-marker))
(end-of-visible-line)))
((< arg 0)
(prog1 (save-excursion
(end-of-visible-line)
(point-marker))
(forward-visible-line (1+ arg))
(unless (bobp) (backward-char))))
(t
(prog1 (save-excursion
(forward-visible-line 0)
(point-marker))
(forward-visible-line arg))))))
(let ((kill-read-only-ok (or kill-read-only-ok
(/= regions-begin (point)))))
(kill-region (marker-position regions-begin)
(marker-position region1-end)))
(kill-region (marker-position regions-begin)
(point))
(set-marker regions-begin nil)
(set-marker region1-end nil)))
(defun mark-word (&optional arg allow-extend)
(cond ((and allow-extend
(or (and (eq last-command this-command) (mark t))
(region-active-p)))
(setq arg (if arg (prefix-numeric-value arg)
(if (< (mark) (point)) -1 1)))
(set-mark
(save-excursion
(goto-char (mark))
(forward-word arg)
(point))))
(t
(push-mark
(save-excursion
(forward-word (prefix-numeric-value arg))
(point))
nil t))))
;; emacs-lisp/lisp.el
(defun mark-sexp (&optional arg allow-extend)
(cond ((and allow-extend
(or (and (eq last-command this-command) (mark t))
(and transient-mark-mode mark-active)))
(setq arg (if arg (prefix-numeric-value arg)
(if (< (mark) (point)) -1 1)))
(set-mark
(save-excursion
(goto-char (mark))
(condition-case error
(forward-sexp arg)
(scan-error
(user-error (if (equal (cadr error)
"Containing expression ends prematurely")
"No more sexp to select"
(cadr error)))))
(point))))
(t
(push-mark
(save-excursion
(condition-case error
(forward-sexp (prefix-numeric-value arg))
(scan-error
(user-error (if (equal (cadr error)
"Containing expression ends prematurely")
"No sexp to select"
(cadr error)))))
(point))
nil t))))
(defun kill-sexp (&optional arg interactive)
(if interactive
(condition-case _
(kill-sexp arg nil)
(scan-error (user-error (if (> arg 0)
"No next sexp"
"No previous sexp"))))
(let ((opoint (point)))
(forward-sexp (or arg 1))
(kill-region opoint (point)))))
(defun backward-kill-sexp (&optional arg interactive)
(kill-sexp (- (or arg 1)) interactive))
(defun upcase-dwim (arg)
(if (use-region-p)
(upcase-region (region-beginning) (region-end) (region-noncontiguous-p))
(upcase-word arg)))
(defun downcase-dwim (arg)
(if (use-region-p)
(downcase-region (region-beginning) (region-end) (region-noncontiguous-p))
(downcase-word arg)))
(defun capitalize-dwim (arg)
(if (use-region-p)
(capitalize-region (region-beginning) (region-end) (region-noncontiguous-p))
(capitalize-word arg)))
(defun exchange-point-and-mark (&optional arg)
(let ((omark (mark t))
(region-was-active (region-active-p))
(temp-highlight (eq (car-safe transient-mark-mode) 'only)))
(if (null omark)
(user-error "No mark set in this buffer"))
(set-mark (point))
(goto-char omark)
(cond (temp-highlight)
((xor arg (if exchange-point-and-mark-highlight-region
(not (region-active-p))
(not region-was-active)))
(deactivate-mark))
(t (activate-mark)))
nil))
(defun insert-for-yank (string)
(run-hook-wrapped 'yank-transform-functions
(lambda (f) (setq string (funcall f string)) nil))
(let (to)
(while (setq to (next-single-property-change 0 'yank-handler string))
(insert-for-yank-1 (substring string 0 to))
(setq string (substring string to))))
(insert-for-yank-1 string))
(defun insert-for-yank-1 (string)
(let* ((handler (and (stringp string)
(get-text-property 0 'yank-handler string)))
(param (or (nth 1 handler) string))
(opoint (point))
end)
(setq yank-undo-function t)
(if (nth 0 handler)
(funcall (car handler) param)
(insert param))
(setq end (point))
(unless (nth 2 handler)
(remove-yank-excluded-properties opoint end))
(if (and (> end opoint)
(text-properties-at (1- end)))
(put-text-property (1- end) end 'rear-nonsticky t))
(if (eq yank-undo-function t)
(setq yank-undo-function (nth 3 handler)))
(if (nth 4 handler)
(setq this-command (nth 4 handler)))))
(defun yank (&optional arg)
(setq yank-window-start (window-start))
(setq this-command t)
(push-mark)
(insert-for-yank (current-kill (cond
((listp arg) 0)
((eq arg '-) -2)
(t (1- arg)))))
(if (consp arg)
(goto-char (prog1 (mark t)
(set-marker (mark-marker) (point) (current-buffer)))))
(if (eq this-command t)
(setq this-command 'yank))
nil)
(defun transpose-chars (arg)
(when (and (eolp) (not (bobp))
(not (get-text-property (1- (point)) 'read-only)))
(forward-char -1))
(transpose-subr #'forward-char arg))
(defun transpose-words (arg)
(transpose-subr 'forward-word arg))
(defun transpose-lines (arg)
(transpose-subr (lambda (arg)
(if (> arg 0)
(progn
(setq arg (forward-line arg))
(if (/= (preceding-char) ?\n)
(setq arg (1+ arg)))
(if (> arg 0)
(newline arg)))
(forward-line arg)))
arg))
(defun transpose-subr (mover arg &optional special)
(let ((aux (if special mover
(lambda (x)
(cons (progn (funcall mover x) (point))
(progn (funcall mover (- x)) (point))))))
pos1 pos2)
(cond
((= arg 0)
(save-excursion
(setq pos1 (funcall aux 1))
(goto-char (or (mark) (error "No mark set in this buffer")))
(setq pos2 (funcall aux 1))
(transpose-subr-1 pos1 pos2))
(goto-char (prog1 (mark t) (set-mark (point)))))
((> arg 0)
(setq pos1 (funcall aux -1))
(setq pos2 (funcall aux arg))
(transpose-subr-1 pos1 pos2)
(goto-char (car pos2)))
(t
(setq pos1 (funcall aux -1))
(goto-char (car pos1))
(setq pos2 (funcall aux arg))
(transpose-subr-1 pos1 pos2)
(goto-char (+ (car pos2) (- (cdr pos1) (car pos1))))))))
(defun transpose-subr-1 (pos1 pos2)
(unless (and pos1 pos2)
(error "Don't have two things to transpose"))
(when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
(when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
(when (> (car pos1) (car pos2))
(let ((swap pos1))
(setq pos1 pos2 pos2 swap)))
(if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
(let* ((word (buffer-substring (car pos2) (cdr pos2)))
(len1 (- (cdr pos1) (car pos1)))
(len2 (length word))
(boundary (make-marker)))
(set-marker boundary (car pos2))
(goto-char (cdr pos1))
(insert-before-markers word)
(setq word (delete-and-extract-region (car pos1) (+ (car pos1) len1)))
(goto-char boundary)
(insert word)
(goto-char (+ boundary len1))
(delete-region (point) (+ (point) len2))
(set-marker boundary nil)))
(defvar inhibit-read-only nil)
(defun buffer-narrowed-p ()
(/= (- (point-max) (point-min)) (buffer-size)))
;; subr.el (Emacs 31.1) motion by whitespace runs and by symbols.
(defun forward-whitespace (arg)
(if (natnump arg)
(re-search-forward "[ \t]+\\|\n" nil 'move arg)
(while (< arg 0)
(if (re-search-backward "[ \t]+\\|\n" nil 'move)
(or (eq (char-after (match-beginning 0)) ?\n)
(skip-chars-backward " \t")))
(setq arg (1+ arg)))))
(defun forward-symbol (arg)
(if (natnump arg)
(re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
(while (< arg 0)
(if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
(skip-syntax-backward "w_"))
(setq arg (1+ arg)))))
(defun forward-same-syntax (&optional arg)
(or arg (setq arg 1))
(while (< arg 0)
(skip-syntax-backward
(char-to-string (char-syntax (char-before))))
(setq arg (1+ arg)))
(while (> arg 0)
(skip-syntax-forward (char-to-string (char-syntax (char-after))))
(setq arg (1- arg))))
;; thingatpt.el (Emacs 31.1): the generic THING machinery and the things
;; that need no window, URL or file-system support.
(defvar thing-at-point-provider-alist nil)
(defvar forward-thing-provider-alist nil)
(defvar bounds-of-thing-at-point-provider-alist nil)
(defun forward-thing (thing &optional n)
(setq n (or n 1))
(if (assq thing forward-thing-provider-alist)
(let* ((backward (< n 0))
(reducer (if backward #'max #'min))
(limit (if backward (point-min) (point-max))))
(catch 'done
(dotimes (_ (abs n))
(let ((new-point (seq-reduce
(lambda (value elt)
(if (eq (car elt) thing)
(save-excursion
(funcall (cdr elt) backward)
(if value
(funcall reducer value (point))
(point)))
value))
forward-thing-provider-alist nil)))
(if (and new-point (/= new-point (point)))
(goto-char new-point)
(goto-char limit)
(throw 'done t))))))
(let ((forward-op (or (get thing 'forward-op)
(intern-soft (format "forward-%s" thing)))))
(if (functionp forward-op)
(funcall forward-op n)
(error "Can't determine how to move over a %s" thing)))))
(defun bounds-of-thing-at-point (thing)
(cond
((seq-some (lambda (elt)
(and (eq (car elt) thing)
(funcall (cdr elt))))
bounds-of-thing-at-point-provider-alist))
((get thing 'bounds-of-thing-at-point)
(funcall (get thing 'bounds-of-thing-at-point)))
((and (not (eq thing 'whitespace))
(save-excursion
(goto-char (point-min))
(not (re-search-forward "[^\t\n ]" nil t))))
nil)
(t
(let ((orig (point)))
(ignore-errors
(save-excursion
(funcall
(or (get thing 'end-op)
(lambda () (forward-thing thing 1))))
(funcall
(or (get thing 'beginning-op)
(lambda () (forward-thing thing -1))))
(let ((beg (point)))
(if (<= beg orig)
(let ((real-end
(progn
(funcall
(or (get thing 'end-op)
(lambda () (forward-thing thing 1))))
(point))))
(when (and (<= orig real-end) (< beg real-end))
(cons beg real-end)))
(goto-char orig)
(funcall
(or (get thing 'beginning-op)
(lambda () (forward-thing thing -1))))
(funcall
(or (get thing 'end-op)
(lambda () (forward-thing thing 1))))
(let ((end (point))
(real-beg
(progn
(funcall
(or (get thing 'beginning-op)
(lambda () (forward-thing thing -1))))
(point))))
(if (and (<= real-beg orig) (<= orig end) (< real-beg end))
(cons real-beg end)))))))))))
(defun thing-at-point (thing &optional no-properties)
(let ((text
(cond
((let ((alist thing-at-point-provider-alist)
elt result)
(while (and alist (null result))
(setq elt (car alist)
alist (cdr alist))
(and (eq (car elt) thing)
(setq result (funcall (cdr elt)))))
result))
((get thing 'thing-at-point)
(funcall (get thing 'thing-at-point)))
(t
(let ((bounds (bounds-of-thing-at-point thing)))
(when bounds
(buffer-substring (car bounds) (cdr bounds))))))))
(when (and text no-properties (sequencep text))
(set-text-properties 0 (length text) nil text))
text))
(defun beginning-of-thing (thing)
(let ((bounds (bounds-of-thing-at-point thing)))
(or bounds (error "No %s here" thing))
(goto-char (car bounds))))
(defun end-of-thing (thing)
(let ((bounds (bounds-of-thing-at-point thing)))
(or bounds (error "No %s here" thing))
(goto-char (cdr bounds))))
(put 'line 'beginning-op
(lambda () (if (bolp) (forward-line -1) (beginning-of-line))))
(defun thing-at-point--end-of-sexp ()
(let ((char-syntax (syntax-after (point))))
(if (or (eq char-syntax ?\))
(and (eq char-syntax ?\") (nth 3 (syntax-ppss))))
(forward-char 1)
(condition-case _
(forward-sexp 1)
(scan-error nil)))))
(put 'sexp 'end-op 'thing-at-point--end-of-sexp)
(defun thing-at-point--beginning-of-sexp ()
(let ((char-syntax (char-syntax (char-before))))
(if (or (eq char-syntax ?\()
(and (eq char-syntax ?\") (nth 3 (syntax-ppss))))
(forward-char -1)
(forward-sexp -1))))
(put 'sexp 'beginning-op 'thing-at-point--beginning-of-sexp)
(put 'symbol 'beginning-op 'thing-at-point--beginning-of-symbol)
(defun thing-at-point--beginning-of-symbol ()
(and (re-search-backward "\\(\\sw\\|\\s_\\)+")
(skip-syntax-backward "w_")))
(put 'list 'bounds-of-thing-at-point 'thing-at-point-bounds-of-list-at-point)
(defun thing-at-point-bounds-of-list-at-point ()
(save-excursion
(if (ignore-errors (up-list -1))
(ignore-errors (cons (point) (progn (forward-sexp) (point))))
(let ((bound (bounds-of-thing-at-point 'sexp)))
(and bound
(<= (car bound) (point)) (< (point) (cdr bound))
bound)))))
(put 'buffer 'end-op (lambda () (goto-char (point-max))))
(put 'buffer 'beginning-op (lambda () (goto-char (point-min))))
(defun thing-at-point-looking-at (regexp &optional distance)
(let* ((old (point))
(beg (if distance (max (point-min) (- old distance)) (point-min)))
(end (if distance (min (point-max) (+ old distance))))
prev match)
(save-excursion
(goto-char beg)
(while (and (setq prev (point)
match (re-search-forward regexp end t))
(< (match-end 0) old))
(goto-char (match-beginning 0))
(unless (< prev (point)) (forward-char))))
(and match (<= (match-beginning 0) old (match-end 0)))))
(defun word-at-point (&optional no-properties)
(thing-at-point 'word no-properties))
(defun thing-at-point--read-from-whole-string (str)
(let* ((read-data (read-from-string str))
(more-left
(condition-case nil
(progn (ignore (read-from-string (substring str (cdr read-data))))
t)
(end-of-file nil))))
(if more-left
(error "Can't read whole string")
(car read-data))))
(defun form-at-point (&optional thing pred)
(let* ((obj (thing-at-point (or thing 'sexp)))
(sexp (if (stringp obj)
(ignore-errors
(thing-at-point--read-from-whole-string obj))
obj)))
(if (or (not pred) (funcall pred sexp)) sexp)))
(defun sexp-at-point ()
(form-at-point 'sexp))
(defun symbol-at-point ()
(let ((thing (thing-at-point 'symbol)))
(if thing (intern thing))))
(defvar thing-at-point-decimal-regexp
"-?[0-9]+\\.?[0-9]*")
(defvar thing-at-point-hexadecimal-regexp
"\\(0x\\|#x\\)\\([a-fA-F0-9]+\\)")
(defun number-at-point ()
(cond
((thing-at-point-looking-at thing-at-point-hexadecimal-regexp 500)
(string-to-number
(buffer-substring (match-beginning 2) (match-end 2))
16))
((thing-at-point-looking-at thing-at-point-decimal-regexp 500)
(string-to-number
(buffer-substring (match-beginning 0) (match-end 0))))))
(put 'number 'bounds-of-thing-at-point
(lambda ()
(and (or (thing-at-point-looking-at thing-at-point-hexadecimal-regexp 500)
(thing-at-point-looking-at thing-at-point-decimal-regexp 500))
(cons (match-beginning 0) (match-end 0)))))
(put 'number 'forward-op 'forward-word)
(put 'number 'thing-at-point 'number-at-point)
(defun list-at-point (&optional ignore-comment-or-string)
(let ((ppss (and ignore-comment-or-string (syntax-ppss))))
(save-excursion
(goto-char (or (nth 8 ppss) (point)))
(form-at-point 'list 'listp))))
;; buffer-hash: a SHA-1 of the buffer contents (BUFFER arg ignored — current only).
(defun buffer-hash (&optional _buffer) (sha1 (buffer-string)))
;; Character at/before point (0 at the buffer's end/start), like Emacs.
(defun following-char () (or (char-after) 0))
(defun preceding-char () (or (char-before) 0))
;; Insert N newlines at point (default 1); like insert, no kill ring.
(defun newline (&optional n _interactive) (insert (make-string (or n 1) ?\n)) nil)
;; Insert N newlines after point, leaving point before them.
(defun open-line (n) (save-excursion (insert (make-string n ?\n))) nil)
;; insert-before-markers: like insert, but markers exactly at point advance past
;; the new text (handled by the primitive --insert-before-markers--).
(defun insert-before-markers (&rest args)
(dolist (a args) (--insert-before-markers-- a))
nil)
(defun count-words (start end)
(length (split-string (buffer-substring start end) "[^[:alnum:]]+" t)))
;; subr.el `replace-string-in-region' / `replace-regexp-in-region': replace in
;; START..END (default point..point-max) with case-fold-search nil, returning the
;; count or nil. The region is a narrowing, so START > END is swapped (Emacs answers
;; nil, not "wrong side of point") and an out-of-range START signals
;; `narrow-to-region''s `(args-out-of-range START END)'.
(defun replace-string-in-region (string replacement &optional start end)
(if start
(when (< start (point-min)) (error "Start before start of buffer"))
(setq start (point)))
(if end
(when (> end (point-max)) (error "End after end of buffer"))
(setq end (point-max)))
(save-excursion
(goto-char start)
(save-restriction
(narrow-to-region start end)
(let ((matches 0) (case-fold-search nil))
(while (search-forward string nil t)
(delete-region (match-beginning 0) (match-end 0))
(insert replacement)
(setq matches (1+ matches)))
(and (not (zerop matches)) matches)))))
(defun replace-regexp-in-region (regexp replacement &optional start end)
(if start
(when (< start (point-min)) (error "Start before start of buffer"))
(setq start (point)))
(if end
(when (> end (point-max)) (error "End after end of buffer"))
(setq end (point-max)))
(save-excursion
(goto-char start)
(save-restriction
(narrow-to-region start end)
(let ((matches 0) (case-fold-search nil))
(while (re-search-forward regexp nil t)
(replace-match replacement t)
(setq matches (1+ matches)))
(and (not (zerop matches)) matches)))))
;; replace.el `how-many'. RSTART/REND are ordered (a reversed pair counts the
;; same region), and `search-upper-case' turns case folding off for a REGEXP
;; with an upper-case letter. `isearch-no-upper-case-p' and `search-upper-case'
;; are defined with `keep-lines' further down; they are only called at run time.
(defun how-many (regexp &optional rstart rend interactive)
"Return the number of matches for REGEXP following point (or in RSTART..REND)."
(save-excursion
(if rstart
(if rend
(progn
(goto-char (min rstart rend))
(setq rend (max rstart rend)))
(goto-char rstart)
(setq rend (point-max)))
(if (and interactive (use-region-p))
(setq rstart (region-beginning)
rend (region-end))
(setq rstart (point)
rend (point-max)))
(goto-char rstart))
(let ((count 0)
(case-fold-search
(if (and case-fold-search search-upper-case)
(isearch-no-upper-case-p regexp t)
case-fold-search)))
(while (and (< (point) rend)
(re-search-forward regexp rend t))
;; Ensure forward progress on zero-length matches like "^$".
(when (and (= (match-beginning 0) (match-end 0))
(not (eobp)))
(forward-char 1))
(setq count (1+ count)))
(when interactive (message (ngettext "%d occurrence"
"%d occurrences"
count)
count))
count)))
;;; ---- misc small subr.el helpers ----
(defun ngettext (singular plural n) (if (= n 1) singular plural))
;;; ---- version comparison (faithful port of lisp/subr.el, Emacs 30.2) ----
;; version-to-list parses a version string into a list of integers; the
;; version-list-* comparators do the significant-trailing-zero comparison; and
;; version< / version<= / version= wrap them over two version strings. The
;; version-regexp-alist data is copied value-for-value from subr.el so that
;; non-numeric qualifiers (snapshot/alpha/beta/pre/rc) sort exactly as Emacs.
(defconst version-separator "."
"Specify the string used to separate the version elements.")
(defconst version-regexp-alist
'(("^[-._+ ]?snapshot$" . -4)
("^[-._+]$" . -4)
("^[-._+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)$" . -4)
("^[-._+ ]?unknown$" . -4)
("^[-._+ ]?alpha$" . -3)
("^[-._+ ]?beta$" . -2)
("^[-._+ ]?\\(pre\\|rc\\)$" . -1))
"Specify association between non-numeric version and its priority.")
(defun version-to-list (ver)
"Convert version string VER into a list of integers."
(declare (side-effect-free t))
(unless (stringp ver)
(error "Version must be a string"))
;; Change .x.y to 0.x.y
(if (and (>= (length ver) (length version-separator))
(string-equal (substring ver 0 (length version-separator))
version-separator))
(setq ver (concat "0" ver)))
(unless (string-match-p "^[0-9]" ver)
(error "Invalid version syntax: `%s' (must start with a number)" ver))
(save-match-data
(let ((i 0)
(case-fold-search t) ; ignore case in matching
lst s al)
;; Parse the version-string up to a separator until there are none left
(while (and (setq s (string-match "[0-9]+" ver i))
(= s i))
;; Add the numeric part to the beginning of the version list;
;; lst gets reversed at the end
(setq lst (cons (string-to-number (substring ver i (match-end 0)))
lst)
i (match-end 0))
;; handle non-numeric part
(when (and (setq s (string-match "[^0-9]+" ver i))
(= s i))
(setq s (substring ver i (match-end 0))
i (match-end 0))
;; handle alpha, beta, pre, etc. separator
(unless (string= s version-separator)
(setq al version-regexp-alist)
(while (and al (not (string-match (caar al) s)))
(setq al (cdr al)))
(cond (al
(push (cdar al) lst))
;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc., but only if
;; the letter is the end of the version-string, to avoid
;; 22.8X3 being valid
((and (string-match "^[-._+ ]?\\([a-zA-Z]\\)$" s)
(= i (length ver)))
(push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
lst))
(t (error "Invalid version syntax: `%s'" ver))))))
(nreverse lst))))
(defun version-list-< (l1 l2)
"Return t if L1, a list specification of a version, is lower than L2."
(declare (pure t) (side-effect-free t))
(while (and l1 l2 (= (car l1) (car l2)))
(setq l1 (cdr l1)
l2 (cdr l2)))
(cond
((and l1 l2) (< (car l1) (car l2)))
((and (null l1) (null l2)) nil)
(l1 (< (version-list-not-zero l1) 0))
(t (< 0 (version-list-not-zero l2)))))
(defun version-list-= (l1 l2)
"Return t if L1, a list specification of a version, is equal to L2."
(declare (pure t) (side-effect-free t))
(while (and l1 l2 (= (car l1) (car l2)))
(setq l1 (cdr l1)
l2 (cdr l2)))
(cond
((and l1 l2) nil)
((and (null l1) (null l2)))
(l1 (zerop (version-list-not-zero l1)))
(t (zerop (version-list-not-zero l2)))))
(defun version-list-<= (l1 l2)
"Return t if L1, a list specification of a version, is lower or equal to L2."
(declare (pure t) (side-effect-free t))
(while (and l1 l2 (= (car l1) (car l2)))
(setq l1 (cdr l1)
l2 (cdr l2)))
(cond
((and l1 l2) (< (car l1) (car l2)))
((and (null l1) (null l2)))
(l1 (<= (version-list-not-zero l1) 0))
(t (<= 0 (version-list-not-zero l2)))))
(defun version-list-not-zero (lst)
"Return the first non-zero element of LST, which is a list of integers.
If all LST elements are zeros or LST is nil, return zero."
(declare (pure t) (side-effect-free t))
(while (and lst (zerop (car lst)))
(setq lst (cdr lst)))
(if lst
(car lst)
0))
(defun version< (v1 v2)
"Return t if version V1 is lower (older) than V2."
(declare (side-effect-free t))
(version-list-< (version-to-list v1) (version-to-list v2)))
(defun version<= (v1 v2)
"Return t if version V1 is lower (older) than or equal to V2."
(declare (side-effect-free t))
(version-list-<= (version-to-list v1) (version-to-list v2)))
(defun version= (v1 v2)
"Return t if version V1 is equal to V2."
(declare (side-effect-free t))
(version-list-= (version-to-list v1) (version-to-list v2)))
;; ---- Lisp timestamps: a port of timefns.c (Emacs 31.1) ----
;; Every time value decodes to an exact (TICKS . HZ) pair (bignum arithmetic,
;; no floats), so sums, differences and comparisons are exact and come back in
;; the form timefns.c picks: an integer when HZ is 1, (TICKS . HZ) when either
;; input was in that form or HZ does not divide a trillion, otherwise the
;; (HI LO US PS) list `current-time-list' asks for.
(defvar current-time-list t)
(defun time--gcd (a b)
(setq a (abs a) b (abs b))
(while (/= b 0) (setq b (prog1 (% a b) (setq a b))))
a)
;; `time--decode' (src/timefns.rs) is decode_lisp_time: TIME as exact (TICKS . HZ).
;; ticks_hz_list4: floor to picoseconds, then split.
(defun time--list4 (ticks hz)
(let* ((x (floor (* ticks 1000000000000) hz))
(s (floor x 1000000000000))
(fullps (mod x 1000000000000)))
(list (ash s -16) (logand s 65535) (/ fullps 1000000) (% fullps 1000000))))
;; ticks_hz_hz_ticks: floor (TICKS * HZ / T.HZ), validating HZ.
(defun time--hz-ticks (th hz)
(unless (and (integerp hz) (> hz 0))
(signal 'error (list "Invalid time frequency" hz)))
(floor (* (car th) hz) (cdr th)))
(defun time--trillion-factor (hz)
(and (fixnump hz) (= 0 (% 1000000000000 hz))))
;; time_arith.
(defun time--arith (a b subtract)
(let ((ta (time--decode a)) (tb (time--decode b)) ticks hz)
(if (eql (cdr ta) (cdr tb))
(setq hz (cdr ta)
ticks (if subtract (- (car ta) (car tb)) (+ (car ta) (car tb))))
(let* ((da (cdr ta)) (db (cdr tb))
(hzmin (min da db))
(g (time--gcd da db))
(fa (/ da g)) (fb (/ db g))
(ihz (* fa db))
(iticks (if subtract
(- (* fb (car ta)) (* fa (car tb)))
(+ (* fb (car ta)) (* fa (car tb)))))
(ig (time--gcd iticks ihz)))
(when (> ig 1)
(setq iticks (/ iticks ig) ihz (/ ihz ig))
(when (< ihz hzmin)
(let ((rescale (ceiling hzmin ihz)))
(setq iticks (* iticks rescale) ihz (* ihz rescale)))))
(setq ticks iticks hz ihz)))
(cond ((eql hz 1) ticks)
((or (not current-time-list)
(and (consp a) (not (consp (cdr a))))
(and (consp b) (not (consp (cdr b))))
(not (time--trillion-factor hz)))
(cons ticks hz))
(t (time--list4 ticks hz)))))
(defun time-add (a b) (time--arith a b nil))
(defun time-subtract (a b)
(if (eq a b)
(if current-time-list (list 0 0 0 0) (cons 0 1000000000))
(time--arith a b t)))
;; time_cmp, including its fast paths that compare without validating.
(defun time--cmp (a b)
(if (eq a b)
0
(let ((x a) (y b))
(when (and (consp a) (consp b) (eql (cdr a) (cdr b)))
(setq x (car a) y (car b)))
(if (and (fixnump x) (fixnump y))
(- x y)
(let ((ta (time--decode a)) (tb (time--decode b)))
(- (* (car ta) (cdr tb)) (* (car tb) (cdr ta))))))))
(defun time-less-p (a b) (< (time--cmp a b) 0))
(defun time-equal-p (a b)
(and (eq (null a) (null b)) (= (time--cmp a b) 0)))
(defun time-convert (time &optional form)
(let ((th (time--decode time)))
(setq form (cond (form form) (current-time-list 'list) (t t)))
(cond ((eq form 'list) (time--list4 (car th) (cdr th)))
((eq form 'integer)
(if (integerp time) time (floor (car th) (cdr th))))
(t
(when (eq form t) (setq form (cdr th)))
(if (and (consp time) (eq form (cdr time)))
time
(cons (time--hz-ticks th form) form))))))
;; timefns.c `Fcurrent_time_zone': (OFFSET NAME) for the whole seconds of TIME
;; (`lisp_seconds_argument') in ZONE. NAME is `%Z'; an empty one becomes the
;; numeric `+HH[MM[SS]]' spelling of OFFSET.
(defun current-time-zone (&optional specified-time zone)
(let* ((secs (time-convert specified-time 'integer))
(name (format-time-string "%Z" secs zone))
(offset (nth 8 (decode-time secs zone))))
(when (string= name "")
(let* ((amin-sec (abs (% offset 3600)))
(min (/ amin-sec 60))
(sec (% amin-sec 60)))
(setq name (concat (if (< offset 0) "-" "+")
(format "%02d" (abs (/ offset 3600)))
(if (/= amin-sec 0) (format "%02d" min) "")
(if (and (/= amin-sec 0) (/= sec 0))
(format "%02d" sec)
"")))))
(list offset name)))
;; decoded-time accessors: (sec min hour day month year weekday dst zone).
(defun decoded-time-second (dt) (nth 0 dt))
(defun decoded-time-minute (dt) (nth 1 dt))
(defun decoded-time-hour (dt) (nth 2 dt))
(defun decoded-time-day (dt) (nth 3 dt))
(defun decoded-time-month (dt) (nth 4 dt))
(defun decoded-time-year (dt) (nth 5 dt))
(defun decoded-time-weekday (dt) (nth 6 dt))
(defun decoded-time-dst (dt) (nth 7 dt))
(defun decoded-time-zone (dt) (nth 8 dt))
(defun char-displayable-p (_char &optional _display) t)
;; Feature/module system. `features' starts as the list `emacs -Q --batch'
;; reports before it reads any argument, in its order:
;;
;; emacs -Q --batch --eval '(prin1 features)'
;;
;; Emacs preloads (dumps) every one of these, so `(require 'FEATURE)' is a
;; no-op for each and must not go looking for a file. The tail lists the
;; libraries elisprs implements natively; a stock Emacs provides those only once
;; they are required. (`rx', which lisp-mode.el expands while the prelude
;; loads, is unloaded again afterwards: see `unload_rx_after_prelude'.)
(defvar features
'(rmc iso-transl tooltip cconv eldoc paren electric uniquify ediff-hook
vc-hooks lisp-float-type elisp-mode tabulated-list replace newcomment
text-mode lisp-mode prog-mode register page tab-bar menu-bar rfn-eshadow
isearch easymenu timer select mouse jit-lock font-lock syntax font-core
term/tty-colors frame minibuffer nadvice seq simple cl-generic indonesian
philippine cham georgian utf-8-lang misc-lang vietnamese tibetan thai
tai-viet lao korean japanese eucjp-ms cp51932 hebrew greek romanian slovak
czech european ethiopic indian cyrillic chinese composite emoji-zwj
charscript charprop case-table epa-hook jka-cmpr-hook help abbrev obarray
oclosure cl-preloaded button loaddefs theme-loaddefs faces cus-face macroexp
files window text-properties overlay sha1 md5 base64 format env code-pages
mule custom widget keymap hashtable-print-readable backquote threads kqueue
multi-tty make-network-process tty-child-frames emacs
cl-lib cl-macs cl-seq cl-extra subr-x map pcase json gv ert time-date))
(defun provide (feature &optional _subfeatures)
(unless (memq feature features) (setq features (cons feature features)))
feature)
(defun featurep (feature &optional _subfeature) (and (memq feature features) t))
;; Faithful port of C `Frequire' (fns.c): if FEATURE is already provided, return
;; it; otherwise `load' its file (FILENAME, else the feature's name) with a
;; recursion guard, then verify the load actually provided FEATURE. Loading uses
;; MUST-SUFFIX when FILENAME is nil (require a `.el'/`.elc', never a bare name),
;; matching `Fload (…, Qnil, Qt, Qnil, NILP (filename) ? Qt : Qnil)'.
(defvar require--nesting-list nil
"Features whose `require' is currently in progress (recursion guard).")
(defun require (feature &optional filename noerror)
(if (featurep feature)
feature
(let ((lisp-file (if filename filename (symbol-name feature))))
(when (member lisp-file require--nesting-list)
(error "Recursive `require' for feature `%s'" feature))
(let ((require--nesting-list (cons lisp-file require--nesting-list)))
(if (load lisp-file noerror t nil (if filename nil t))
(if (featurep feature)
feature
(unless noerror
(error "Loading file %s failed to provide feature `%s'"
lisp-file feature)))
nil)))))
(defmacro bound-and-true-p (var) (list 'and (list 'boundp (list 'quote var)) var))
;; `make-local-variable', `make-variable-buffer-local', `local-variable-p',
;; `local-variable-if-set-p', `kill-local-variable' and `buffer-local-value' are
;; C primitives (builtins.rs) backed by the current buffer's local-binding table.
;; Faithful to the C subr `Fset_default_toplevel_value' (data.c): it runs
;; `set_default_internal' and returns nil, NOT the value.
(defun set-default-toplevel-value (sym val) (set-default sym val) nil)
(defun defalias (symbol definition &optional _docstring) (fset symbol definition) symbol)
(defalias 'string-split 'split-string)
(defalias 'search-forward-regexp (symbol-function 're-search-forward))
(defalias 'search-backward-regexp (symbol-function 're-search-backward))
;; cl-lib.el: the three- and four-letter accessors under their cl- names are
;; plain aliases, so `(symbol-function (quote cl-caddr))' is `caddr' and setf
;; reaches them by following the alias (gv.el:112).
(let ((names (quote (caaar caadr cadar caddr cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr))))
(while names
(defalias (intern (concat "cl-" (symbol-name (car names)))) (car names))
(setq names (cdr names))))
;; help.el: obsolete alias for `help--make-usage' (help usage helpers ported above).
(define-obsolete-function-alias 'help-make-usage #'help--make-usage "25.1")
;; with-memoization: cache BODY's value in PLACE; reuse it on later calls.
(defmacro with-memoization (place &rest body) (declare (indent 1) (debug (gv-place body))) `(or ,place (setf ,place (progn ,@body))))
;; regexp-opt: a regexp matching any of STRINGS (sorted, regexp-quoted alternation).
;; NOTE: this does NOT replicate Emacs's trie/shared-prefix optimization, so the
;; output string differs for prefix-overlapping inputs — but it matches the same
;; set of strings. Special cases (empty, single, PAREN variants) match Emacs.
(defun match-string-no-properties (n &optional string)
;; elisprs strings carry no text properties, so this is just match-string.
(match-string n string))
(defun regexp-opt-depth (regexp)
;; Count capturing groups: bare `\\(' (not the `\\(?…' shy/numbered forms).
(let ((count 0) (i 0) (n (length regexp)))
(while (< i n)
(if (and (eq (aref regexp i) ?\\) (< (1+ i) n) (eq (aref regexp (1+ i)) ?\())
(progn
(unless (and (< (+ i 2) n) (eq (aref regexp (+ i 2)) ??))
(setq count (1+ count)))
(setq i (+ i 2)))
(setq i (1+ i))))
count))
;; regexp-opt.el, ported. The old implementation joined the strings with `\\|',
;; which is a correct regexp but not the one Emacs builds: `regexp-opt' factors
;; common prefixes and suffixes and folds one-character alternatives into a
;; character set, so `(regexp-opt '("cat" "cot" "cut"))' is "\\(?:c\\(?:[aou]t\\)\\)"
;; and `(regexp-opt '("a" "b" "c"))' is "[abc]". That output is observable
;; wherever a caller inspects or composes the result -- `rx''s all-strings `or'
;; branch is one -- so it is the shape, not just the language, that has to match.
(defun regexp-opt--common-prefix (strings)
"The longest common prefix of STRINGS.
`regexp-opt-group' asks `try-completion' for this, having bound
`completion-ignore-case' and `completion-regexp-list' to nil so that it means
exactly the common prefix and nothing else."
(let ((pre (car strings)) (rest (cdr strings)))
(while (and rest (> (length pre) 0))
(let ((s (car rest)) (i 0))
(while (and (< i (length pre)) (< i (length s))
(eq (aref pre i) (aref s i)))
(setq i (1+ i)))
(setq pre (substring pre 0 i)))
(setq rest (cdr rest)))
(or pre "")))
(defun regexp-opt-charset (chars)
"Return a regexp matching a character in CHARS (a list of characters).
The empty list yields a regexp that never matches."
;; The C walks a char-table; walking the sorted, de-duplicated list is the
;; same traversal. A run becomes a RANGE only when it is longer than three
;; characters (`(> end (+ start 2))'), which is why (?a ?b ?c) is "[abc]" and
;; (?a ?b ?c ?d) is "[a-d]".
(let ((bracket "") (dash "") (caret "") (plain nil) (charset "")
(start -1) (end -2))
(dolist (char chars)
(cond ((eq char ?\]) (setq bracket "]"))
((eq char ?^) (setq caret "^"))
((eq char ?-) (setq dash "-"))
(t (setq plain (cons char plain)))))
(setq plain (sort (delete-dups (nreverse plain)) #'<))
(dolist (c plain)
(if (= (1- c) end)
(setq end c)
(if (> end (+ start 2))
(setq charset (concat charset (string start) "-" (string end)))
(while (>= end start)
(setq charset (concat charset (string start)))
(setq start (1+ start))))
(setq start c end c)))
(when (>= end start)
(if (> end (+ start 2))
(setq charset (concat charset (string start) "-" (string end)))
(while (>= end start)
(setq charset (concat charset (string start)))
(setq start (1+ start)))))
;; `]' must come first, `^' must not, and `-' must be first or last.
(let ((all (concat bracket charset caret dash)))
(cond ((= (length all) 0) "\\`a\\`")
((= (length all) 1) (regexp-quote all))
((string= all "^-") "[-^]")
(t (concat "[" all "]"))))))
(defun regexp-opt-group (strings &optional paren lax)
"Return a regexp matching a string in the SORTED list STRINGS.
PAREN non-nil wraps the result; LAX non-nil omits the wrapping where it is not
needed. Merges keywords to avoid backtracking, as regexp-opt.el does."
(let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
(close-group (if paren "\\)" ""))
(open-charset (if lax "" open-group))
(close-charset (if lax "" close-group)))
(cond
((= (length strings) 0) "")
((= (length strings) 1)
(if (= (length (car strings)) 1)
(concat open-charset (regexp-quote (car strings)) close-charset)
(concat open-group (regexp-quote (car strings)) close-group)))
;; An empty string: drop it and make the rest optional.
((= (length (car strings)) 0)
(concat open-charset (regexp-opt-group (cdr strings) t t) "?" close-charset))
;; Several one-character strings: a character set beats alternation.
((and (= (length (car strings)) 1)
(let ((found nil))
(dolist (s (cdr strings)) (when (= (length s) 1) (setq found t)))
found))
(let ((letters nil) (rest nil))
(dolist (s strings)
(if (= (length s) 1)
(setq letters (cons (aref s 0) letters))
(setq rest (cons s rest))))
(if rest
;; Longest first, so the alternation matches the longer string.
(concat open-group (regexp-opt-group (nreverse rest))
"\\|" (regexp-opt-charset letters) close-group)
(concat open-charset (regexp-opt-charset letters) close-charset))))
(t
(let ((prefix (regexp-opt--common-prefix strings)))
(if (> (length prefix) 0)
(let* ((n (length prefix))
(suffixes (mapcar (lambda (s) (substring s n)) strings)))
(concat open-group (regexp-quote prefix)
(regexp-opt-group suffixes t t) close-group))
(let* ((sgnirts (mapcar (lambda (s) (reverse s)) strings))
(xiffus (regexp-opt--common-prefix sgnirts)))
(if (> (length xiffus) 0)
(let* ((n (- (length xiffus)))
;; Sorting matters for cases such as ("ad" "d").
(prefixes (sort (mapcar (lambda (s) (substring s 0 n)) strings)
#'string<)))
(concat open-group (regexp-opt-group prefixes t t)
(regexp-quote (reverse xiffus)) close-group))
;; No shared affix: split on the first character and recurse.
(let* ((char (substring (car strings) 0 1))
(half1 nil) (half2 nil))
(dolist (s strings)
(if (and (null half2) (string-prefix-p char s))
(setq half1 (cons s half1))
(setq half2 (cons s half2))))
(concat open-group (regexp-opt-group (nreverse half1))
"\\|" (regexp-opt-group (nreverse half2))
close-group))))))))))
(defun regexp-opt (strings &optional paren)
"Return a regexp matching any string in STRINGS, each taken literally.
PAREN controls the surrounding group: a string is used as the opening bracket,
`words'/`symbols' add the word/symbol boundaries, any other non-nil value uses
`\\(', and nil uses a shy group only where one is needed."
(let* ((open (cond ((stringp paren) paren) (paren "\\(")))
(re (if strings
(regexp-opt-group (delete-dups (sort (copy-sequence strings) #'string<))
(or open t) (not open))
(concat (or open "\\(?:") "\\`a\\`" "\\)"))))
(cond ((eq paren 'words) (concat "\\<" re "\\>"))
((eq paren 'symbols) (concat "\\_<" re "\\_>"))
(t re))))
;; `looking-back' (subr.el): `looking-at' for the text BEFORE point. The trick
;; is the `\\=' anchor -- searching backwards for "\\(?:REGEXP\\)\\=" finds a match
;; that ENDS at point. GREEDY then walks the start backwards one character at a
;; time for as long as the match still reaches the end, which is allowed to pass
;; LIMIT.
(defun looking-back (regexp &optional limit greedy)
"Return non-nil if the text before point matches REGEXP."
(let ((start (point))
(pos (save-excursion
(and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
(point)))))
(if (and greedy pos)
(save-restriction
(narrow-to-region (point-min) start)
(while (and (> pos (point-min))
(save-excursion
(goto-char pos)
(backward-char 1)
(looking-at (concat "\\(?:" regexp "\\)\\'"))))
(setq pos (1- pos)))
(save-excursion
(goto-char pos)
(looking-at (concat "\\(?:" regexp "\\)\\'"))))
(not (null pos)))))
(defmacro while-let (binding &rest body)
(declare (indent 1) (debug if-let))
(let ((var (car (car binding))) (val (car (cdr (car binding)))))
`(let ((,var ,val)) (while ,var ,@body (setq ,var ,val)))))
;; cl-macs.el `cl-deftype': the expander is `(cl-function (lambda (&cl-defs
;; ('*) ,@ARGLIST) ...))', so an omitted &optional or &key argument defaults to
;; `*'; calling it with no arguments at definition time computes the atomic
;; type's specifier, and a `wrong-number-of-arguments' there means NAME has no
;; atomic form (no predicate). A `(declare (parents ...))' is consumed.
(defun cl--deftype-defaulted-arglist (arglist)
(let ((res nil) (kind nil))
(while (consp arglist)
(let ((a (car arglist)))
(cond ((memq a '(&optional &key &rest &body &aux)) (setq kind a))
((and (memq kind '(&optional &key)) (symbolp a) (not (eq a '&allow-other-keys)))
(setq a (list a ''*))))
(setq res (cons a res)))
(setq arglist (cdr arglist)))
(nconc (nreverse res) arglist)))
(defun cl--deftype-arity (arglist)
;; (MIN . MAX) of a cl lambda list, MAX nil when &rest/&body/&key takes any.
(let ((min 0) (max 0) (kind nil))
(while (consp arglist)
(let ((a (car arglist)))
(cond ((memq a '(&optional &key &rest &body &aux &allow-other-keys))
(setq kind a)
(when (memq a '(&rest &body &key)) (setq max nil)))
((null kind) (setq min (1+ min)) (and max (setq max (1+ max))))
((eq kind '&optional) (and max (setq max (1+ max))))))
(setq arglist (cdr arglist)))
(when arglist (setq max nil))
(cons min max)))
(defmacro cl-deftype (name arglist &rest body)
(declare (debug cl-defmacro) (doc-string 3) (indent 2))
(let ((decls nil) (forms body) (parents nil))
(while (and forms
(or (and (stringp (car forms)) (cdr forms))
(memq (car-safe (car forms)) '(:documentation declare interactive cl-declare))))
(setq decls (cons (car forms) decls) forms (cdr forms)))
(setq decls (nreverse decls))
(let ((declares (assq 'declare decls)))
(when declares
(let ((parent-decl (assq 'parents (cdr declares))))
(when parent-decl
(setq parents (cdr parent-decl))
(setcdr declares (delq parent-decl (copy-sequence (cdr declares))))
(when (equal declares '(declare))
(setq decls (delq declares decls)))))))
(let* ((arity (cl--deftype-arity arglist))
(args (make-symbol "args"))
(expander
`(lambda (&rest ,args)
,@(and (stringp (car decls)) (list (car decls)))
(let ((n (length ,args)))
(when (or (< n ,(car arity)) ,(and (cdr arity) `(> n ,(cdr arity))))
(signal 'wrong-number-of-arguments (list ',arity n))))
(cl-destructuring-bind ,(cl--deftype-defaulted-arglist arglist) ,args
,@forms)))
(specifier
(condition-case nil
(funcall (eval expander t))
(wrong-number-of-arguments
(and parents arglist
(error "Type %S with parents may be not atomic: %S"
name arglist)))))
(predicate
(cond ((and (eq (car-safe specifier) 'satisfies)
(consp (cdr specifier)) (null (cdr (cdr specifier))))
`#',(car (cdr specifier)))
((null specifier) nil)
(t `(lambda (x) (ignore x) (cl-typep x ',specifier))))))
`(eval-and-compile
(cl--define-derived-type ',name ,expander ,predicate ',parents)))))
;; cl-preloaded.el `cl--define-derived-type', without the derived-type class
;; object (method dispatch on derived types is not modelled).
(defun cl--define-derived-type (name expander predicate &optional _parents)
(define-symbol-prop name 'cl-deftype-handler expander)
(when predicate
(define-symbol-prop name 'cl-deftype-satisfies predicate)))
;; cl-macs.el `cl-typep' (a `define-inline'), as its function body runs.
(defun cl-typep (val type)
"Return t if VAL is of type TYPE, nil otherwise."
(let ((satisfies (cond ((and type (symbolp type)) (get type 'cl-deftype-satisfies))
((and (consp type) (null (cdr type)))
(get (car type) 'cl-deftype-satisfies)))))
(cond
(satisfies (funcall satisfies val))
((and (consp type) (get (car type) 'cl-deftype-handler))
(cl-typep val (apply (get (car type) 'cl-deftype-handler) (cdr type))))
((and (consp type) (memq (car type) '(integer float number)))
;; The compiled `(or `(,min ,max) pcase--dontcare)' keeps whatever the
;; failed list match bound: MIN is the first argument, MAX the second.
(let* ((bounds (cdr type))
(min (car-safe bounds))
(max (car-safe (cdr-safe bounds))))
(and (cl-typep val (car type))
(if (memq min '(* nil)) t
(if (consp min) (> val (car min)) (>= val min)))
(if (memq max '(* nil)) t
(if (consp max) (< val (car max)) (<= val max))))))
((and (eq (car-safe type) 'not) (consp (cdr type)) (null (cdr (cdr type))))
(not (cl-typep val (car (cdr type)))))
((memq (car-safe type) '(and or))
(let ((types (cdr type)))
(cond ((null types) (eq (car type) 'and))
((null (cdr types)) (cl-typep val (car types)))
((eq (car type) 'and)
(and (cl-typep val (car types)) (cl-typep val (cons 'and (cdr types)))))
(t (or (cl-typep val (car types)) (cl-typep val (cons 'or (cdr types))))))))
((and (eq (car-safe type) 'eql) (consp (cdr type)) (null (cdr (cdr type))))
(and (eql val (car (cdr type))) t))
((eq (car-safe type) 'member) (and (memql val (cdr type)) t))
((and (eq (car-safe type) 'satisfies) (consp (cdr type)) (null (cdr (cdr type))))
(funcall (car (cdr type)) val))
((and type (symbolp type) (get type 'cl-deftype-handler))
(cl-typep val (funcall (get type 'cl-deftype-handler))))
((memq type '(nil t)) type)
((symbolp type)
(let* ((name (symbol-name type))
(namep (intern (concat name "p"))))
(cond ((fboundp namep) (funcall namep val))
((fboundp (setq namep (intern (concat name "-p")))) (funcall namep val))
((fboundp type) (funcall type val))
(t (error "Unknown type %S" type)))))
(t (error "Bad type spec: %S" type)))))
;; ---- cl-defgeneric / cl-defmethod: single/multi type-dispatch with CLOS
;; method combination — primary plus :before/:after/:around qualifiers and
;; `cl-call-next-method'/`cl-next-method-p'. Methods are kept per generic name
;; in `cl--generic-table' as (QUALIFIER SPECS . FN); a call selects the
;; applicable methods, orders them by specificity, and runs the effective method.
(defvar cl--generic-table nil)
(defvar cl--cnm-args nil)
(defvar cl--cnm-next nil)
;; cl-generic.el: the three method-lookup failures share `cl-no-method'.
(define-error 'cl-no-method "No method")
(define-error 'cl-no-next-method "No next method" 'cl-no-method)
(define-error 'cl-no-primary-method "No primary method" 'cl-no-method)
(define-error 'cl-no-applicable-method "No applicable method" 'cl-no-method)
(defun cl--spec-match (sp arg)
(cond ((eq sp t) t)
((and (consp sp) (eq (car sp) 'eql)) (eql arg (car (cdr sp))))
((and (consp sp) (eq (car sp) 'head)) (and (consp arg) (eq (car arg) (car (cdr sp)))))
(t (cl-typep arg sp))))
(defun cl--type-rank (sp)
;; Higher = more specific, so it wins ties between applicable methods.
(cond ((eq sp t) 0)
((and (consp sp) (memq (car sp) '(eql head))) 100)
((memq sp '(number list sequence array atom integer-or-marker)) 2)
(t 3)))
(defun cl--add-method (name qualifier specs fn)
(let ((entry (assq name cl--generic-table)))
(unless entry
(setq entry (cons name nil) cl--generic-table (cons entry cl--generic-table)))
(setcdr entry (cons (cons qualifier (cons specs fn))
(cl-remove-if (lambda (m) (and (eq (car m) qualifier)
(equal (car (cdr m)) specs)))
(cdr entry))))))
(defun cl--sortq (app qual desc)
;; The FNs in APP (each (SCORE QUALIFIER FN)) whose qualifier is QUAL, ordered
;; by SCORE (descending when DESC).
(let ((sel (cl-remove-if-not (lambda (e) (eq (car (cdr e)) qual)) app)))
(setq sel (sort sel (lambda (a b) (if desc (> (car a) (car b)) (< (car a) (car b))))))
(mapcar (lambda (e) (car (cdr (cdr e)))) sel)))
(defun cl-call-next-method (&rest newargs)
(let ((args (if newargs newargs cl--cnm-args)))
(if cl--cnm-next (funcall cl--cnm-next args) (signal 'cl-no-next-method nil))))
(defun cl-next-method-p () (and cl--cnm-next t))
(defun cl--chain (methods final args)
;; Run METHODS[0] with `cl-call-next-method' wired to the rest, ending in FINAL
;; (a one-arg thunk) or signaling when exhausted.
(if (null methods)
(if final (funcall final args) (signal 'cl-no-next-method nil))
(let ((cl--cnm-args args)
(cl--cnm-next (if (or (cdr methods) final)
(let ((rest (cdr methods)))
(lambda (a) (cl--chain rest final a)))
nil)))
(apply (car methods) args))))
(defun cl--generic-dispatch (name args)
(let ((methods (cdr (assq name cl--generic-table))) (app nil))
(dolist (m methods)
;; m = (QUALIFIER SPECS . FN)
(let ((specs (car (cdr m))) (score 0) (ok t) (a args))
(while (and specs ok)
(let ((sp (car specs)))
(if (cl--spec-match sp (car a)) (setq score (+ score (cl--type-rank sp)))
(setq ok nil)))
(setq specs (cdr specs) a (cdr a)))
(when ok (setq app (cons (list score (car m) (cdr (cdr m))) app)))))
(let ((arounds (cl--sortq app :around t))
(befores (cl--sortq app :before t))
(primaries (cl--sortq app nil t))
(afters (cl--sortq app :after nil)))
(if (and (null primaries) (null arounds))
(signal 'cl-no-applicable-method (cons name args))
(let ((core (lambda (a)
(dolist (b befores) (apply b a))
(let ((result (cl--chain primaries nil a)))
(dolist (af afters) (apply af a))
result))))
(if arounds (cl--chain arounds core args) (funcall core args)))))))
(defun cl--method-spec (sp)
;; Build a FORM that evaluates to the runtime specializer for arglist entry SP.
(cond
;; `(eql EXPR)' evaluates EXPR (Emacs 30 lifted the literal-only rule)...
((and (consp sp) (eq (car sp) 'eql))
(list 'list (list 'quote 'eql) (car (cdr sp))))
;; ...but `(head SYMBOL)' does NOT: it names the symbol the argument's car
;; must be `eq' to. Evaluating it made `(cl-defmethod g ((x (head foo))) …)'
;; a `void-variable foo', and where `foo' happened to be bound it dispatched
;; on that value instead: `(let ((foo 'bar)) …(g '(foo 1)))' is `hf' in Emacs.
((and (consp sp) (eq (car sp) 'head))
(list 'quote (list 'head (car (cdr sp)))))
(t (list 'quote sp))))
(defmacro cl-defmethod (name &rest body)
(declare (doc-string cl--defmethod-doc-pos) (indent defun))
;; (cl-defmethod NAME [QUALIFIER] ARGLIST BODY...) — QUALIFIER is an optional
;; :before/:after/:around keyword.
(let ((qualifier nil) (arglist nil) (plain nil) (specs nil) (mode 'req))
(when (keywordp (car body)) (setq qualifier (car body) body (cdr body)))
(setq arglist (car body) body (cdr body))
(dolist (a arglist)
(cond
((memq a '(&optional &rest &key)) (setq mode a) (setq plain (cons a plain)))
((and (eq mode 'req) (consp a))
(setq plain (cons (car a) plain) specs (cons (cl--method-spec (car (cdr a))) specs)))
((eq mode 'req) (setq plain (cons a plain) specs (cons t specs)))
(t (setq plain (cons a plain)))))
(setq plain (nreverse plain) specs (nreverse specs))
(list 'progn
(list 'cl--add-method (list 'quote name) qualifier (cons 'list specs)
;; cl-generic.el: `(cl-function (lambda ,plain-args ,@body))'.
(list 'cl-function (cons 'lambda (cons plain body))))
(list 'defun name '(&rest --args--)
(list 'cl--generic-dispatch (list 'quote name) '--args--))
(list 'quote name))))
(defmacro cl-defgeneric (name arglist &rest body)
(declare (indent 2) (doc-string 3))
;; Establish the dispatcher; real body forms become an unspecialized default.
(let ((real (cl-remove-if
(lambda (f) (or (stringp f)
(and (consp f) (memq (car f) '(declare :documentation)))))
body)))
(append
(list 'progn
(list 'unless (list 'assq (list 'quote name) 'cl--generic-table)
(list 'setq 'cl--generic-table
(list 'cons (list 'cons (list 'quote name) nil) 'cl--generic-table))))
(when real
(list (list 'cl--add-method (list 'quote name) nil nil
(list 'cl-function (cons 'lambda (cons arglist real))))))
;; `cl-defgeneric' answers nil, not its own name: the trailing `defun'
;; would otherwise leave the symbol as the `progn''s value.
(list (list 'defun name '(&rest --args--)
(list 'cl--generic-dispatch (list 'quote name) '--args--))
nil))))
(defmacro cl-the (_type form) form)
(defmacro cl-assert (form &optional _show-args string &rest args)
;; With a STRING, signal a plain `error' with the formatted message; otherwise
;; `cl-assertion-failed' carrying the failed FORM.
(if string
(list 'if form nil (cons 'error (cons string args)))
(list 'if form nil (list 'signal (list 'quote 'cl-assertion-failed) (list 'list (list 'quote form))))))
;; simple.el's `region-active-p' (with the mark subsystem above), placed after
;; the `cl-assert' it expands.
(defun region-active-p ()
(and transient-mark-mode mark-active
(progn (cl-assert (mark)) t)))
;; cl-macs.el: the signal DATA is (STRING-or-TYPE VALUE FORM), FORM evaluated once.
;; (`macroexp-let2' is defined further down, after this body is compiled, so its
;; expansion is spelled out.)
(defmacro cl-check-type (form type &optional string)
(let* ((temp (if (macroexp-copyable-p form) form (make-symbol "temp")))
(body `(progn (or (cl-typep ,temp ',type)
(signal 'wrong-type-argument
(list ,(or string `',type) ,temp ',form)))
nil)))
(if (eq temp form) body `(let ((,temp ,form)) ,body))))
;; (cl-do ((VAR INIT [STEP])...) (END RESULT...) BODY...): like CL `do', with
;; the steps computed from the previous iteration's values (parallel assignment).
(defmacro cl-do (specs endclause &rest body)
(let ((inits nil) (steps nil) (tmps nil))
(dolist (s specs)
(let ((var (if (consp s) (car s) s))
(init (if (consp s) (car (cdr s)) nil))
(has-step (and (consp s) (cdr (cdr s)))))
(setq inits (cons (list var init) inits))
(when has-step
(let ((tv (make-symbol (symbol-name var))))
(setq tmps (cons (list tv (car (cdr (cdr s)))) tmps))
(setq steps (cons (list var tv) steps))))))
(setq inits (nreverse inits) tmps (nreverse tmps) steps (nreverse steps))
(let ((setqargs nil))
(dolist (p steps)
(setq setqargs (cons (car p) setqargs))
(setq setqargs (cons (car (cdr p)) setqargs)))
(setq setqargs (nreverse setqargs))
`(let ,inits
(while (not ,(car endclause))
,@body
(let ,tmps (setq ,@setqargs)))
,@(cdr endclause)))))
;; cl-do*: like cl-do but bindings and step assignments are sequential (let* and
;; an in-order setq), so each spec sees the updated earlier ones.
(defmacro cl-do* (specs endclause &rest body)
(let ((inits nil) (steps nil))
(dolist (s specs)
(let ((var (if (consp s) (car s) s))
(init (if (consp s) (car (cdr s)) nil))
(has-step (and (consp s) (cdr (cdr s)))))
(setq inits (cons (list var init) inits))
(when has-step
(setq steps (cons (car (cdr (cdr s))) (cons var steps))))))
(setq inits (nreverse inits) steps (nreverse steps))
`(let* ,inits
(while (not ,(car endclause))
,@body
(setq ,@steps))
,@(cdr endclause))))
;; cl-progv: dynamically bind the runtime lists SYMBOLS to VALUES around BODY,
;; restoring (or unbinding) each afterwards.
(defmacro cl-progv (symbols values &rest body)
`(let* ((--pv-syms-- ,symbols)
(--pv-saved-- (mapcar (lambda (s) (list s (boundp s) (and (boundp s) (symbol-value s))))
--pv-syms--)))
(unwind-protect
(progn
(let ((ss --pv-syms--) (vv ,values))
(while ss (set (car ss) (car vv)) (setq ss (cdr ss) vv (cdr vv))))
,@body)
(dolist (e --pv-saved--)
(if (nth 1 e) (set (car e) (nth 2 e)) (makunbound (car e)))))))
;; Build let* bindings that positionally destructure VALEXPR (a symbol holding a
;; list) against a flat ARGLIST, honoring &optional and &rest.
(defun cl-db--plist-get (plist key default)
;; plist-get with a fallback when KEY is absent (for &key defaults).
(let ((m (plist-member plist key))) (if m (car (cdr m)) default)))
(defun cl-db--arity (arglist)
;; (MIN . MAX) element counts a destructuring ARGLIST accepts; MAX is nil for
;; no upper bound (&rest / &body / &key or a dotted tail allow extra elements).
;; &aux vars consume nothing, so they neither raise MIN nor lift the bound.
(let ((min 0) (max 0) (mode 'req) (unbounded nil))
(when (eq (car arglist) '&whole) (setq arglist (cddr arglist)))
(while (consp arglist)
(let ((a (car arglist)))
(cond
((eq a '&optional) (setq mode 'opt))
((memq a '(&rest &body &key)) (setq mode 'done unbounded t))
((eq a '&aux) (setq mode 'done))
((eq mode 'done) nil)
((eq mode 'opt) (setq max (1+ max)))
(t (setq min (1+ min) max (1+ max)))))
(setq arglist (cdr arglist)))
(when (and arglist (symbolp arglist)) (setq unbounded t))
(cons min (if unbounded nil max))))
(defun cl-db--check (val min max arglist)
;; Signal `wrong-number-of-arguments' when VAL's length is outside [MIN,MAX]
;; (MAX nil = unbounded), reporting ARGLIST like Emacs' cl-destructuring-bind.
(let ((n (length val)))
(when (or (< n min) (and max (> n max)))
(signal 'wrong-number-of-arguments (list arglist n))))
nil)
(defun cl-db--binds (arglist v &optional check)
;; Supports &whole, &optional / &rest / &key with per-arg defaults `(VAR DEFAULT)`
;; and nested patterns in required position. &key reads the plist tail at pos i.
;; When CHECK (the top-level arglist to report) is non-nil, an arity guard is
;; emitted so cl-destructuring-bind errors on length mismatch; cl-loop passes
;; no CHECK and stays lenient, matching Emacs in both cases.
(let ((binds nil) (i 0) (mode 'req)
(haskey nil) (allow nil) (keystart 0) (keywords nil))
;; Leading (&whole VAR …): bind VAR to the whole value, then continue.
(when (eq (car arglist) '&whole)
(setq binds (cons (list (car (cdr arglist)) v) binds))
(setq arglist (cddr arglist)))
(when check
(let ((ar (cl-db--arity arglist)))
(setq binds (cons (list (make-symbol "--cl-db-chk--")
(list 'cl-db--check v (car ar) (cdr ar)
(list 'quote check)))
binds))))
(while (consp arglist)
(let ((a (car arglist)))
(cond
((eq a '&optional) (setq mode 'opt))
((eq a '&rest) (setq mode 'rest))
((eq a '&key) (setq mode 'key haskey t keystart i))
((eq a '&allow-other-keys) (setq allow t))
((eq a '&aux) (setq mode 'aux))
((eq mode 'rest) (setq binds (cons (list a (list 'nthcdr i v)) binds)))
((eq mode 'aux)
(let ((var (if (consp a) (car a) a)) (def (and (consp a) (car (cdr a)))))
(setq binds (cons (list var def) binds))))
((eq mode 'key)
;; cl-macs.el: VAR, (VAR DEFAULT SVAR) or ((KEYWORD VAR) DEFAULT SVAR);
;; SVAR is t when the keyword was supplied.
(let* ((spec (if (consp a) (car a) a))
(var (if (consp spec) (car (cdr spec)) spec))
(def (and (consp a) (car (cdr a))))
(svar (and (consp a) (car (cdr (cdr a)))))
(kw (if (consp spec) (car spec) (intern (concat ":" (symbol-name var))))))
(setq keywords (cons kw keywords))
(setq binds (cons (list var (list 'cl-db--plist-get (list 'nthcdr i v)
(list 'quote kw) def))
binds))
(when svar
(setq binds (cons (list svar (list 'and (list 'plist-member (list 'nthcdr i v)
(list 'quote kw))
t))
binds)))))
((eq mode 'opt)
(let ((var (if (consp a) (car a) a)) (def (and (consp a) (car (cdr a))))
(svar (and (consp a) (car (cdr (cdr a))))))
(setq binds (cons (list var (list 'if (list 'nthcdr i v) (list 'nth i v) def))
binds))
(when svar
(setq binds (cons (list svar (list 'and (list 'nthcdr i v) t)) binds)))
(setq i (1+ i))))
((consp a)
;; Nested pattern: bind a temp to the element, then destructure it.
(let ((tv (make-symbol "db")))
(setq binds (cons (list tv (list 'nth i v)) binds))
(dolist (rb (cl-db--binds a tv check)) (setq binds (cons rb binds))))
(setq i (1+ i)))
(t (setq binds (cons (list a (list 'nth i v)) binds)) (setq i (1+ i)))))
(setq arglist (cdr arglist)))
;; &key keyword validation (only under CHECK, i.e. cl-destructuring-bind).
;; Faithful to cl-macs.el: reject any keyword not among the &key names unless
;; the lambda-list has &allow-other-keys or the plist carries :allow-other-keys t.
(when (and check haskey (not allow))
(let ((ks (make-symbol "--cl-keys--"))
(tail (list 'nthcdr keystart v))
(allowed (reverse keywords)))
(setq binds
(cons
(list (make-symbol "--cl-db-keychk--")
(list 'let (list (list ks tail))
(list 'while ks
(list 'cond
(list (list 'memq (list 'car ks)
(list 'quote (append allowed '(:allow-other-keys))))
(list 'if (list 'cdr ks) nil
(list 'error "Missing argument for %s" (list 'car ks)))
(list 'setq ks (list 'cddr ks)))
(list (list 'car (list 'cdr (list 'memq '':allow-other-keys tail)))
(list 'setq ks nil))
(list t (list 'error "Keyword argument %s not one of %s"
(list 'car ks) (list 'quote allowed)))))))
binds))))
;; A dotted tail — e.g. (K . V) — binds the trailing symbol to the rest.
(when (and arglist (symbolp arglist))
(setq binds (cons (list arglist (list 'nthcdr i v)) binds)))
(reverse binds)))
(defmacro cl-destructuring-bind (arglist expr &rest body)
`(let ((--cl-db-v-- ,expr))
(let* ,(cl-db--binds arglist '--cl-db-v-- arglist) ,@body)))
;; `cl-defun' and `cl-defmacro' are cl-macs.el's, built on `cl--transform-lambda'
;; before the first top-level `cl-defstruct' (`ppss').
;; cl multiple values are just lists in this model.
(defun cl-values (&rest vals) vals)
(defun cl-values-list (l) l)
(defmacro cl-multiple-value-bind (vars form &rest body)
`(cl-destructuring-bind ,vars ,form ,@body))
(defmacro cl-multiple-value-setq (vars form)
(let ((tmp (make-symbol "mv")))
`(let ((,tmp ,form))
,@(let ((sets nil) (i 0) (vs vars))
(while vs
(setq sets (cons (list 'setq (car vs) (list 'nth i tmp)) sets) i (1+ i) vs (cdr vs)))
(reverse sets))
,tmp)))
;; ---- setf: generalized-variable assignment ----
;; Expands (setf PLACE VALUE) to the right mutator for PLACE. Supported places
;; (those whose setter primitives exist): a plain variable, car/cdr and the
;; two-level c[ad][ad]r accessors, nth, elt, aref, gethash, and symbol-value.
;; Each setter returns VALUE, so (setf …) yields the last assigned value, as in
;; Emacs. Backquote-pattern places (cl-struct slots, alist-get) wait on more
;; setter primitives.
;; Maps a cl-defstruct accessor symbol to its slot index (populated by
;; `cl-defstruct' when it runs, consulted by `setf--expand' when expanding later
;; top-level forms — which works because forms are processed in order).
(defvar cl-struct--slot-index nil)
;; The same, for the accessors of a `(:type list)' struct, whose setter is
;; `(setcar (nthcdr INDEX S) V)' because there is nothing to `aset'.
(defvar cl-struct--slot-list-index nil)
;; Accessors of `:read-only' cl-defstruct slots. `setf--expand' signals the same
;; "ACCESSOR is a read-only slot" error cl-macs.el:3260 raises via gv-define-expander.
(defvar cl-struct--slot-readonly nil)
(defun setf--expand (place val)
(if (symbolp place)
(list 'setq place val)
;; gv.el:80 rejects a place that is neither a symbol nor a cons with its own
;; condition; falling through to `(car place)' reported `listp' instead.
(unless (consp place) (signal 'gv-invalid-place (list place)))
(let ((head (car place)) (args (cdr place)))
(cond
((eq head 'car) (list 'setcar (car args) val))
((eq head 'cdr) (list 'setcdr (car args) val))
;; c[ad]+r, two to four letters: subr.el's compiler macro rewrites each to
;; its car/cdr chain, so the place is set{car,cdr} of the accessor made of
;; the remaining letters — (setf (cadadr X) V) is (setcar (cdadr X) V).
((and (symbolp head)
(string-match-p "\\`c[ad][ad][ad]?[ad]?r\\'" (symbol-name head)))
(let ((name (symbol-name head)))
(list (if (eq (aref name 1) ?a) 'setcar 'setcdr)
(list (intern (concat "c" (substring name 2))) (car args))
val)))
((eq head 'nth) (list 'setcar (list 'nthcdr (car args) (car (cdr args))) val))
;; (setf (nthcdr N L) V): N=0 replaces L; else setcdr the (N-1)th cell.
((eq head 'nthcdr)
(list 'let (list (list '--setf-nc-- (car args)))
(list 'if (list '<= '--setf-nc-- 0)
(setf--expand (car (cdr args)) val)
(list 'setcdr (list 'nthcdr (list '1- '--setf-nc--) (car (cdr args))) val))))
((memq head '(elt seq-elt))
;; Bind the sequence + index once: list → setcar, array → aset.
(list 'let (list (list '--setf-s-- (car args)) (list '--setf-n-- (car (cdr args))))
(list 'if (list 'listp '--setf-s--)
(list 'setcar (list 'nthcdr '--setf-n-- '--setf-s--) val)
(list 'aset '--setf-s-- '--setf-n-- val))))
((eq head 'aref) (list 'aset (car args) (car (cdr args)) val))
((eq head 'gethash) (list 'puthash (car args) val (car (cdr args))))
((eq head 'symbol-value) (list 'set (car args) val))
;; (setf (default-value SYM) V) -> (set-default SYM V) (gv.el simple setter).
((eq head 'default-value) (list 'set-default (car args) val))
((eq head 'symbol-function) (list 'fset (car args) val))
;; (setf (get SYM PROP) V) -> (put SYM PROP V).
((eq head 'get) (list 'put (car args) (car (cdr args)) val))
;; (setf (cl-get SYM PROP DEF) V) -> (put SYM PROP V); DEF is ignored, as in
;; cl-extra.el's gv-setter.
((eq head 'cl-get) (list 'put (car args) (car (cdr args)) val))
;; (setf (cl--find-class NAME) CLASS) -> (put NAME 'cl--class CLASS).
;; `cl--find-class' stores class descriptors on the symbol's plist, exactly
;; as cl-preloaded.el does; this is its gv setter.
((eq head 'cl--find-class)
(list 'put (car args) (list 'quote 'cl--class) val))
;; cl-first..cl-tenth name list positions; cl-rest is the cdr.
((eq head 'cl-rest) (list 'setcdr (car args) val))
((memq head '(cl-first cl-second cl-third cl-fourth cl-fifth
cl-sixth cl-seventh cl-eighth cl-ninth cl-tenth))
(let ((idx (cdr (assq head '((cl-first . 0) (cl-second . 1) (cl-third . 2)
(cl-fourth . 3) (cl-fifth . 4) (cl-sixth . 5)
(cl-seventh . 6) (cl-eighth . 7) (cl-ninth . 8)
(cl-tenth . 9))))))
(list 'setcar (list 'nthcdr idx (car args)) val)))
;; `decoded-time' is `(cl-defstruct (decoded-time (:type list)) ...)' in
;; Emacs (simple.el:11111), so its accessors are list-position places whose
;; setter is `(setcar (nthcdr INDEX TIME) VAL)' — the same expansion a
;; `:type list' struct generates. time-date.el relies on it (e.g.
;; `(setf (decoded-time-month time) ...)', `(cl-incf (decoded-time-year time) ...)').
((assq head '((decoded-time-second . 0) (decoded-time-minute . 1)
(decoded-time-hour . 2) (decoded-time-day . 3)
(decoded-time-month . 4) (decoded-time-year . 5)
(decoded-time-weekday . 6) (decoded-time-dst . 7)
(decoded-time-zone . 8)))
(list 'setcar
(list 'nthcdr
(cdr (assq head '((decoded-time-second . 0) (decoded-time-minute . 1)
(decoded-time-hour . 2) (decoded-time-day . 3)
(decoded-time-month . 4) (decoded-time-year . 5)
(decoded-time-weekday . 6) (decoded-time-dst . 7)
(decoded-time-zone . 8))))
(car args))
val))
;; (setf (alist-get K AL &optional DEFAULT REMOVE TESTFN) V): setcdr an
;; existing pair (found via TESTFN or eq), else prepend. With REMOVE, a V
;; equal to DEFAULT deletes the entry instead.
((eq head 'alist-get)
(let* ((key (car args)) (al (nth 1 args)) (default (nth 2 args))
(remove (nth 3 args)) (testfn (nth 4 args))
(getter (if testfn (list 'assoc key al testfn) (list 'assq key al)))
(eq-default (list 'eql '--ag-v-- default)))
(if remove
(list 'let (list (list '--ag-v-- val) (list '--ag-p-- getter))
(list 'if eq-default
(list 'when '--ag-p-- (setf--expand al (list 'delq '--ag-p-- al)))
(list 'if '--ag-p--
(list 'setcdr '--ag-p-- '--ag-v--)
(setf--expand al (list 'cons (list 'cons key '--ag-v--) al)))))
(list 'let (list (list '--ag-p-- getter))
(list 'if '--ag-p--
(list 'setcdr '--ag-p-- val)
(setf--expand al (list 'cons (list 'cons key val) al)))))))
;; (setf (plist-get P K) V) / (setf (cl-getf P K) V): set an existing value
;; cell, else prepend (K V) to P — matching Emacs's order for a new key.
((memq head '(plist-get cl-getf))
(list 'let (list (list '--pg-m-- (list 'plist-member (car args) (car (cdr args)))))
(list 'if '--pg-m--
(list 'setcar (list 'cdr '--pg-m--) val)
(setf--expand (car args)
(list 'cons (car (cdr args)) (list 'cons val (car args)))))))
;; A read-only cl-defstruct slot: setf is an error (cl-macs.el:3260).
((memq head cl-struct--slot-readonly)
(error "%s is a read-only slot" head))
;; A cl-defstruct accessor: (setf (NAME-SLOT s) v) -> (aset s INDEX v).
((assq head cl-struct--slot-index)
(list 'aset (car args) (cdr (assq head cl-struct--slot-index)) val))
;; The `(:type list)' form of the same: the slot is a list position.
((assq head cl-struct--slot-list-index)
(list 'setcar
(list 'nthcdr (cdr (assq head cl-struct--slot-list-index)) (car args))
val))
;; (setf (map-elt MAP KEY [DEFAULT [TESTFN]]) V): map.el's gv-expander --
;; `map-put!' in place, else rebind MAP to `map-insert' when the map has to
;; grow (an alist, or nil).
((eq head 'map-elt)
(list 'let
(list (list '--me-v-- val))
(list 'condition-case nil
(list 'map-put! (car args) (car (cdr args)) '--me-v-- (nth 3 args))
(list 'map-not-inplace
(setf--expand (car args)
(list 'map-insert (car args) (car (cdr args)) '--me-v--))
'--me-v--))))
;; (setf (cl-subseq SEQ START &optional END) V): destructively copy V into
;; SEQ[START..END) via cl-replace, then yield V — matching cl-lib's setter.
((eq head 'cl-subseq)
(list 'let (list (list '--ss-v-- val))
(list 'cl-replace (car args) '--ss-v--
:start1 (car (cdr args)) :end1 (car (cddr args)))
'--ss-v--))
;; Control-flow places (gv.el): setf threads into the value position of
;; each branch. Only one branch runs, so VAL may appear textually more
;; than once without being evaluated twice.
;; (setf (if C THEN ELSE...) V) -> (if C (setf THEN V) (setf (progn ELSE...) V))
((eq head 'if)
(list 'if (car args)
(setf--expand (car (cdr args)) val)
(setf--expand (cons 'progn (cdr (cdr args))) val)))
;; (setf (progn A B C) V) -> (progn A B (setf C V))
((eq head 'progn)
(append (list 'progn) (butlast args)
(list (setf--expand (car (last args)) val))))
;; (setf (cond (T A B) ...) V) -> (cond (T A (setf B V)) ...)
((eq head 'cond)
(cons 'cond
(mapcar (lambda (clause)
(append (list (car clause)) (butlast (cdr clause))
(list (setf--expand (car (last clause)) val))))
args)))
;; Unknown head: consult the gv.el registry first (gv.el:98 checks the
;; `gv-expander' property before anything else), so any place registered
;; via `gv-define-setter'/`gv-define-expander' (e.g. `gv-deref', user
;; places) works. `setf' is exactly `(gv-letplace (_getter setter) place
;; (funcall setter val))' (gv.el:288).
(t (let ((gf (function-get head 'gv-expander 'autoload)))
(if gf
(apply gf (lambda (_getter setter) (funcall setter val)) args)
;; No gv-expander: if PLACE is a macro call, expand it once and
;; retry (gv.el:103), else use the `(setf HEAD)' function setter
;; (installed via `(defalias (gv-setter aname) ...)').
(let ((me (macroexpand-1 place)))
(if (eq me place)
;; Follow a function alias (gv.el:112), so `cl-caddr' is
;; a place because `caddr' is.
(if (and (fboundp head) (symbolp (symbol-function head))
(symbol-function head))
(setf--expand (cons (symbol-function head) args) val)
(let ((setter (intern (format "(setf %s)" head))))
(if (fboundp setter)
(cons 'funcall (cons (list 'function setter) (cons val args)))
(signal 'gv-invalid-place (list place)))))
(setf--expand me val))))))))))
(defmacro setf (&rest pairs)
(let ((forms nil))
(while pairs
(setq forms (cons (setf--expand (car pairs) (car (cdr pairs))) forms))
(setq pairs (cdr (cdr pairs))))
(cons 'progn (reverse forms))))
;; ---- hooks (subr.el `add-hook'; C `run-hooks'/`run-hook-with-args') ----
;; Defined after the full `setf' (add-hook's depth-alist branch uses a `get'
;; place). add-hook is ported verbatim; the depth-alist / buffer-local branches
;; are dead in elisprs's global-only, no-buffer-local model but kept faithful.
(defun add-hook (hook function &optional depth local)
"Add to the value of HOOK the function FUNCTION.
FUNCTION is not added if already present."
(or (boundp hook) (set hook nil))
(or (default-boundp hook) (set-default hook nil))
(unless (numberp depth) (setq depth (if depth 90 0)))
(if local (unless (local-variable-if-set-p hook)
(set (make-local-variable hook) (list t)))
(when (and (local-variable-if-set-p hook)
(not (and (consp (symbol-value hook))
(memq t (symbol-value hook)))))
(setq local t)))
(let ((hook-value (if local (symbol-value hook) (default-value hook))))
(when (or (not (listp hook-value)) (functionp hook-value))
(setq hook-value (list hook-value)))
(unless (member function hook-value)
(let ((depth-sym (get hook 'hook--depth-alist)))
(unless (zerop depth)
(unless depth-sym
(setq depth-sym (make-symbol "depth-alist"))
(set depth-sym nil)
(setf (get hook 'hook--depth-alist) depth-sym))
(if local (make-local-variable depth-sym))
(setf (alist-get function
(if local (symbol-value depth-sym)
(default-value depth-sym))
0)
depth))
(setq hook-value
(if (< 0 depth)
(append hook-value (list function))
(cons function hook-value)))
(when depth-sym
(let ((depth-alist (if local (symbol-value depth-sym)
(default-value depth-sym))))
(when depth-alist
(setq hook-value
(sort (if (< 0 depth) hook-value (copy-sequence hook-value))
(lambda (f1 f2)
(< (alist-get f1 depth-alist 0 nil #'eq)
(alist-get f2 depth-alist 0 nil #'eq))))))))))
(if local
(progn
(and (symbolp function)
(get function 'permanent-local-hook)
(not (get hook 'permanent-local))
(put hook 'permanent-local 'permanent-local-hook))
(set hook hook-value))
(set-default hook hook-value))))
(defun run-hook-with-args (hook &rest args)
"Run HOOK with the specified arguments ARGS.
HOOK should be a symbol; its value is a function or a list of functions."
(when (boundp hook)
(let ((value (symbol-value hook)))
(if (functionp value)
(apply value args)
(dolist (f value)
(unless (eq f t)
(apply f args)))
nil))))
(defun run-hooks (&rest hooks)
"Run each hook in HOOKS, which are symbols whose values are lists of functions."
(dolist (hook hooks)
(run-hook-with-args hook))
nil)
(defun run-hook-with-args-until-success (hook &rest args)
"Run HOOK's functions with ARGS, stopping at the first non-nil result.
Return that result, or nil if every function returned nil."
;; C `run_hook_with_args' with `until_success' (eval.c). A hook whose value is
;; a single function is that one call; `t' inside a list is the buffer-local
;; marker and is skipped, as in `run-hook-with-args'.
(when (boundp hook)
(let ((value (symbol-value hook)))
(if (functionp value)
(apply value args)
(let ((res nil))
(while (and value (null res))
(unless (eq (car value) t)
(setq res (apply (car value) args)))
(setq value (cdr value)))
res)))))
(defun run-hook-with-args-until-failure (hook &rest args)
"Run HOOK's functions with ARGS, stopping at the first nil result.
Return nil if one returned nil, t otherwise."
;; C `run_hook_with_args' with `until_failure'. An unbound or empty hook has
;; no function that can fail, so the answer is t.
(if (not (boundp hook))
t
(let ((value (symbol-value hook)))
(if (functionp value)
(apply value args)
(let ((ok t))
(while (and value ok)
(unless (eq (car value) t)
(setq ok (apply (car value) args)))
(setq value (cdr value)))
(and ok t))))))
(defun run-hook-wrapped (hook wrap-function &rest args)
"Run HOOK's functions through WRAP-FUNCTION, stopping at the first non-nil.
Each function F is invoked as (funcall WRAP-FUNCTION F ARGS...)."
;; C `run_hook_wrapped' (eval.c): the wrapper decides how to call F, which is
;; what lets a caller install a `condition-case' or a timing shim around every
;; hook function without rewriting the hook.
(when (boundp hook)
(let ((value (symbol-value hook)))
(if (functionp value)
(apply wrap-function value args)
(let ((res nil))
(while (and value (null res))
(unless (eq (car value) t)
(setq res (apply wrap-function (car value) args)))
(setq value (cdr value)))
res)))))
(defun remove-hook (hook function &optional local)
"Remove FUNCTION from HOOK's functions.
Do nothing if HOOK does not currently contain FUNCTION."
;; Ported from subr.el:2186. FUNCTION is matched with `equal' (via `member'),
;; not `eq', so an anonymous function equal to the stored one removes it. The
;; depth-alist entry goes with it — leaving it behind leaks the entry and
;; re-orders the hook if the same function is added again (bug#46414).
(or (boundp hook) (set hook nil))
(or (default-boundp hook) (set-default hook nil))
(unless (and local (not (local-variable-p hook)))
(when (and (local-variable-p hook)
(not (and (consp (symbol-value hook))
(memq t (symbol-value hook)))))
(setq local t))
(let ((hook-value (if local (symbol-value hook) (default-value hook)))
(old-fun nil))
(if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
(when (equal hook-value function)
(setq old-fun hook-value)
(setq hook-value nil))
(when (setq old-fun (car (member function hook-value)))
(setq hook-value (remq old-fun hook-value))))
(when old-fun
(let* ((depth-sym (get hook 'hook--depth-alist))
(depth-alist (if depth-sym (if local (symbol-value depth-sym)
(default-value depth-sym))))
(di (assq old-fun depth-alist)))
(when di
(setf (if local (symbol-value depth-sym)
(default-value depth-sym))
(remq di depth-alist)))))
(if (not local)
(set-default hook hook-value)
(if (equal hook-value '(t))
(kill-local-variable hook)
(set hook hook-value))))))
;; ---- pcase: structural `cond` (non-backquote subset) ----
;; Supported patterns (compiled to tests + bindings at macroexpansion time):
;; _ wildcard — always matches
;; nil / t / :kw self-quoting literals (matched with `equal`)
;; NUMBER STRING self-quoting literals
;; SYMBOL binds SYMBOL to the value (anything not a literal above)
;; 'X / (quote X) literal X
;; (pred FN) matches when (FN VALUE) is non-nil; (pred (FN ARGS...)) →
;; (FN ARGS... VALUE), as in Emacs
;; (guard EXPR) matches when EXPR — which can read earlier bindings — is non-nil
;; (and PAT...) matches when every PAT matches (bindings accumulate)
;; (or PAT...) matches when any PAT matches
;; `QPAT pcase.el's backquote pattern: (Q1 . Q2) matches a cons,
;; [Q...] a vector of that length, ,PAT matches PAT, and
;; any other atom is compared with `equal'
;; How `pred'/`app' call FN on the value: a lambda or symbol gets VAL as its one
;; argument; a partial application (F ARGS…) appends VAL.
;; pcase.el `pcase--funcall': `_' in a call form stands for the matched value.
(defun pcase--apply (fn val)
(cond ((symbolp fn) (list fn val))
((eq 'not (car-safe fn)) (list 'not (pcase--apply (car (cdr fn)) val)))
((or (functionp fn) (not (consp fn))) (list 'funcall (list 'function fn) val))
((memq '_ fn) (mapcar (lambda (x) (if (eq '_ x) val x)) fn))
(t (append fn (list val)))))
(defconst regexp-unmatchable "\\`a\\`"
"Standard regexp guaranteed not to match any string at all.")
(defvar tab-width 8
"Distance between tab stops (for display of tab characters), in columns.
A buffer-local variable in Emacs; a plain global here, since elisprs has no
per-buffer display model. `string-pixel-width' and `char-width' read it.")
;; `string-pixel-width' (lisp/emacs-lisp/subr-x.el) renders STRING in a temp
;; buffer and asks `window-text-pixel-size' for its width. In batch every
;; character is one pixel wide per display column, so the pixel width IS the
;; display-column advance -- which is NOT `string-width': a TAB advances to the
;; next multiple of `tab-width' rather than counting a flat `tab-width' columns,
;; so `(string-pixel-width "ab\tc")' is 9 where `(string-width "ab\tc")' is 11.
;; A newline starts a new line and the widest line wins, so
;; `(string-pixel-width "a\nb")' is 1.
(defun string-pixel-width (string &optional _buffer)
"Return the width of STRING in pixels, as `emacs -Q --batch' measures it."
(let ((widest 0) (col 0) (i 0) (n (length string)) (c nil))
(while (< i n)
(setq c (aref string i))
(cond ((eq c ?\n)
(when (> col widest) (setq widest col))
(setq col 0))
((eq c ?\t)
(setq col (* tab-width (1+ (/ col tab-width)))))
(t (setq col (+ col (char-width c)))))
(setq i (1+ i)))
(when (> col widest) (setq widest col))
widest))
(defun pcase--literal-p (pat)
(or (numberp pat) (stringp pat) (keywordp pat) (eq pat t) (null pat)))
;; pcase.el's `\`' pattern, as `pcase-defmacro \`' defines it: a cons is
;; (and (pred consp) (app car-safe `Q1) (app cdr-safe `Q2)), a vector
;; (and (pred vectorp) (app length LEN) (app (aref _ I) `QI)...), ,PAT is PAT,
;; and a string, number or symbol is 'QPAT. The element readers are guarded,
;; because `pcase--clause' establishes the binders before the tests run.
(defun pcase--compile-qpat (qpat val)
(cond
((eq (car-safe qpat) '\,) (pcase--compile (car (cdr qpat)) val))
((eq (car-safe qpat) '\,@) (error "Unsupported QPAT: %S" qpat))
((vectorp qpat)
(let* ((len (length qpat))
(ok (list 'and (list 'vectorp val) (list '= (list 'length val) len)))
(tests (list (list 'vectorp val) (list 'equal (list 'length val) len)))
(binds nil)
(i 0))
(while (< i len)
(let ((r (pcase--compile-qpat (aref qpat i)
(list 'if ok (list 'aref val i)))))
(setq tests (append tests (car r)))
(setq binds (append binds (cdr r))))
(setq i (1+ i)))
(cons tests binds)))
((consp qpat)
(let ((cr (pcase--compile-qpat (car qpat) (list 'car-safe val)))
(cd (pcase--compile-qpat (cdr qpat) (list 'cdr-safe val))))
(cons (cons (list 'consp val) (append (car cr) (car cd)))
(append (cdr cr) (cdr cd)))))
((or (stringp qpat) (numberp qpat) (symbolp qpat))
(pcase--compile (list 'quote qpat) val))
(t (error "Unknown QPAT: %S" qpat))))
(defun pcase--compile (pat val)
;; Return (TESTS . BINDS): TESTS a list of boolean forms over VAL, BINDS a
;; list of (SYM ACCESSOR) let*-bindings. In this subset every binder captures
;; VAL whole, so accessors never car/cdr an atom.
(cond
((eq pat '_) (cons nil nil))
((pcase--literal-p pat) (cons (list (list 'equal val (list 'quote pat))) nil))
((symbolp pat) (cons nil (list (list pat val))))
((consp pat)
(let ((head (car pat)))
(cond
((eq head 'quote) (cons (list (list 'equal val pat)) nil))
((eq head 'pred) (cons (list (pcase--apply (car (cdr pat)) val)) nil))
((eq head 'guard) (cons (list (car (cdr pat))) nil))
;; `(cl-type TYPE)': route through `cl-typep', not through a
;; symbol-to-predicate name mangle, so a COMPOUND specifier works --
;; `(pcase 3 ((cl-type (integer 0 5)) 'in) (_ 'out))' is `in', where
;; naming a predicate after `(integer 0 5)' was `wrong-type-argument
;; symbolp'.
((eq head 'cl-type)
(cons (list (list 'cl-typep val (list 'quote (car (cdr pat))))) nil))
;; (app FN PAT): match PAT against (FN VAL).
((eq head 'app)
(let* ((tv (make-symbol "app"))
(r (pcase--compile (nth 2 pat) tv)))
(cons (car r) (cons (list tv (pcase--apply (nth 1 pat) val)) (cdr r)))))
;; (let PAT EXPR): match PAT against EXPR's value (EXPR ignores VAL).
((eq head 'let)
(let* ((tv (make-symbol "let"))
(r (pcase--compile (nth 1 pat) tv)))
(cons (car r) (cons (list tv (nth 2 pat)) (cdr r)))))
((eq head 'and)
(let ((tests nil) (binds nil))
(dolist (p (cdr pat))
(let ((r (pcase--compile p val)))
(setq tests (append tests (car r)))
(setq binds (append binds (cdr r)))))
(cons tests binds)))
((eq head 'or)
(let ((alts nil) (binds nil))
(dolist (p (cdr pat))
(let ((r (pcase--compile p val)))
(setq alts (append alts (list (cons 'and (car r)))))
(setq binds (append binds (cdr r)))))
(cons (list (cons 'or alts)) binds)))
((eq head '\`) (pcase--compile-qpat (car (cdr pat)) val))
;; (map KEY...): map.el's pattern. An element is a bare SYMBOL (bound to
;; the value at 'SYMBOL), a KEYWORD :k (binding k to the value at :k), or
;; a (KEY VAR [DEFAULT]) list whose KEY and DEFAULT are *evaluated*
;; forms. `map-elt' signals for anything that is not a map, and
;; `pcase--clause' establishes the binders before the tests run, so each
;; lookup is guarded by the same `mapp' the pattern tests.
((eq head 'map)
(let ((tests (list (list 'mapp val))) (binds nil))
(dolist (elt (cdr pat))
(setq binds
(append binds
(list (cond
((consp elt)
(list (nth 1 elt)
(list 'if (list 'mapp val)
(list 'map-elt val (nth 0 elt) (nth 2 elt)))))
((keywordp elt)
(list (intern (substring (symbol-name elt) 1))
(list 'if (list 'mapp val)
(list 'map-elt val elt))))
(t (list elt
(list 'if (list 'mapp val)
(list 'map-elt val (list 'quote elt))))))))))
(cons tests binds)))
;; (cl-struct TYPE SLOT...): cl-lib's pattern. A SLOT is a bare name
;; (bound to itself) or (SLOT VAR). The slot reads are guarded by the
;; type test, because `pcase--clause' establishes the binders around the
;; tests and `cl-struct-slot-value' signals on the wrong type -- a
;; non-matching value has to FAIL the clause, not error out of it.
((eq head 'cl-struct)
(let* ((type (nth 1 pat))
(typed (list 'cl-typep val (list 'quote type)))
(tests (list typed))
(binds nil))
(dolist (slot (cddr pat))
(let ((name (if (consp slot) (car slot) slot))
(var (if (consp slot) (nth 1 slot) slot)))
(setq binds
(append binds
(list (list var
(list 'if typed
(list 'cl-struct-slot-value
(list 'quote type)
(list 'quote name)
val))))))))
(cons tests binds)))
;; seq.el's `(pcase-defmacro seq (&rest patterns))': `(and (pred seqp)
;; (app (seq--elt-safe _ I) PI)...)', the bindings in reverse order.
((eq head 'seq)
(pcase--compile `(and (pred seqp) ,@(seq--make-pcase-bindings (cdr pat))) val))
;; A `pcase-defmacro' pattern: expand it and compile the expansion.
((and (symbolp head) (get head 'pcase-macroexpander))
(pcase--compile (apply (get head 'pcase-macroexpander) (cdr pat)) val))
(t (error "pcase: unsupported pattern %S" pat)))))
(t (error "pcase: unsupported pattern %S" pat))))
;; pcase.el `pcase-defmacro': define the expander function NAME--pcase-macroexpander
;; and record it on NAME's `pcase-macroexpander' property.
(defmacro pcase-defmacro (name args &rest body)
(let ((fsym (intern (format "%s--pcase-macroexpander" name))))
(list 'progn
(cons 'defun (cons fsym (cons args body)))
(list 'define-symbol-prop (list 'quote name) ''pcase-macroexpander
(list 'function fsym)))))
(defun pcase--clause (clause)
;; Build one `cond' clause (TEST BODY) from a pcase clause (PATTERN BODY...).
;; Bindings wrap BOTH the test and the body via `let*' so a `guard' in TEST
;; sees the binders. This `cond' shape (like `cl-case') expands cleanly when
;; nested in a macro-produced `defun' (e.g. an ERT `should'); a `catch'/`throw'
;; shape does not — it miscompiles to a "void variable" error there.
(let* ((r (pcase--compile (car clause) '--pcase-v--))
(tests (car r))
(binds (cdr r))
(conj (if tests (cons 'and tests) t))
(test (if binds (list 'let* binds conj) conj))
(body (cons 'progn (cdr clause))))
(list test (if binds (list 'let* binds body) body))))
(defmacro pcase (expr &rest clauses)
`(let ((--pcase-v-- ,expr))
(cond ,@(mapcar (function pcase--clause) clauses))))
(defmacro pcase-exhaustive (expr &rest clauses)
;; Like pcase, but error if no clause matches.
`(let ((--pcase-v-- ,expr))
(cond ,@(mapcar (function pcase--clause) clauses)
(t (error "No clause matching `%S'" --pcase-v--)))))
(defmacro pcase-let* (bindings &rest body)
;; Each binding is (PATTERN VALUE); destructure VALUE against PATTERN (reusing
;; `pcase--compile'), binding the pattern variables for BODY, in order.
(let ((lets nil) (i 0))
(dolist (b bindings)
(let* ((tv (intern (concat "--pl-" (number-to-string i) "--")))
(r (pcase--compile (car b) tv)))
(setq lets (cons (list tv (car (cdr b))) lets))
(dolist (bind (cdr r)) (setq lets (cons bind lets)))
(setq i (1+ i))))
`(let* ,(reverse lets) ,@body)))
;; pcase.el `pcase-let': every EXP is evaluated first (into a temporary unless
;; the pattern is a plain variable), then `pcase-let*' destructures them.
(defmacro pcase-let (bindings &rest body)
(if (null (cdr bindings))
`(pcase-let* ,bindings ,@body)
(let ((matches '()))
(dolist (binding (prog1 bindings (setq bindings nil)))
(cond
((memq (car binding) '(t _ pcase--dontcare))
(push (cons (make-symbol "_") (cdr binding)) bindings))
((and (symbolp (car binding)) (not (memq (car binding) '(t _ pcase--dontcare))))
(push binding bindings))
(t
(let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
(push (cons tmpvar (cdr binding)) bindings)
(push (list (car binding) tmpvar) matches)))))
`(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
(defmacro pcase-lambda (lambda-list &rest body)
"A `lambda' whose parameters may be pcase PATTERNS instead of names.
Each pattern parameter becomes a fresh name that a `pcase-let*' destructures
around BODY, so `(funcall (pcase-lambda (`(,a ,b)) (+ a b)) (list 1 2))' is 3."
(declare (doc-string 2) (indent defun))
;; As in pcase.el: a symbol (including `&optional'/`&rest') is an ordinary
;; parameter, anything else -- a `(\=` PAT)' form among them -- is a pattern.
(let ((bindings nil) (parameters nil) (i 0))
(dolist (pat lambda-list)
(if (consp pat)
(let ((arg (intern (concat "--pl-arg-" (number-to-string i) "--"))))
(setq bindings (cons (list pat arg) bindings))
(setq parameters (cons arg parameters)))
(setq parameters (cons pat parameters)))
(setq i (1+ i)))
(list 'lambda (nreverse parameters)
(cons 'pcase-let* (cons (nreverse bindings) body)))))
;; pcase.el `pcase-setq': pairs after the first become a `progn' of single
;; `pcase-setq's; a trivial pattern is a plain `setq'; otherwise each pattern
;; variable is `setq' to its value, the last assignment being the value.
(defconst pcase--dontcare-upats '(t _ pcase--dontcare))
(defun pcase--trivial-upat-p (upat)
(and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
(defmacro pcase-setq (pat val &rest args)
(cond
(args
(let ((arg-length (length args)))
(unless (evenp arg-length)
(signal 'wrong-number-of-arguments
(list 'pcase-setq (+ 2 arg-length)))))
(let ((result))
(while args
(push `(pcase-setq ,(pop args) ,(pop args))
result))
`(progn
(pcase-setq ,pat ,val)
,@(nreverse result))))
((pcase--trivial-upat-p pat)
`(setq ,pat ,val))
(t
(let* ((tv (make-symbol "x"))
(r (pcase--compile pat tv)))
`(let ((,tv ,val))
,@(mapcar (lambda (b) (list 'setq (car b) (car (cdr b)))) (cdr r)))))))
(defmacro pcase-dolist (spec &rest body)
;; Iterate (cadr SPEC), destructuring each element against (car SPEC).
(let ((ev (make-symbol "e")))
(list 'dolist (list ev (car (cdr spec)))
(cons 'pcase-let (cons (list (list (car spec) ev)) body)))))
;; help.el:2302 — defined here (after `pcase') because its body uses `pcase' and
;; elisprs expands macros when the `defun' is read, not when it is called.
(defun help-split-fundoc (docstring def &optional section)
"Split a function DOCSTRING into the actual doc and the usage info.
Return (USAGE . DOC), where USAGE is a string describing the argument
list of DEF, such as \"(apply FUNCTION &rest ARGUMENTS)\".
DEF is the function whose usage we're looking for in DOCSTRING.
With SECTION nil, return nil if there is no usage info; conversely,
SECTION t means to return (USAGE . DOC) even if there's no usage info.
When SECTION is \\='usage or \\='doc, return only that part."
(let* ((found (and docstring
(string-match "\n\n(fn\\(\\( .*\\)?)\\)\\'" docstring)))
(doc (if found
(and (memq section '(t nil doc))
(not (zerop (match-beginning 0)))
(substring docstring 0 (match-beginning 0)))
docstring))
(usage (and found
(memq section '(t nil usage))
(let ((tail (match-string 1 docstring)))
(format "(%s%s"
(if (and (symbolp def) def)
(help--docstring-quote (format "%S" def))
'anonymous)
tail)))))
(pcase section
(`nil (and usage (cons usage doc)))
(`t (cons usage doc))
(`usage usage)
(`doc doc))))
(defmacro seq-doseq (spec &rest body)
(declare (indent 1) (debug ((symbolp form &optional form) body)))
;; (seq-doseq (VAR SEQUENCE) BODY...) — iterate VAR over any sequence's
;; elements. Returns the sequence (like Emacs, via seq-do).
(let ((var (car spec)) (seq (car (cdr spec))) (sv (make-symbol "seq")))
`(let* ((,sv ,seq) (--seq-doseq-tail-- (append ,sv nil)) (,var nil))
(while --seq-doseq-tail--
(setq ,var (car --seq-doseq-tail--))
,@body
(setq --seq-doseq-tail-- (cdr --seq-doseq-tail--)))
,sv)))
;; seq.el: `seq-let' and `seq-setq' are `pcase-let' / `pcase-setq' over the
;; `seq' pattern `seq--make-pcase-patterns' builds from ARGS.
(defun seq--elt-safe (sequence n)
(ignore-errors (seq-elt sequence n)))
(defun seq--make-pcase-bindings (args)
(let ((bindings '())
(index 0)
(rest-marker nil))
(seq-doseq (name args)
(unless rest-marker
(if (eq name '&rest)
(progn (push `(app (seq-drop _ ,index)
,(seq--elt-safe args (1+ index)))
bindings)
(setq rest-marker t))
(push `(app (seq--elt-safe _ ,index) ,name) bindings)))
(setq index (1+ index)))
bindings))
(defun seq--make-pcase-patterns (args)
(cons 'seq
(seq-map (lambda (elt)
(if (seqp elt)
(seq--make-pcase-patterns elt)
elt))
args)))
(defmacro seq-let (args sequence &rest body)
(declare (indent 2) (debug (sexp form body)))
`(pcase-let ((,(seq--make-pcase-patterns args) ,sequence))
,@body))
(defmacro seq-setq (args sequence)
`(pcase-setq ,(seq--make-pcase-patterns args) ,sequence))
;; macroexp-unprogn / macroexp-let* / macroexp-let2 (macroexp.el:560,565,601).
;; `macroexp-let2' evaluates BODY with SYM bound to an expression for EXP: if
;; EXP is copyable per TEST, SYM is EXP itself; else SYM is a fresh symbol and
;; the result wraps a `let*' that evaluates EXP once. gv's place-expanders use
;; it to guarantee each place subform is evaluated exactly once.
(defun macroexp-unprogn (exp)
(if (eq (car-safe exp) 'progn) (or (cdr exp) '(nil)) (list exp)))
(defun macroexp-let* (bindings exp)
(cond ((null bindings) exp)
((eq 'let* (car-safe exp))
(append (list 'let* (append bindings (car (cdr exp)))) (cdr (cdr exp))))
(t (list 'let* bindings exp))))
;; The final test is `eql', where macroexp.el has `eq': a float is an immediate
;; here with no object identity, so `(eq 1.5 1.5)' on the SAME value is nil and
;; a copyable float EXP would be bound as a variable named `1.5'. `eql' answers
;; the same for every other value (SYM is either EXP itself or a fresh symbol).
(defmacro macroexp-let2 (test sym exp &rest body)
(declare (indent 3))
(let ((bodysym (make-symbol "body"))
(expsym (make-symbol "exp")))
`(let* ((,expsym ,exp)
(,sym (if (funcall #',(or test 'macroexp-const-p) ,expsym)
,expsym (make-symbol ,(symbol-name sym))))
(,bodysym ,(macroexp-progn body)))
(if (eql ,sym ,expsym) ,bodysym
(macroexp-let* (list (list ,sym ,expsym)) ,bodysym)))))
;; macroexp-small-p (macroexp.el:678): is EXP small enough to duplicate? gv's
;; `if'/`cond' expanders consult it (after `lexical-binding') to decide between
;; duplicating the DO code into each branch and building a runtime closure pair.
(defun macroexp--maxsize (exp size)
(cond ((< size 0) size)
((symbolp exp) (1- size))
((stringp exp) (- size (/ (length exp) 16)))
((vectorp exp)
(dotimes (i (length exp))
(setq size (macroexp--maxsize (aref exp i) size)))
(1- size))
((consp exp)
(dolist (e exp)
(setq size (macroexp--maxsize e size)))
(1- size))
(t -1)))
(defun macroexp-small-p (exp)
(> (macroexp--maxsize exp 10) 0))
;;; ---- gv.el: generalized-variable place expanders ----
;; Faithful port of emacs-lisp/gv.el's higher-order place model. A place-
;; expander is a function (do -> code) where DO is (getter setter -> code); it is
;; stored on the head symbol's `gv-expander' property (gv.el:71). `gv-get' turns
;; a PLACE form into that call, `gv-letplace' is its macro sugar, `gv-ref'/
;; `gv-deref' build first-class references, and `setf' (via `setf--expand's'
;; fallback) consults this registry for any place its own cond does not handle.
(define-error 'gv-invalid-place "Invalid place expression")
(defun gv-get (place do)
"Build the code that applies DO to PLACE (gv.el:80)."
(cond
((symbolp place)
(let ((me (macroexpand-1 place)))
(if (eq me place)
(funcall do place (lambda (v) (list 'setq place v)))
(gv-get me do))))
((not (consp place)) (signal 'gv-invalid-place (list place)))
(t
(let* ((head (car place))
(gf (function-get head 'gv-expander 'autoload)))
(if gf (apply gf do (cdr place))
(let ((me (macroexpand-1 place)))
(if (and (eq me place) (get head 'compiler-macro))
(setq me (apply (get head 'compiler-macro) place (cdr place))))
(if (and (eq me place) (fboundp head)
(symbolp (symbol-function head)))
(setq me (cons (symbol-function head) (cdr place))))
(if (eq me place)
(if (and (symbolp head) (get head 'setf-method))
(error "Incompatible place needs recompilation: %S" head)
(let ((setter (gv-setter head)))
(gv--defsetter head (lambda (&rest args) (cons setter args))
do (cdr place))))
(gv-get me do))))))))
(defmacro gv-letplace (vars place &rest body)
"Build the code manipulating the generalized variable PLACE (gv.el:133)."
(declare (indent 2))
`(gv-get ,place (lambda ,vars ,@body)))
(defmacro gv-define-expander (name handler)
"Use HANDLER to handle NAME as a generalized var (gv.el:150)."
(declare (indent 1))
`(function-put ',name 'gv-expander ,handler))
(defun gv--defsetter (name setter do args &optional vars)
"Helper used by code generated by `gv-define-setter' (gv.el:227)."
(if (null args)
(let ((vars (nreverse vars)))
(funcall do (cons name vars) (lambda (v) (apply setter v vars))))
(macroexp-let2 nil v (car args)
(gv--defsetter name setter do (cdr args) (cons v vars)))))
(defmacro gv-define-setter (name arglist &rest body)
"Define a setter method for generalized variable NAME (gv.el:242)."
(declare (indent 2))
`(gv-define-expander ,name
(lambda (do &rest args)
(gv--defsetter ',name (lambda ,arglist ,@body) do args))))
(defmacro gv-define-simple-setter (name setter &optional fix-return)
"Define a simple setter method for generalized variable NAME (gv.el:262).
Assignments of VAL to (NAME ARGS...) become (SETTER ARGS... VAL)."
`(gv-define-setter ,name (val &rest args)
,(if fix-return
`(macroexp-let2 nil v val
`(progn
(,',setter ,@args ,v)
,v))
``(,',setter ,@args ,val))))
;;; The common generalized variables (gv.el:348).
(gv-define-simple-setter aref aset)
(gv-define-simple-setter char-table-range set-char-table-range)
(gv-define-simple-setter car setcar)
(gv-define-simple-setter cdr setcdr)
(gv-define-setter caar (val x) `(setcar (car ,x) ,val))
(gv-define-setter cadr (val x) `(setcar (cdr ,x) ,val))
(gv-define-setter cdar (val x) `(setcdr (car ,x) ,val))
(gv-define-setter cddr (val x) `(setcdr (cdr ,x) ,val))
(gv-define-setter elt (store seq n)
`(if (listp ,seq) (setcar (nthcdr ,n ,seq) ,store)
(aset ,seq ,n ,store)))
(gv-define-simple-setter get put)
(gv-define-setter gethash (val k h &optional _d) `(puthash ,k ,val ,h))
(put 'nth 'gv-expander
(lambda (do idx list)
(macroexp-let2 nil c `(nthcdr ,idx ,list)
(funcall do `(car ,c) (lambda (v) `(setcar ,c ,v))))))
(gv-define-simple-setter symbol-function fset)
(gv-define-simple-setter symbol-plist setplist)
(gv-define-simple-setter symbol-value set)
(put 'nthcdr 'gv-expander
(lambda (do n place)
(macroexp-let2 nil idx n
(gv-letplace (getter setter) place
(funcall do `(nthcdr ,idx ,getter)
(lambda (v) `(if (<= ,idx 0) ,(funcall setter v)
(setcdr (nthcdr (1- ,idx) ,getter) ,v))))))))
(gv-define-simple-setter default-value set-default)
;;; Control-flow and "occasionally handy" place expanders (gv.el:459). These
;; show up as the output of macroexpanding real places (e.g. struct accessors)
;; and, in nadvice, as literal `(gv-ref (cond ...))'. Since elisprs's
;; `lexical-binding' is nil, the `(not lexical-binding)' branch always fires:
;; the DO code is duplicated into each branch rather than closed over at runtime.
(put 'progn 'gv-expander
(lambda (do &rest exps)
(let ((start (butlast exps))
(end (car (last exps))))
(if (null start) (gv-get end do)
`(progn ,@start ,(gv-get end do))))))
(let ((let-expander
(lambda (letsym)
(lambda (do bindings &rest body)
`(,letsym ,bindings
,@(macroexp-unprogn
(gv-get (macroexp-progn body) do)))))))
(put 'let 'gv-expander (funcall let-expander 'let))
(put 'let* 'gv-expander (funcall let-expander 'let*)))
(put 'if 'gv-expander
(lambda (do test then &rest else)
(if (or (not lexical-binding)
(macroexp-small-p (funcall do 'dummy (lambda (_) 'dummy))))
`(if ,test ,(gv-get then do)
,@(macroexp-unprogn (gv-get (macroexp-progn else) do)))
(let ((v (gensym "v")))
(macroexp-let2 nil
gv `(if ,test ,(gv-letplace (getter setter) then
`(cons (lambda () ,getter)
(lambda (,v) ,(funcall setter v))))
,(gv-letplace (getter setter) (macroexp-progn else)
`(cons (lambda () ,getter)
(lambda (,v) ,(funcall setter v)))))
(funcall do `(funcall (car ,gv))
(lambda (v) `(funcall (cdr ,gv) ,v))))))))
(put 'cond 'gv-expander
(lambda (do &rest branches)
(if (or (not lexical-binding)
(macroexp-small-p (funcall do 'dummy (lambda (_) 'dummy))))
`(cond
,@(mapcar (lambda (branch)
(if (cdr branch)
(cons (car branch)
(macroexp-unprogn
(gv-get (macroexp-progn (cdr branch)) do)))
(gv-get (car branch) do)))
branches))
(let ((v (gensym "v")))
(macroexp-let2 nil
gv `(cond
,@(mapcar
(lambda (branch)
(if (cdr branch)
`(,(car branch)
,@(macroexp-unprogn
(gv-letplace (getter setter)
(macroexp-progn (cdr branch))
`(cons (lambda () ,getter)
(lambda (,v) ,(funcall setter v))))))
(gv-letplace (getter setter)
(car branch)
`(cons (lambda () ,getter)
(lambda (,v) ,(funcall setter v))))))
branches))
(funcall do `(funcall (car ,gv))
(lambda (v) `(funcall (cdr ,gv) ,v))))))))
(put 'cons 'gv-expander
(lambda (do a d)
(gv-letplace (agetter asetter) a
(gv-letplace (dgetter dsetter) d
(funcall do
`(cons ,agetter ,dgetter)
(lambda (v)
(macroexp-let2 nil v v
`(progn
,(funcall asetter `(car ,v))
,(funcall dsetter `(cdr ,v))
,v))))))))
(put 'logand 'gv-expander
(lambda (do place &rest masks)
(gv-letplace (getter setter) place
(macroexp-let2 macroexp-copyable-p
mask (if (cdr masks) `(logand ,@masks) (car masks))
(funcall
do `(logand ,getter ,mask)
(lambda (v)
(macroexp-let2 nil v v
`(progn
,(funcall setter
`(logior (logand ,v ,mask)
(logand ,getter (lognot ,mask))))
,v))))))))
;; (setf (error ...) ..) appears naturally from macroexpanding places like
;; (setf (pcase-exhaustive ...)) (gv.el:646).
(gv-define-expander error (lambda (_do &rest args) `(error . ,args)))
;;; References (gv.el:597).
(defmacro gv-ref (place)
"Return a reference to PLACE (gv.el:600).
This is like the `&' operator of the C language."
(gv-letplace (getter setter) place
`(cons (lambda () ,getter)
(lambda (gv--val) ,(funcall setter 'gv--val)))))
(defsubst gv-deref (ref)
"Dereference REF, returning the referenced value (gv.el:621)."
(funcall (car ref)))
(gv-define-setter gv-deref (v ref) `(funcall (cdr ,ref) ,v))
;; (setf (eq a 7) B) means (setq a 7) or (setq a nil) per B's truthiness — used
;; by define-minor-mode's :variable (gv.el:813).
(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))))))))))
(defun hash-table-empty-p (h) (= 0 (hash-table-count h)))
;; Emacs 30 dropped the per-table rehash parameters from `struct
;; Lisp_Hash_Table'; both accessors survive and answer the same constant for
;; every table (measured on GNU Emacs 30.2: 1.5 and 0.8125, for a default table
;; and for `:size 99' alike).
(defun hash-table-rehash-size (_table) 1.5)
(defun hash-table-rehash-threshold (_table) 0.8125)
;;; ---- Customize declaration machinery (custom.el / cus-face.el) ----
;; Faithful port of the DECLARATION half of custom.el: `defgroup', `defcustom',
;; `defface' and the `custom-declare-*' functions they expand into, storing the
;; same observable symbol properties real Emacs stores at declaration time
;; (standard-value, custom-type, custom-requests, custom-group,
;; group-documentation, face-defface-spec, ...). This lets libraries that
;; declare options (sort.el, ansi-color.el, ...) load. The Customize *UI*
;; (widget.el, cus-edit.el, `custom-set-variables' persistence) and live face
;; objects/frames are out of scope; where a facet needs them the boundary is
;; named below.
;;
;; `lexical-binding' is nil while the prelude loads; `load' binds it to each
;; file's cookie (`file_lexical_cookie' in src/host.rs), and `*scratch*' has it
;; t from `lisp-interaction-mode'. The `defcustom' macro branches on it to
;; decide how STANDARD is stashed: nil quotes it, so `standard-value' is
;; (DEFAULT); t wraps it in `(funcall #'(lambda () DEFAULT))', as in Emacs.
(defvar lexical-binding nil)
(defvar purify-flag nil)
(defvar custom-define-hook nil) ; custom.el:38
(defvar custom-dont-initialize nil) ; custom.el:42
(defvar custom-current-group-alist nil) ; custom.el:47
;; C `current-load-list' (lread.c): `load' accumulates definitions on it. A
;; plain global is enough for `custom-declare-face' to push onto here.
(defvar current-load-list nil)
;; custom.el:52 — set SYMBOL to EXP only if it has no default binding yet.
(defun custom-initialize-default (symbol exp)
(condition-case nil
(default-toplevel-value symbol)
(void-variable
(set-default-toplevel-value
symbol (eval (let ((sv (get symbol 'saved-value)))
(if sv (car sv) exp))
t)))))
;; custom.el:68
(defun custom-initialize-set (symbol exp)
(condition-case nil
(default-toplevel-value symbol)
(error
(funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
symbol
(eval (let ((sv (get symbol 'saved-value)))
(if sv (car sv) exp)))))))
;; custom.el:84 — the default `:initialize' every plain `defcustom' uses.
(defun custom-initialize-reset (symbol exp)
;; The `custom-check-value'/widget branch only fires for options previously
;; set via `setopt'; it never runs at declaration (custom-check-value is nil),
;; so `widget-convert'/`widget-apply' — part of the out-of-scope widget UI —
;; are never called here.
(let ((value (get symbol 'custom-check-value)))
(when value
(let ((type (get symbol 'custom-type)))
(when (and type
(boundp symbol)
(eq (car value) (symbol-value symbol))
(not (widget-apply (widget-convert type)
:match (car value))))
(warn "Value `%S' for `%s' does not match type %s"
value symbol type)))))
(funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
symbol
(condition-case nil
(let ((def (default-toplevel-value symbol))
(getter (get symbol 'custom-get)))
(if getter (funcall getter symbol) def))
(error
(eval (let ((sv (get symbol 'saved-value)))
(if sv (car sv) exp)))))))
;; custom.el:117
(defun custom-initialize-changed (symbol exp)
(condition-case nil
(let ((def (default-toplevel-value symbol)))
(funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
symbol
(let ((getter (get symbol 'custom-get)))
(if getter (funcall getter symbol) def))))
(error
(cond
((get symbol 'saved-value)
(funcall (or (get symbol 'custom-set) #'set-default-toplevel-value)
symbol
(eval (car (get symbol 'saved-value)))))
(t
(set-default-toplevel-value symbol (eval exp)))))))
;; custom.el:137
(defvar custom-delayed-init-variables nil
"List of variables whose initialization is pending until startup.
Once this list has been processed, this var is set to a non-list value.")
;; custom.el:141
(defun custom-initialize-delay (symbol value)
"Delay initialization of SYMBOL to the next Emacs start.
This is used in files that are preloaded (or for autoloaded
variables), so that the initialization is done in the run-time
context rather than the build-time context."
;; Defvar it so as to mark it special, etc (bug#25770).
(internal--define-uninitialized-variable symbol)
;; Until the var is actually initialized, it is kept unbound.
(if (listp custom-delayed-init-variables)
(push symbol custom-delayed-init-variables)
;; In case this is called after startup, there is no "later" to which to
;; delay it, so initialize it "normally" (bug#47072).
(custom-initialize-reset symbol value)))
;; eval.c `internal--define-uninitialized-variable': mark SYMBOL special
;; (dynamically bound) for good and record DOC, without touching its value.
(defun internal--define-uninitialized-variable (symbol &optional doc)
(--declare-special symbol)
(when doc (put symbol 'variable-documentation doc))
nil)
;; custom.el:479
(defun custom-current-group ()
(cdr (assoc load-file-name custom-current-group-alist)))
;; custom.el:545
(defun custom-add-to-group (group option widget)
(let ((members (get group 'custom-group))
(entry (list option widget)))
(unless (member entry members)
(put group 'custom-group (nconc members (list entry))))))
;; custom.el:626
(defun custom-add-option (symbol option)
(let ((options (get symbol 'custom-options)))
(unless (member option options)
(put symbol 'custom-options (cons option options)))))
;; custom.el:652
(defun custom-add-load (symbol load)
(let ((loads (get symbol 'custom-loads)))
(unless (member load loads)
(put symbol 'custom-loads (cons (purecopy load) loads)))))
;; custom.el:659
(defun custom-autoload (symbol load &optional noset)
"Mark SYMBOL as autoloaded custom variable and add dependency LOAD.
If NOSET is non-nil, don't bother autoloading LOAD when setting the variable."
(put symbol 'custom-autoload (if noset 'noset t))
(custom-add-load symbol load))
;; custom.el:638
(defun custom-add-link (symbol widget)
(let ((links (get symbol 'custom-links)))
(unless (member widget links)
(put symbol 'custom-links (cons (purecopy widget) links)))))
;; custom.el:644
(defun custom-add-version (symbol version)
(put symbol 'custom-version (purecopy version)))
;; custom.el:648
(defun custom-add-package-version (symbol version)
(put symbol 'custom-package-version (purecopy version)))
;; custom.el:607
(defun custom-add-dependencies (symbol value)
(unless (listp value)
(error "Invalid custom dependency `%s'" value))
(let* ((deps (get symbol 'custom-dependencies))
(new-deps deps))
(while value
(let ((dep (car value)))
(unless (symbolp dep)
(error "Invalid custom dependency `%s'" dep))
(unless (memq dep new-deps)
(setq new-deps (cons dep new-deps)))
(setq value (cdr value))))
(unless (eq deps new-deps)
(put symbol 'custom-dependencies new-deps))))
;; custom.el:585
(defun custom-handle-keyword (symbol keyword value type)
(if purify-flag
(setq value (purecopy value)))
(cond ((eq keyword :group)
(custom-add-to-group value symbol type))
((eq keyword :version)
(custom-add-version symbol value))
((eq keyword :package-version)
(custom-add-package-version symbol value))
((eq keyword :link)
(custom-add-link symbol value))
((eq keyword :load)
(custom-add-load symbol value))
((eq keyword :tag)
(put symbol 'custom-tag value))
((eq keyword :set-after)
(custom-add-dependencies symbol value))
(t
(error "Unknown keyword %s" keyword))))
;; custom.el:566
(defun custom-handle-all-keywords (symbol args type)
(unless (memq :group args)
(let ((cg (custom-current-group)))
(when cg
(custom-add-to-group cg symbol type))))
(while args
(let ((arg (car args)))
(setq args (cdr args))
(unless (symbolp arg)
(error "Junk in args %S" args))
(let ((keyword arg)
(value (car args)))
(unless args
(error "Keyword %s is missing an argument" keyword))
(setq args (cdr args))
(custom-handle-keyword symbol keyword value type)))))
;; custom.el:161
(defun custom-declare-variable (symbol default doc &rest args)
(put symbol 'standard-value (purecopy (list default)))
(when (get symbol 'force-value)
(put symbol 'force-value nil))
(if (keywordp doc)
(error "Doc string is missing"))
(let ((initialize #'custom-initialize-reset)
(requests nil)
buffer-local)
(unless (memq :group args)
(let ((cg (custom-current-group)))
(when cg
(custom-add-to-group cg symbol 'custom-variable))))
(while args
(let ((keyword (pop args)))
(unless (symbolp keyword)
(error "Junk in args %S" args))
(unless args
(error "Keyword %s is missing an argument" keyword))
(let ((value (pop args)))
(cond ((eq keyword :initialize)
(setq initialize value))
((eq keyword :set)
(put symbol 'custom-set value))
((eq keyword :get)
(put symbol 'custom-get value))
((eq keyword :require)
(push value requests))
((eq keyword :risky)
(put symbol 'risky-local-variable value))
((eq keyword :safe)
(put symbol 'safe-local-variable value))
((eq keyword :local)
(when (memq value '(t permanent))
(setq buffer-local t))
(when (eq value 'permanent)
(put symbol 'permanent-local t)))
((eq keyword :type)
(put symbol 'custom-type (purecopy value)))
((eq keyword :options)
(if (get symbol 'custom-options)
(mapc (lambda (option)
(custom-add-option symbol option))
value)
(put symbol 'custom-options (copy-sequence value))))
(t
(custom-handle-keyword symbol keyword value
'custom-variable))))))
(internal--define-uninitialized-variable symbol doc)
(put symbol 'custom-requests requests)
(unless custom-dont-initialize
(funcall initialize symbol default)
(let ((theme (caar (get symbol 'theme-value))))
(when (and theme (not (eq theme 'user)) (get symbol 'saved-value))
(put symbol 'saved-value nil))))
(when buffer-local
(make-variable-buffer-local symbol)))
(run-hooks 'custom-define-hook)
symbol)
;; custom.el:482
(defun custom-declare-group (symbol members doc &rest args)
(while members
(apply #'custom-add-to-group symbol (car members))
(setq members (cdr members)))
(when doc
(put symbol 'group-documentation (purecopy doc)))
(while args
(let ((arg (car args)))
(setq args (cdr args))
(unless (symbolp arg)
(error "Junk in args %S" args))
(let ((keyword arg)
(value (car args)))
(unless args
(error "Keyword %s is missing an argument" keyword))
(setq args (cdr args))
(cond ((eq keyword :prefix)
(put symbol 'custom-prefix (purecopy value)))
(t
(custom-handle-keyword symbol keyword value
'custom-group))))))
(let ((elt (assoc load-file-name custom-current-group-alist)))
(if elt (setcdr elt symbol)
(push (cons load-file-name symbol) custom-current-group-alist)))
(run-hooks 'custom-define-hook)
symbol)
;; C subr: t if OBJECT can serve as a documentation string — a string, an
;; integer DOC-file offset, or a (string . offset) cons.
(defun documentation-stringp (object)
(or (stringp object)
(integerp object)
(and (consp object) (stringp (car object)) (integerp (cdr object)))))
;; faces.el:647
(defun face-documentation (face)
"Get the documentation string for FACE.
If FACE is a face-alias, get the documentation for the target face."
(let ((alias (get face 'face-alias)))
(if alias
(let ((doc (documentation-property alias 'face-documentation)))
(format "%s is an alias for the face `%s'.%s" face alias
(if doc (format "\n%s" doc)
"")))
(documentation-property face 'face-documentation))))
;; faces.el:662
(defun set-face-documentation (face string)
(put face 'face-documentation (purecopy string)))
;; faces.el:1685 — declaration-scope port: store the face spec under the
;; requested property (this is the observable half). BOUNDARY: real
;; `face-spec-set' then calls `make-empty-face' and recalculates the face on
;; every frame (`face-spec-recalc'). elisprs has no display subsystem — no face
;; objects, no frames — so those are omitted; no face object is created.
;; xfaces.c — the frame-independent face table. Batch Emacs keeps every
;; face's global attribute vector all-`unspecified' (attributes are
;; realized per frame from the specs), so that is what is modelled.
(defvar face--new-frame-defaults (make-hash-table :test 'eq)
"Hash table of global face definitions (for internal use only.)")
(defun editfns--resolve-face-name (face)
"resolve_face_name: a string names the interned symbol; aliases are followed."
(when (stringp face)
(setq face (intern face)))
(let ((depth 0))
(while (and (symbolp face) (get face 'face-alias) (< depth 10))
(setq face (get face 'face-alias) depth (1+ depth))))
face)
(defun internal-make-lisp-face (face &optional frame)
"Make FACE, a symbol, a Lisp face with all attributes unspecified.
If FACE was not known as a face before, create a new one.
If optional argument FRAME is specified, make a frame-local face
for that frame. Otherwise operate on the global face definition.
Value is a vector of face attributes."
(ignore frame)
(unless (symbolp face)
(signal 'wrong-type-argument (list 'symbolp face)))
(let ((entry (gethash face face--new-frame-defaults)))
(if entry
(cdr entry)
(let ((vec (make-vector 20 'unspecified)))
(aset vec 0 'face)
(puthash face (cons (hash-table-count face--new-frame-defaults) vec)
face--new-frame-defaults)
vec))))
(defun internal-lisp-face-p (face &optional frame)
"Return non-nil if FACE names a face.
FACE should be a symbol or string.
If optional second argument FRAME is non-nil, check for the
existence of a frame-local face with name FACE on that frame.
Otherwise check for the existence of a global face."
(ignore frame)
(setq face (editfns--resolve-face-name face))
(and (symbolp face)
(cdr (gethash face face--new-frame-defaults))))
(defun make-face-x-resource-internal (face &optional frame)
"Make FACE a face with the attributes X resources give it.
There are no X resources without a window system, so this does nothing."
(ignore face frame)
nil)
(defun face-font (face &optional frame character)
"Return the font name of face FACE, or nil if it is unspecified.
On the terminal frame of batch Emacs every realized face has the font
\"tty\"; with FRAME t the global face's bold and italic attributes are
consulted, which batch Emacs leaves unspecified."
(ignore character)
(if (eq frame t)
nil
(unless (facep face)
(signal 'error (list "Invalid face" face)))
"tty"))
;; faces.el (Emacs 31.1), verbatim.
(defun face-list ()
"Return a list of all defined faces."
(let (faces)
(maphash (lambda (face spec)
(push `(,(car spec) . ,face) faces))
face--new-frame-defaults)
(mapcar #'cdr (sort faces (lambda (f1 f2) (> (car f1) (car f2)))))))
(defun make-face (face)
"Define a new face with name FACE, a symbol.
Do not call this directly from Lisp code; use `defface' instead.
If FACE is already known as a face, leave it unmodified. Return FACE."
(interactive (list (read-from-minibuffer
"Make face: " nil nil t 'face-name-history)))
(unless (facep face)
;; Make frame-local faces (this also makes the global one).
(dolist (frame (frame-list))
(internal-make-lisp-face face frame))
;; Add the face to the face menu.
(when (fboundp 'facemenu-add-new-face)
(facemenu-add-new-face face))
;; Define frame-local faces for all frames from X resources.
(make-face-x-resource-internal face))
face)
(defun make-empty-face (face)
"Define a new, empty face with name FACE.
Do not call this directly from Lisp code; use `defface' instead."
(interactive (list (read-from-minibuffer
"Make empty face: " nil nil t 'face-name-history)))
(make-face face))
(defun facep (face)
"Return non-nil if FACE is a face name; nil otherwise.
A face name can be a string or a symbol."
(internal-lisp-face-p face))
(defun face-spec-set (face spec &optional spec-type)
(if (get face 'face-alias)
(setq face (get face 'face-alias)))
(unless spec-type
(setq spec-type 'face-override-spec))
(if (memq spec-type '(face-defface-spec face-override-spec
customized-face saved-face))
(put face spec-type spec))
(if (memq spec-type '(reset saved-face))
(put face 'customized-face nil))
(if (memq spec-type '(customized-face saved-face reset))
(put face 'face-override-spec nil))
(unless (eq face 'face-override-spec)
(put face 'face-modified nil))
;; Initialize the face if it does not exist. (Recalculating its
;; attributes per frame, `face-spec-recalc', is not modelled.)
(make-empty-face face))
;; cus-face.el:32
(defun custom-declare-face (face spec doc &rest args)
(when (and doc
(not (documentation-stringp doc)))
(error "Invalid (or missing) doc string %S" doc))
(unless (get face 'face-defface-spec)
(face-spec-set face (purecopy spec) 'face-defface-spec)
(push (cons 'defface face) current-load-list)
(when doc
(set-face-documentation face (purecopy doc)))
(custom-handle-all-keywords face args 'custom-face)
(run-hooks 'custom-define-hook))
face)
;; custom.el:512 — no backquote here, matching the upstream bootstrap note.
(defmacro defgroup (symbol members doc &rest args)
(declare (doc-string 3) (indent defun))
(nconc (list 'custom-declare-group (list 'quote symbol) members doc) args))
;; custom.el (Emacs 31.1; 30.2 put a "" docstring in the lambda)
(defmacro defcustom (symbol standard doc &rest args)
(declare (doc-string 3) (debug (name body)) (indent defun))
`(custom-declare-variable
',symbol
,(if lexical-binding
``(funcall #',(lambda () ,standard))
`',standard)
,doc
,@args))
;; custom.el:409
(defmacro defface (face spec doc &rest args)
(declare (doc-string 3) (indent defun))
(nconc (list 'custom-declare-face (list 'quote face) spec doc) args))
;;; ---- password-prompt recognition data (international/mule-conf.el) ----
;; mule-conf.el is preloaded in Emacs, so these are always bound. Both are
;; fixed, build-independent i18n data lists — captured value-for-value from GNU
;; Emacs 30.2 mule-conf.el:1681/1739. Used by comint.el/shell.el and friends to
;; build `comint-password-prompt-regexp'. Placed after `defcustom' is defined.
;; mule-conf.el:1681
(defcustom password-word-equivalents
'("password" "passcode" "passphrase" "pass phrase" "pin"
"decryption key" "encryption key" ; From ccrypt.
; These are sorted according to the GNU en_US locale.
"암호" ; ko
"パスワード" ; ja
"ପ୍ରବେଶ ସଙ୍କେତ" ; or
"ពាក្យសម្ងាត់" ; km
"adgangskode" ; da
"contraseña" ; es
"contrasenya" ; ca
"geslo" ; sl
"hasło" ; pl
"heslo" ; cs, sk
"iphasiwedi" ; zu
"jelszó" ; hu
"lösenord" ; sv
"lozinka" ; hr, sr
"mật khẩu" ; vi
"mot de passe" ; fr
"parola" ; tr
"pasahitza" ; eu
"passord" ; nb
"passwort" ; de
"pasvorto" ; eo
"salasana" ; fi
"senha" ; pt
"slaptažodis" ; lt
"wachtwoord" ; nl
"كلمة السر" ; ar
"ססמה" ; he
"лозинка" ; sr
"пароль" ; kk, ru, uk
"गुप्तशब्द" ; mr
"शब्दकूट" ; hi
"પાસવર્ડ" ; gu
"సంకేతపదము" ; te
"ਪਾਸਵਰਡ" ; pa
"ಗುಪ್ತಪದ" ; kn
"கடவுச்சொல்" ; ta
"അടയാളവാക്ക്" ; ml
"গুপ্তশব্দ" ; as
"পাসওয়ার্ড" ; bn_IN
"රහස්පදය" ; si
"密码" ; zh_CN
"密碼" ; zh_TW
)
"List of words equivalent to \"password\".
This is used by Shell mode and other parts of Emacs to recognize
password prompts, including prompts in languages other than
English. Different case choices should not be assumed to be
included; callers should bind `case-fold-search' to t."
:type '(repeat string)
:version "27.1"
:group 'processes)
;; mule-conf.el:1739
(defcustom password-colon-equivalents
'(?: ; ?\N{COLON}
?: ; ?\N{FULLWIDTH COLON}
?﹕ ; ?\N{SMALL COLON}
?︓ ; ?\N{PRESENTATION FORM FOR VERTICAL COLON}
?៖ ; ?\N{KHMER SIGN CAMNUC PII KUUH}
)
"List of characters equivalent to trailing colon in \"password\" prompts."
:type '(repeat character)
:version "30.1"
:group 'processes)
;;; ---- files.el pure-data regexps ----
;; files.el:1180 `locate-dominating-stop-dir-regexp': a plain `defvar' whose
;; value is a fixed, build-independent regexp string (purecopy'd in the C tree).
;; Read by `locate-dominating-file' to decide which directory names terminate an
;; upward search. Ported value-for-value from GNU Emacs 30.2 files.el.
(defvar locate-dominating-stop-dir-regexp
(purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
"Regexp of directory names that stop the search in `locate-dominating-file'.
Any directory whose name matches this regexp will be treated like
a kind of root directory by `locate-dominating-file', which will stop its
search when it bumps into it.
The default regexp prevents fruitless and time-consuming attempts to find
special files in directories in which file names are interpreted as host names,
or mount points potentially requiring authentication as a different user.")
;; files.el:1722 `mounted-file-systems': a `defcustom' regexp. The standard
;; value is platform-conditional; the `if' is kept intact so the value is
;; correct on any `system-type' (Windows/Cygwin get "^//[^/]+/", the rest get
;; the regexp-opt-precomputed alternation). Ported value-for-value; oracle on
;; darwin yields the else branch. `:require 'regexp-opt' is honored by
;; `custom-declare-variable' (pushed onto its requests list).
(defcustom mounted-file-systems
(if (memq system-type '(windows-nt cygwin))
"^//[^/]+/"
"^\\(?:/\\(?:afs/\\|m\\(?:edia/\\|nt\\)\\|\\(?:ne\\|tmp_mn\\)t/\\)\\)")
"File systems that ought to be mounted."
:group 'files
:version "26.1"
:require 'regexp-opt
:type 'regexp)
;;; ---- per-user Emacs file location (files.el / startup.el) ----
;; startup.el:597 sets `user-emacs-directory' at startup; the defvar itself is
;; nil ("The value does not matter since Emacs sets this at startup"). elisprs
;; does not run the C/startup init path, so we seed the documented runtime value
;; "~/.emacs.d/" -- oracle-confirmed against emacs -Q --batch (30.2).
;; startup.el
(defvar init-file-user nil
"Identity of user whose init file is or was read.")
;; startup.el (effective runtime value; Emacs sets this at startup)
(defvar user-emacs-directory "~/.emacs.d/"
"Directory beneath which additional per-user Emacs-specific files are placed.")
;; emacs.c C variable (nil outside the dump/pdump build path)
(defvar dump-mode nil
"Non-nil means Emacs is dumping or bootstrapping.")
;; files.el
(defcustom user-emacs-directory-warning t
"Non-nil means warn if unable to access or create `user-emacs-directory'."
:type 'boolean
:group 'initialization
:version "24.4")
;; files.el: faithful port of `locate-user-emacs-file'.
(defun locate-user-emacs-file (new-name &optional old-name)
"Return an absolute per-user Emacs-specific file name.
If NEW-NAME exists in `user-emacs-directory', return it.
Else if OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
Else return NEW-NAME in `user-emacs-directory', creating the
directory if it does not exist."
(convert-standard-filename
(let* ((home (concat "~" (or init-file-user "")))
(at-home (and old-name (expand-file-name old-name home)))
(bestname (abbreviate-file-name
(expand-file-name new-name user-emacs-directory))))
(if (and at-home (not (file-readable-p bestname))
(file-readable-p at-home))
at-home
;; Make sure `user-emacs-directory' exists,
;; unless we're in batch mode or dumping Emacs.
(or noninteractive
dump-mode
(let (errtype)
(if (file-directory-p user-emacs-directory)
(or (file-accessible-directory-p user-emacs-directory)
(setq errtype "access"))
;; We don't want to create HOME if it doesn't exist.
(if (and (not (file-exists-p "~"))
(string-prefix-p
(expand-file-name "~")
(expand-file-name user-emacs-directory)))
(setq errtype "create")
;; Create `user-emacs-directory'.
(with-file-modes ?\700
(condition-case nil
(make-directory user-emacs-directory t)
(error (setq errtype "create"))))))
(when (and errtype
user-emacs-directory-warning
(not (get 'user-emacs-directory-warning 'this-session)))
;; Warn only once per Emacs session.
(put 'user-emacs-directory-warning 'this-session t)
(display-warning 'initialization
(format "\
Unable to %s `user-emacs-directory' (%s).
Any data that would normally be written there may be lost!
If you never want to see this message again,
customize the variable `user-emacs-directory-warning'."
errtype user-emacs-directory)))))
bestname))))
;;; ---- keymaps (data subsystem: keymap.c primitives + keymap.el string API) ----
;; A keymap is a list whose car is the symbol `keymap'. Bindings follow as
;; (EVENT . DEFINITION) conses; a bare `keymap' element in the tail begins the
;; PARENT keymap (shared structure). These are faithful ports of the DOCUMENTED
;; behavior of the C primitives in keymap.c, verified value-for-value against the
;; Emacs 30.2 binary. make-keymap (full char-table keymap) is NOT implemented:
;; it needs a char-table Value type elisprs lacks -- see report. command-remapping
;; returns nil (correct with no active global/local remap keymaps).
;; With no buffer-local/global remap keymaps in effect, no command is remapped.
(defun make-sparse-keymap (&optional string)
"Construct and return a new sparse keymap.
Optional STRING is a menu name for the keymap."
(if string (list 'keymap string) (list 'keymap)))
(defun keymapp (object)
"Return t if OBJECT is a keymap.
A keymap is a list (keymap . ALIST), or a symbol whose function
definition is itself a keymap."
(if (symbolp object)
(and object (keymapp (symbol-function object)))
(and (consp object) (eq (car object) 'keymap))))
;; Resolve a keymap that may be a symbol standing for a keymap (a prefix command).
(defun keymap--get (object)
(if (symbolp object) (symbol-function object) object))
(defun make-composed-keymap (maps &optional parent)
"Construct a new keymap composed of MAPS and inheriting from PARENT.
MAPS can be a single keymap or a list of keymaps. PARENT, if non-nil,
should be a keymap."
(cons 'keymap (append (if (keymapp maps) (list maps) maps) parent)))
;; Return the (EVENT . DEF) cons in KM's own bindings (before the parent), or nil.
(defun keymap--own-binding (km event)
(let ((tail (cdr km)) (res nil))
(while (and (consp tail) (not res))
(let ((el (car tail)))
(cond ((eq el 'keymap) (setq tail nil))
((and (consp el) (equal (car el) event)) (setq res el))
(t (setq tail (cdr tail))))))
res))
;; Replace or prepend a binding for EVENT in KM's own bindings.
(defun keymap--set-binding (km event def)
(let ((cell (keymap--own-binding km event)))
(if cell
(setcdr cell def)
(setcdr km (cons (cons event def) (cdr km))))))
;; Delete EVENT's own binding from KM.
(defun keymap--remove-binding (km event)
(let ((cell (keymap--own-binding km event)))
(when cell (setcdr km (delq cell (cdr km))))))
;; Expand meta-modified integer events (bit 2^27) into ESC (27) + base char,
;; matching how keymap.c stores/looks up meta bindings. Symbol events (e.g.
;; `M-left') are stored verbatim and are not expanded.
(defun keymap--expand-meta (events)
(let ((res nil))
(dolist (e events)
(if (and (integerp e) (/= 0 (logand e (ash 1 27))))
(progn (push 27 res) (push (logand e (lognot (ash 1 27))) res))
(push e res)))
(nreverse res)))
;; `Fdefine_key' / `Flookup_key' read a unibyte string key's characters 128-255
;; as meta characters (`c ^= 0200 | meta_modifier'). Strings here carry no
;; unibyte flag, so a string whose characters all fit in a byte and include one
;; above 127 is read that way.
(defun keymap--key-events (key)
(if (and (stringp key)
(let ((hi nil) (ok t))
(mapc (lambda (c)
(cond ((> c 255) (setq ok nil))
((> c 127) (setq hi t))))
key)
(and ok hi)))
(mapcar (lambda (c)
(if (> c 127) (logxor c (logior #o200 #x8000000)) c))
key)
(append key nil)))
(defun define-key (keymap key def &optional remove)
"In KEYMAP, define key sequence KEY as DEF.
KEY is a string or vector of events. DEF is anything that can be a
key definition (a command symbol, a keymap for a prefix key, nil, etc.).
If optional REMOVE is non-nil, remove the binding instead.
Returns DEF."
(let ((events (keymap--expand-meta (keymap--key-events key)))
(km keymap)
(consumed nil))
(while (cdr events)
(setq consumed (cons (car events) consumed))
(let* ((raw (cdr (or (keymap--own-binding km (car events))
(cons nil nil))))
(sub (keymap--get raw)))
(cond
((keymapp sub) (setq km (keymap--get sub)))
;; A bound non-prefix key cannot start a longer sequence.
(raw
(error "Key sequence %s starts with non-prefix key %s"
(key-description key)
(key-description (vconcat (reverse consumed)))))
(t
(let ((new (make-sparse-keymap)))
(keymap--set-binding km (car events) new)
(setq km new)))))
(setq events (cdr events)))
(if remove
(keymap--remove-binding km (car events))
(keymap--set-binding km (car events) def))
def))
;; Look up EVENT in KM's own bindings, then (transparently) its parent chain.
;; ACCEPT-DEFAULT recognizes a (t . DEF) default binding.
(defun lookup-key--event (km event accept-default)
(let ((tail (cdr km)) (res nil) (deflt nil) (done nil))
(while (and (consp tail) (not done))
(let ((el (car tail)))
(cond
((eq el 'keymap)
(setq res (lookup-key--event tail event accept-default) done t))
((and (consp el) (eq (car el) 'keymap))
(let ((r (lookup-key--event el event accept-default)))
(when r (setq res r done t))))
((and (consp el) (equal (car el) event))
(setq res (cdr el) done t))
((and (consp el) (eq (car el) t))
(setq deflt (cdr el)))))
(unless done (setq tail (cdr tail))))
(or res (and accept-default deflt))))
(defun lookup-key (keymap key &optional accept-default)
"Look up key sequence KEY in KEYMAP; return the definition.
KEY is a string or vector. Returns nil if undefined. If KEY is longer
than needed to reach a non-prefix binding, returns the number of events
at the front of KEY that were used. ACCEPT-DEFAULT recognizes default
(t) bindings."
(let ((events (keymap--expand-meta (keymap--key-events key)))
(km (keymap--get keymap)) (i 0) (res nil) (done nil))
(if (null events)
keymap
(while (and events (not done))
(setq res (lookup-key--event km (car events) accept-default))
(setq events (cdr events))
(setq i (1+ i))
(cond
((null events) (setq done t))
((keymapp res) (setq km (keymap--get res)))
(t (setq res i done t))))
res)))
(defun keymap-parent (keymap)
"Return the parent keymap of KEYMAP, or nil if it has none."
(let ((tail (cdr keymap)) (res nil))
(while (and (consp tail) (not res))
(if (eq (car tail) 'keymap)
(setq res tail)
(setq tail (cdr tail))))
res))
(defun set-keymap-parent (keymap parent)
"Modify KEYMAP to set its parent keymap to PARENT. Return PARENT."
(let ((prev keymap) (tail (cdr keymap)))
(while (and (consp tail) (not (eq (car tail) 'keymap)))
(setq prev tail tail (cdr tail)))
(setcdr prev parent)
parent))
(defun define-prefix-command (command &optional mapvar _name)
"Define COMMAND as a prefix command with a new sparse keymap.
Set COMMAND's function cell to the keymap, and its value cell (or MAPVAR
if given and not t) to the same keymap. Return COMMAND."
(let ((map (make-sparse-keymap)))
(fset command map)
(if (and mapvar (not (eq mapvar t)))
(set mapvar map)
(set command map))
command))
(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."
(define-key map [remap self-insert-command] #'undefined)
(or nodigits
(let (loop)
(define-key map "-" #'negative-argument)
(setq loop ?0)
(while (<= loop ?9)
(define-key map (char-to-string loop) #'digit-argument)
(setq loop (1+ loop))))))
;; ---- keymap.el: the string-based key API (faithful ports) ----
(defun key-parse (keys)
"Convert KEYS to the internal Emacs key representation.
KEYS should be a string describing a key sequence in the format
returned by \\[describe-key] (`describe-key')."
(save-match-data
(let ((case-fold-search nil)
(len (length keys))
(pos 0)
(res []))
(while (and (< pos len)
(string-match "[^ \t\n\f]+" keys pos))
(let* ((word-beg (match-beginning 0))
(word-end (match-end 0))
(word (substring keys word-beg len))
(times 1)
key)
(if (string-match "\\`<[^ <>\t\n\f][^>\t\n\f]*>" word)
(setq word (match-string 0 word)
pos (+ word-beg (match-end 0)))
(setq word (substring keys word-beg word-end)
pos word-end))
(when (string-match "\\([0-9]+\\)\\*." word)
(setq times (string-to-number (substring word 0 (match-end 1))))
(setq word (substring word (1+ (match-end 1)))))
(cond ((string-match "^<<.+>>$" word)
(setq key (vconcat (if (eq (key-binding [?\M-x])
'execute-extended-command)
[?\M-x]
(or (car (where-is-internal
'execute-extended-command))
[?\M-x]))
(substring word 2 -2) "\r")))
((and (string-match "^\\(\\([ACHMsS]-\\)*\\)<\\(.+\\)>$" word)
(progn
(setq word (concat (match-string 1 word)
(match-string 3 word)))
(not (string-match
"\\<\\(NUL\\|RET\\|LFD\\|TAB\\|ESC\\|SPC\\|DEL\\)$"
word))))
(setq key (list (intern word))))
((or (equal word "REM") (string-match "^;;" word))
(setq pos (string-match "$" keys pos)))
(t
(let ((orig-word word) (prefix 0) (bits 0))
(while (string-match "^[ACHMsS]-." word)
(setq bits (+ bits
(cdr
(assq (aref word 0)
'((?A . ?\A-\0) (?C . ?\C-\0)
(?H . ?\H-\0) (?M . ?\M-\0)
(?s . ?\s-\0) (?S . ?\S-\0))))))
(setq prefix (+ prefix 2))
(setq word (substring word 2)))
(when (string-match "^\\^.$" word)
(setq bits (+ bits ?\C-\0))
(setq prefix (1+ prefix))
(setq word (substring word 1)))
(let ((found (assoc word '(("NUL" . "\0") ("RET" . "\r")
("LFD" . "\n") ("TAB" . "\t")
("ESC" . "\e") ("SPC" . " ")
("DEL" . "\177")))))
(when found (setq word (cdr found))))
(when (string-match "^\\\\[0-7]+$" word)
(let ((n 0))
(dolist (ch (cdr (string-to-list word)))
(setq n (+ (* n 8) ch -48)))
(setq word (vector n))))
(cond ((= bits 0)
(setq key word))
((and (= bits ?\M-\0) (stringp word)
(string-match "^-?[0-9]+$" word))
(setq key (mapcar (lambda (x) (+ x bits))
(append word nil))))
((/= (length word) 1)
(error "%s must prefix a single character, not %s"
(substring orig-word 0 prefix) word))
((and (/= (logand bits ?\C-\0) 0) (stringp word)
(string-match "[@-_a-z]" word))
(setq key (list (+ bits (- ?\C-\0)
(logand (aref word 0) 31)))))
(t
(setq key (list (+ bits (aref word 0)))))))))
(when key
(dolist (_ (number-sequence 1 times))
(setq res (vconcat res key))))))
res)))
(defun key-valid-p (keys)
"Return non-nil if KEYS, a string, is a valid key sequence.
KEYS should be a string consisting of one or more key strokes, with a
single space character separating one key stroke from another."
(let ((case-fold-search nil))
(and
(stringp keys)
(string-match-p "\\`[^ ]+\\( [^ ]+\\)*\\'" keys)
(save-match-data
(catch 'exit
(let ((prefixes
"\\(A-\\)?\\(C-\\)?\\(H-\\)?\\(M-\\)?\\(S-\\)?\\(s-\\)?"))
(dolist (key (split-string keys " "))
(when (string-match (concat "\\`" prefixes) key)
(setq key (substring key (match-end 0))))
(unless (or (and (= (length key) 1)
(not (< (aref key 0) ?\s))
(or (multibyte-string-p key)
(not (<= 127 (aref key 0) 255))))
(and (string-match-p "\\`<[-_A-Za-z0-9]+>\\'" key)
(= (progn
(string-match
(concat "\\`<" prefixes) key)
(match-end 0))
1))
(string-match-p
"\\`\\(NUL\\|RET\\|TAB\\|LFD\\|ESC\\|SPC\\|DEL\\)\\'"
key))
(throw 'exit nil)))
t))))))
(defun keymap--check (key)
"Signal an error if KEY doesn't have a valid syntax."
(unless (key-valid-p key)
(error "%S is not a valid key definition; see `key-valid-p'" key)))
(defun keymap-set (keymap key definition)
"Set KEY to DEFINITION in KEYMAP.
KEY is a string that satisfies `key-valid-p'."
(keymap--check key)
(when (stringp definition)
(keymap--check definition)
(setq definition (key-parse definition)))
(define-key keymap (key-parse key) definition))
(defun keymap-unset (keymap key &optional remove)
"Remove KEY from KEYMAP.
If REMOVE is non-nil, remove the binding instead of setting it to nil."
(keymap--check key)
(define-key keymap (key-parse key) nil remove))
(defun keymap-lookup (keymap key &optional accept-default no-remap position)
"Return the binding for command KEY in KEYMAP.
KEY is a string that satisfies `key-valid-p'. KEYMAP must be non-nil
here: looking up in the current buffer-local/global keymaps (KEYMAP nil)
needs live buffer state that elisprs does not provide."
(keymap--check key)
(when (and keymap position)
(error "Can't pass in both keymap and position"))
(if keymap
(let ((value (lookup-key keymap (key-parse key) accept-default)))
(if (and (not no-remap)
(symbolp value))
(or (command-remapping value) value)
value))
(error "keymap-lookup with no keymap needs buffer-local current keymaps (unsupported)")))
(defun define-keymap (&rest definitions)
"Create a new keymap and define KEY/DEFINITION pairs as key bindings.
Return the new keymap. Options may be given as keywords before the
pairs: :full :suppress :parent :keymap :name :prefix."
(declare (indent defun))
(let (full suppress parent name prefix keymap)
(while (and definitions
(keywordp (car definitions))
(not (eq (car definitions) :menu)))
(let ((keyword (pop definitions)))
(unless definitions
(error "Missing keyword value for %s" keyword))
(let ((value (pop definitions)))
(pcase keyword
(:full (setq full value))
(:keymap (setq keymap value))
(:parent (setq parent value))
(:suppress (setq suppress value))
(:name (setq name value))
(:prefix (setq prefix value))
(_ (error "Invalid keyword: %s" keyword))))))
(when (and prefix
(or full parent suppress keymap))
(error "A prefix keymap can't be defined with :full/:parent/:suppress/:keymap keywords"))
(when (and keymap full)
(error "Invalid combination: :keymap with :full"))
(let ((keymap (cond
(keymap keymap)
(prefix (define-prefix-command prefix nil name))
(full (make-keymap name))
(t (make-sparse-keymap name))))
seen-keys)
(when suppress
(suppress-keymap keymap (eq suppress 'nodigits)))
(when parent
(set-keymap-parent keymap parent))
(while definitions
(let ((key (pop definitions)))
(unless definitions
(error "Uneven number of key/definition pairs"))
(let ((def (pop definitions)))
(if (eq key :menu)
(easy-menu-define nil keymap "" def)
(when (member key seen-keys)
(message "Duplicate definition for key: %S %s" key keymap))
(push key seen-keys)
(keymap-set keymap key def)))))
keymap)))
(defmacro defvar-keymap (variable-name &rest defs)
"Define VARIABLE-NAME as a variable with a keymap definition.
See `define-keymap' for an explanation of the keywords and KEY/DEFINITION.
Also accepts a `:doc' keyword for the variable documentation string, and
a `:repeat' keyword controlling `repeat-mode' behavior."
(declare (indent 1))
(let ((opts nil)
doc repeat props)
(while (and defs
(keywordp (car defs))
(not (eq (car defs) :menu)))
(let ((keyword (pop defs)))
(unless defs
(error "Uneven number of keywords"))
(cond
((eq keyword :doc) (setq doc (pop defs)))
((eq keyword :repeat) (setq repeat (pop defs)))
(t (push keyword opts)
(push (pop defs) opts)))))
(unless (zerop (% (length defs) 2))
(error "Uneven number of key/definition pairs: %s" defs))
(let ((defs defs)
key seen-keys)
(while defs
(setq key (pop defs))
(pop defs)
(when (not (eq key :menu))
(if (member key seen-keys)
(error "Duplicate definition for key '%s' in keymap '%s'"
key variable-name)
(push key seen-keys)))))
(when repeat
(let ((defs defs)
def)
(dolist (def (plist-get repeat :enter))
(push (list 'put (list 'quote def) ''repeat-map (list 'quote variable-name)) props))
(while defs
(pop defs)
(setq def (pop defs))
(when (and (memq (car def) '(function quote))
(not (memq (cadr def) (plist-get repeat :exit))))
(push (list 'put def ''repeat-map (list 'quote variable-name)) props)))
(dolist (def (plist-get repeat :hints))
(push (list 'put (list 'quote (car def)) ''repeat-hint (list 'quote (cdr def))) props))))
(let ((defvar-form
(append (list 'defvar variable-name
(append (list 'define-keymap) (nreverse opts) defs))
(and doc (list doc)))))
(if props
(append (list 'progn defvar-form) (nreverse props))
defvar-form))))
;; button-buffer-map (button.el) and special-mode-map (simple.el) are pure
;; keymap data that tabulated-list-mode-map inherits from via :parent. Ported
;; from their upstream defvar-keymap forms.
(defvar-keymap button-buffer-map
:doc "Keymap useful for buffers containing buttons.
Mode-specific keymaps may want to use this as their parent keymap."
"TAB" #'forward-button
"ESC TAB" #'backward-button
"<backtab>" #'backward-button)
;;; ---- button types (button.el) ----
;; Faithful port of button.el's button-type system (define-button-type and the
;; button-type-{put,get,subtype-p} accessors). Button types hold default
;; properties for buttons; each type NAME stores them on a separate uninterned
;; `-button' symbol (its `button-category-symbol'), so `category' text/overlay
;; properties can point at it without name clashes. Overlay/text-property
;; button placement (make-button, insert-button, push-button navigation) is not
;; modeled here — only the type registry, which is what init files exercise at
;; load time. Value-for-value against Emacs 30.2 button.el.
;; `(defface button ...)' is in src/lisp/faces-31.el, which makes every face
;; batch Emacs has in its face-id order.
(defvar-keymap button-map
:doc "Keymap used by buttons."
:parent button-buffer-map
"RET" #'push-button
"<mouse-2>" #'push-button
"<follow-link>" 'mouse-face
;; FIXME: You'd think that for keymaps coming from text-properties on the
;; mode-line or header-line, the `mode-line' or `header-line' prefix
;; shouldn't be necessary!
"<mode-line> <mouse-2>" #'push-button
"<header-line> <mouse-2>" #'push-button
;; `push-button' will automatically dispatch to
;; `touch-screen-track-tap'.
"<mode-line> <touchscreen-down>" #'push-button
"<header-line> <touchscreen-down>" #'push-button
"<touchscreen-down>" #'push-button)
;; `button-mode' (the TAB-navigation minor mode) is intentionally omitted: it is
;; button UI, not part of the type registry, and the prelude already omits it
;; while keeping button-buffer-map. The type machinery below is self-contained.
;; Default properties for buttons.
(put 'default-button 'face 'button)
(put 'default-button 'mouse-face 'highlight)
(put 'default-button 'keymap button-map)
(put 'default-button 'type 'button)
;; `action' may be either a function to call, or a marker to go to.
(put 'default-button 'action #'ignore)
(put 'default-button 'help-echo (purecopy "mouse-2, RET: Push this button"))
;; Make overlay buttons go away if their underlying text is deleted.
(put 'default-button 'evaporate t)
;; Prevent insertions adjacent to text-property buttons from
;; inheriting their properties.
(put 'default-button 'rear-nonsticky t)
;; A `category-symbol' property for the default button type.
(put 'button 'button-category-symbol 'default-button)
;; [this is an internal function]
(defsubst button-category-symbol (type)
"Return the symbol used by `button-type' TYPE to store properties.
Buttons inherit them by setting their `category' property to that symbol."
(or (get type 'button-category-symbol)
(error "Unknown button type `%s'" type)))
(defun define-button-type (name &rest properties)
"Define a `button type' called NAME (a symbol).
The remaining PROPERTIES arguments form a plist of PROPERTY VALUE
pairs, specifying properties to use as defaults for buttons with
this type (a button's type may be set by giving it a `type'
property when creating the button, using the :type keyword
argument).
In addition, the keyword argument :supertype may be used to specify a
`button-type' from which NAME inherits its default property values
\(however, the inheritance happens only when NAME is defined; subsequent
changes to a supertype are not reflected in its subtypes)."
(declare (indent defun))
(let ((catsym (make-symbol (concat (symbol-name name) "-button")))
(super-catsym
(button-category-symbol
(or (plist-get properties 'supertype)
(plist-get properties :supertype)
'button))))
;; Provide a link so that it's easy to find the real symbol.
(put name 'button-category-symbol catsym)
;; Initialize NAME's properties using the global defaults.
(let ((default-props (symbol-plist super-catsym)))
(while default-props
(put catsym (pop default-props) (pop default-props))))
;; Add NAME as the `type' property, which will then be returned as
;; the type property of individual buttons.
(put catsym 'type name)
;; Add the properties in PROPERTIES to the real symbol.
(while properties
(let ((prop (pop properties)))
(when (eq prop :supertype)
(setq prop 'supertype))
(put catsym prop (pop properties))))
;; Make sure there's a `supertype' property.
(unless (get catsym 'supertype)
(put catsym 'supertype 'button))
name))
(defun button-type-put (type prop val)
"Set the `button-type' TYPE's PROP property to VAL."
(put (button-category-symbol type) prop val))
(defun button-type-get (type prop)
"Get the property of `button-type' TYPE named PROP."
(get (button-category-symbol type) prop))
(defun button-type-subtype-p (type supertype)
"Return non-nil if `button-type' TYPE is a subtype of SUPERTYPE."
(or (eq type supertype)
(and type
(button-type-subtype-p (button-type-get type 'supertype)
supertype))))
;; Mark `button' as provided so `(require 'button)' in init files no-ops onto
;; the preloaded type machinery instead of trying to open a file (button.el:672).
(provide 'button)
;;; ---- widget types (widget.el) ----
;; Faithful port of widget.el, the bootstrap half of the widget system that only
;; defines new widget types (everything else is autoloaded from wid-edit.el).
;; `define-widget' registers a type by storing (CLASS . ARGS) on the NAME
;; symbol's `widget-type' property and the doc string on `widget-documentation';
;; that registry is what init files touch at load time. The widget UI itself
;; (widget-create/widget-convert/widget-apply, the wid-edit.el layer) is not
;; modeled here. Value-for-value against Emacs 30.2 widget.el.
;; `define-widget-keywords' is a dummy kept only so external libraries that still
;; call it don't error; it expands to nil (obsolete since 27.1).
(defmacro define-widget-keywords (&rest _keys)
(declare (obsolete nil "27.1") (indent defun))
nil)
(defun define-widget (name class doc &rest args)
"Define a new widget type named NAME from CLASS.
NAME and CLASS should both be symbols, CLASS should be one of the
existing widget types, or nil to create the widget from scratch.
After the new widget has been defined, the following two calls will
create identical widgets:
* (widget-create NAME)
* (apply #\\='widget-create CLASS ARGS)
The third argument DOC is a documentation string for the widget."
(declare (doc-string 3) (indent defun))
;;
(unless (or (null doc) (stringp doc))
(error "Widget documentation must be nil or a string"))
(put name 'widget-type (cons class args))
(put name 'widget-documentation (purecopy doc))
name)
(define-obsolete-function-alias 'widget-plist-member #'plist-member "26.1")
;; Mark `widget' as provided so `(require 'widget)' no-ops onto the preloaded
;; type registry instead of trying to open a file (widget.el:139).
(provide 'widget)
(defvar-keymap special-mode-map
:suppress t
"q" #'quit-window
"SPC" #'scroll-up-command
"S-SPC" #'scroll-down-command
"DEL" #'scroll-down-command
"?" #'describe-mode
"h" #'describe-mode
">" #'end-of-buffer
"<" #'beginning-of-buffer
"g" #'revert-buffer)
;;; ---- major/minor mode machinery (derived.el, easy-mmode.el, subr.el) ----
;; Real text editing (point/insert, multiple named live buffers, narrowing,
;; marker-based save-excursion, first-class markers, and string/buffer text
;; properties) is modeled by the text-editing subsystem (builtins.rs). Overlays
;; and redisplay are not. Syntax tables and abbrev tables are separate subsystems:
;; the constructors below
;; are placeholders sufficient for `define-derived-mode' to expand and load; they
;; do not model syntax/abbrev semantics.
;; `interactive' is a special form the compiler lowers to nil (eval.c
;; `Finteractive' returns nil without evaluating its arguments); keeping it a
;; form rather than a macro leaves the spec in the closure, where
;; `make-interpreted-closure' stores it.
;; `current-buffer'/`set-buffer'/`get-buffer-create' and the rest of the buffer
;; registry are C-level primitives (see builtins.rs). Buffers are not associated
;; with files in this model, so `buffer-file-name' is always nil.
(defun buffer-file-name (&optional _buffer) nil)
;;; ---- char-tables (public make-char-table over the make-char-table--new subr) ----
;; make-char-table reads SUBTYPE's `char-table-extra-slots' property (0..10) to
;; size the extra slots, then calls the low-level allocator. Faithful to
;; chartab.c `Fmake_char_table'.
(defun make-char-table (subtype &optional init)
"Return a newly created char-table, with purpose SUBTYPE.
Each element is initialized to INIT, which defaults to nil.
The property `char-table-extra-slots' of SUBTYPE controls the number of
extra slots to reserve in this char-table. This slot number is an
integer between 0 and 10, or nil, meaning 0."
(let ((n (get subtype 'char-table-extra-slots)))
;; chartab.c rejects an out-of-range slot count with `args_out_of_range',
;; naming the property value and INIT -- not with an `error' of its own.
(setq n (cond ((null n) 0)
((and (integerp n) (>= n 0) (<= n 10)) n)
(t (signal 'args-out-of-range (list n init)))))
(make-char-table--new subtype init n)))
;;; ---- syntax tables (syntax.c documented behavior, over char-tables) ----
;; A syntax table is a char-table with subtype `syntax-table'. Each element is
;; a cons (SYNTAX-CODE . MATCHING-CHAR) where SYNTAX-CODE encodes the syntax
;; class in its low 16 bits plus flag bits; MATCHING-CHAR is the paired paren
;; (nil if none). Verified value-for-value against the Emacs 30.2 binary.
;; syntax_code_spec (syntax.c): class index -> designator character.
(defconst --syntax-code-spec-- " .w_()'\"$\\/<>@!|"
"Char at index N is the designator for syntax class N (see `string-to-syntax').")
(defun syntax-class-to-char (syntax-class)
"Return the designator character for SYNTAX-CLASS (an integer 0..15)."
(aref --syntax-code-spec-- syntax-class))
;; The flag descriptor characters and the bit each sets in the syntax code.
;; `c' (bit 23) is the third comment style, added for modes that need a third
;; two-character comment delimiter; it is in `Fstring_to_syntax' alongside the
;; other seven and was the only one missing here.
(defconst --syntax-flag-alist--
'((?1 . 16) (?2 . 17) (?3 . 18) (?4 . 19) (?p . 20) (?b . 21) (?n . 22)
(?c . 23))
"Maps a `modify-syntax-entry' flag char to the bit it sets in the syntax code.")
;; syntax.c `Vsyntax_code_object': one shared `(CODE)' cons per bare class, so
;; that two descriptors naming the same class with no match char and no flags
;; are `eq'. `init_syntax_once' builds it and `Fstring_to_syntax' returns from
;; it whenever `val < Smax' and MATCH is nil; freshly consing instead makes
;; `(eq (string-to-syntax "w") (string-to-syntax "w"))' nil where Emacs says t.
(defconst --syntax-code-object--
(let ((v (make-vector 16 nil)) (i 0))
(while (< i 16) (aset v i (list i)) (setq i (1+ i)))
v)
"Vector of the shared (CODE) conses, indexed by syntax class.")
(defun string-to-syntax (descriptor)
"Convert syntax DESCRIPTOR string into the internal (CODE . MATCH) form.
DESCRIPTOR's first char names the class, the second the matching char
\(a space or missing means none), and any remaining chars are flags."
(unless (stringp descriptor)
(signal 'wrong-type-argument (list 'stringp descriptor)))
;; `Fstring_to_syntax' indexes `syntax_spec_code' with the first BYTE, and the
;; empty string's is the terminating NUL -- which is why Emacs reports the
;; letter as an unprintable character rather than rejecting the string.
(let* ((c (if (= (length descriptor) 0) 0 (aref descriptor 0)))
;; `-' is an alias for whitespace; otherwise look C up in the spec.
(class (if (eq c ?-) 0
(let ((i 0) (found nil) (len (length --syntax-code-spec--)))
(while (and (not found) (< i len))
(when (eq (aref --syntax-code-spec-- i) c) (setq found i))
(setq i (1+ i)))
(or found
(error "Invalid syntax description letter: %c" c))))))
;; Sinherit ("@") means "use the standard table here", which is spelled as a
;; nil descriptor -- not as class 13.
(if (= class 13)
nil
(let ((match (and (> (length descriptor) 1)
(let ((m (aref descriptor 1)))
(unless (eq m ?\s) m))))
(code class)
(i 2) (len (length descriptor)))
(while (< i len)
(let ((bit (cdr (assq (aref descriptor i) --syntax-flag-alist--))))
(when bit (setq code (logior code (ash 1 bit)))))
(setq i (1+ i)))
(if (and (< code 16) (null match))
(aref --syntax-code-object-- code)
(cons code match))))))
(defun syntax-class (syntax)
"Return the syntax class part of the syntax code SYNTAX (a (CODE . MATCH) cons).
Return nil if SYNTAX is nil."
(and syntax (logand (car syntax) 65535)))
;; The standard syntax table, built once to mirror syntax.c `init_syntax_once'
;; plus the Latin-1 block of lisp/international/characters.el.
;;
;; ASCII entries reproduce the binary's `standard-syntax-table' exactly. So does
;; the Latin-1 supplement (U+0080-U+00FF): syntax.c defaults every character at
;; or above U+0080 to word, characters.el then gives the Latin-1 punctuation and
;; symbols `.'/`_' classes, and the two lists below are that result, verified
;; character by character against Emacs 30.2. It is not a rule anyone can
;; re-derive from Unicode's general categories -- U+00A5 YEN SIGN keeps word
;; syntax while U+00A2..U+00A4 (the same Sc category) do not, and U+00B2/B3/B9
;; keep it while U+00BC..U+00BE (the same No category) do not -- so it is carried
;; as data. Above U+00FF the same classification is carried by the (LO HI CODE) list below.
(defvar --standard-syntax-table-- nil
"The standard syntax table (see `standard-syntax-table').")
(defun --init-standard-syntax-table-- ()
(let* ((word (string-to-syntax "w"))
(space (string-to-syntax " "))
(punct (string-to-syntax "."))
(symbol (string-to-syntax "_"))
;; syntax.c `init_syntax_once': whitespace is the table's initial
;; value and its default; everything else is set over it.
(tbl (make-char-table 'syntax-table space)))
;; Word: letters, digits, `$' and `%', and every non-ASCII character.
(set-char-table-range tbl '(?a . ?z) word)
(set-char-table-range tbl '(?A . ?Z) word)
(set-char-table-range tbl '(?0 . ?9) word)
(aset tbl ?$ word)
(aset tbl ?% word)
(set-char-table-range tbl '(128 . #x3FFFFF) word)
;; Control chars 0..31 and DEL are PUNCTUATION here, and `?\n'/`?\r' are
;; whitespace -- syntax.c `init_syntax_once' sets exactly that, and
;; emacs -Q --batch --eval '(with-syntax-table (standard-syntax-table) \
;; (prin1 (list (char-syntax 1) (char-syntax ?\n) \
;; (char-syntax ?\r) (char-syntax 127))))'
;; => (46 32 32 46)
;; confirms it on 30.2. The `_'/`>' classes those characters are usually
;; SEEN with -- `(char-syntax 1)' => 95, `(char-syntax ?\n)' => 62 -- come
;; from the *buffer's* table, not this one: `emacs -Q --batch' starts in
;; `*scratch*' under `lisp-interaction-mode', whose table reclassifies every
;; non-alphanumeric ASCII. That is installed below as the initial buffer's
;; table; putting it here instead would make `(standard-syntax-table)' wrong
;; for all 31 of those characters.
(set-char-table-range tbl '(0 . 31) punct)
(dolist (c '(?\t ?\n ?\f ?\r ?\s 160)) (aset tbl c space))
(aset tbl 127 punct)
;; ASCII punctuation.
(dolist (c '(?! ?# ?' ?, ?. ?: ?\; ?? ?@ ?^ ?` ?~)) (aset tbl c punct))
;; ASCII symbol constituents.
(dolist (c '(?& ?* ?+ ?- ?/ ?< ?= ?> ?_ ?|)) (aset tbl c symbol))
;; Latin-1 supplement: ¡ § « » ¿ are punctuation, ...
(dolist (c '(161 167 171 187 191)) (aset tbl c punct))
;; ... and the currency/modifier/math/other symbols are symbol constituents.
(dolist (c '(162 163 164 166 168 169 170 172 173 174 175 176 177
180 182 183 184 186 188 189 190 215 247))
(aset tbl c symbol))
;; Above U+00FF: characters.el's classification of the rest of the Unicode
;; space, carried as data for the same reason as the Latin-1 lists (it
;; follows the general-category tables, not a rule). Each entry is
;; (LO HI CODE [MATCH]) over the word default; CODE is the syntax code
;; (0 whitespace, 1 punctuation, 3 symbol, 4/5 open/close with MATCH).
;; Dumped from `(standard-syntax-table)' of GNU Emacs 31.1.
(dolist (r '(
(#x2C7 #x2C7 3) (#x2C9 #x2C9 3) (#x2D0 #x2D0 3) (#x2D8 #x2DB 3)
(#x2DD #x2DD 3) (#x384 #x385 3) (#x5BE #x5BE 1) (#x5C0 #x5C0 1)
(#x5C3 #x5C3 1) (#x5C6 #x5C6 1) (#x5F3 #x5F4 1) (#xE2F #xE2F 3)
(#xE3F #xE3F 3) (#xE46 #xE46 3) (#xE4F #xE4F 3) (#xE5A #xE5B 3)
(#xEAF #xEAF 3) (#xEC6 #xEC6 3) (#xF00 #xF0B 1) (#xF0D #xF18 1)
(#xF1A #xF1F 1) (#xF34 #xF34 1) (#xF36 #xF36 1) (#xF38 #xF3F 1)
(#xF7F #xF7F 1) (#xF85 #xF85 1) (#xFBE #xFCF 1) (#x1361 #x1368 1)
(#x1800 #x180A 1) (#x2000 #x200B 0) (#x200C #x2027 1) (#x202F #x202F 0)
(#x2030 #x2038 1) (#x2039 #x203A 3) (#x203B #x2043 1) (#x2044 #x2044 3)
(#x2045 #x2045 4 #x2046) (#x2046 #x2046 5 #x2045) (#x2047 #x2051 1)
(#x2052 #x2052 3) (#x2053 #x205E 1) (#x205F #x205F 0)
(#x207D #x207D 4 #x207E) (#x207E #x207E 5 #x207D)
(#x208D #x208D 4 #x208E) (#x208E #x208E 5 #x208D) (#x20AC #x20AC 3)
(#x2103 #x2103 3) (#x2109 #x2109 3) (#x2116 #x2116 1) (#x2121 #x2122 3)
(#x2153 #x2154 3) (#x215B #x215E 3) (#x2190 #x2328 3)
(#x2329 #x2329 4 #x232A) (#x232A #x232A 5 #x2329) (#x232B #x23B3 3)
(#x23B4 #x23B4 4 #x23B5) (#x23B5 #x23B5 5 #x23B4) (#x23B6 #x244F 3)
(#x2460 #x246E 3) (#x2474 #x24B5 3) (#x2500 #x254B 3) (#x2592 #x2592 3)
(#x25A0 #x25A1 3) (#x25A3 #x25A9 3) (#x25B2 #x25B3 3) (#x25B6 #x25B7 3)
(#x25BC #x25BD 3) (#x25C0 #x25C1 3) (#x25C6 #x25C8 3) (#x25CB #x25CB 3)
(#x25CE #x25D1 3) (#x25EF #x25EF 3) (#x2605 #x2606 3) (#x260E #x260F 3)
(#x261C #x261C 3) (#x261E #x261E 3) (#x2640 #x2640 3) (#x2642 #x2642 3)
(#x2660 #x2661 3) (#x2663 #x2665 3) (#x2667 #x266A 3) (#x266C #x266D 3)
(#x266F #x266F 3) (#x2768 #x2768 4 #x2769) (#x2769 #x2769 5 #x2768)
(#x276A #x276A 4 #x276B) (#x276B #x276B 5 #x276A)
(#x276C #x276C 4 #x276D) (#x276D #x276D 5 #x276C)
(#x2770 #x2770 4 #x2771) (#x2771 #x2771 5 #x2770)
(#x2772 #x2772 4 #x2773) (#x2773 #x2773 5 #x2772)
(#x2774 #x2774 4 #x2775) (#x2775 #x2775 5 #x2774)
(#x27E6 #x27E6 4 #x27E7) (#x27E7 #x27E7 5 #x27E6)
(#x27E8 #x27E8 4 #x27E9) (#x27E9 #x27E9 5 #x27E8)
(#x27EA #x27EA 4 #x27EB) (#x27EB #x27EB 5 #x27EA)
(#x2983 #x2983 4 #x2984) (#x2984 #x2984 5 #x2983)
(#x2985 #x2985 4 #x2986) (#x2986 #x2986 5 #x2985)
(#x2987 #x2987 4 #x2988) (#x2988 #x2988 5 #x2987)
(#x2989 #x2989 4 #x298A) (#x298A #x298A 5 #x2989)
(#x298B #x298B 4 #x298C) (#x298C #x298C 5 #x298B)
(#x298D #x298D 4 #x298E) (#x298E #x298E 5 #x298D)
(#x298F #x298F 4 #x2990) (#x2990 #x2990 5 #x298F)
(#x2991 #x2991 4 #x2992) (#x2992 #x2992 5 #x2991)
(#x2993 #x2993 4 #x2994) (#x2994 #x2994 5 #x2993)
(#x2995 #x2995 4 #x2996) (#x2996 #x2996 5 #x2995)
(#x2997 #x2997 4 #x2998) (#x2998 #x2998 5 #x2997)
(#x29FC #x29FC 4 #x29FD) (#x29FD #x29FD 5 #x29FC) (#x2A00 #x2BFF 3)
(#x2E00 #x2E7F 1) (#x3000 #x3000 0) (#x3001 #x3003 1)
(#x3008 #x3008 4 #x3009) (#x3009 #x3009 5 #x3008)
(#x300A #x300A 4 #x300B) (#x300B #x300B 5 #x300A)
(#x300C #x300C 4 #x300D) (#x300D #x300D 5 #x300C)
(#x300E #x300E 4 #x300F) (#x300F #x300F 5 #x300E)
(#x3010 #x3010 4 #x3011) (#x3011 #x3011 5 #x3010) (#x3012 #x3013 3)
(#x3014 #x3014 4 #x3015) (#x3015 #x3015 5 #x3014)
(#x3016 #x3016 4 #x3017) (#x3017 #x3017 5 #x3016)
(#x3018 #x3018 4 #x3019) (#x3019 #x3019 5 #x3018)
(#x301A #x301A 4 #x301B) (#x301B #x301B 5 #x301A) (#x301C #x301C 3)
(#x30FB #x30FB 1) (#x3200 #x321C 3) (#x3220 #x3229 3) (#x3260 #x327B 3)
(#x327E #x327F 3) (#x3380 #x3384 3) (#x3388 #x33CA 3) (#x33CF #x33D0 3)
(#x33D3 #x33D3 3) (#x33D6 #x33D6 3) (#x33D8 #x33D8 3) (#x33DB #x33DD 3)
(#xAADB #xAADF 3) (#xFD3E #xFD3E 4 #xFD3F) (#xFD3F #xFD3F 5 #xFD3E)
(#xFE35 #xFE35 4 #xFE36) (#xFE36 #xFE36 5 #xFE35)
(#xFE37 #xFE37 4 #xFE38) (#xFE38 #xFE38 5 #xFE37)
(#xFE39 #xFE39 4 #xFE3A) (#xFE3A #xFE3A 5 #xFE39)
(#xFE3B #xFE3B 4 #xFE3C) (#xFE3C #xFE3C 5 #xFE3B)
(#xFE3D #xFE3D 4 #xFE3E) (#xFE3E #xFE3E 5 #xFE3D)
(#xFE3F #xFE3F 4 #xFE40) (#xFE40 #xFE40 5 #xFE3F)
(#xFE41 #xFE41 4 #xFE42) (#xFE42 #xFE42 5 #xFE41)
(#xFE43 #xFE43 4 #xFE44) (#xFE44 #xFE44 5 #xFE43)
(#xFE59 #xFE59 4 #xFE5A) (#xFE5A #xFE5A 5 #xFE59)
(#xFE5B #xFE5B 4 #xFE5C) (#xFE5C #xFE5C 5 #xFE5B)
(#xFE5D #xFE5D 4 #xFE5E) (#xFE5E #xFE5E 5 #xFE5D) (#xFF01 #xFF03 1)
(#xFF04 #xFF04 3) (#xFF05 #xFF07 1) (#xFF08 #xFF08 4 #xFF09)
(#xFF09 #xFF09 5 #xFF08) (#xFF0A #xFF0A 1) (#xFF0B #xFF0B 3)
(#xFF0C #xFF0F 1) (#xFF1A #xFF1B 1) (#xFF1C #xFF1E 3) (#xFF1F #xFF20 1)
(#xFF3B #xFF3B 4 #xFF3D) (#xFF3C #xFF3C 3) (#xFF3D #xFF3D 5 #xFF3B)
(#xFF3E #xFF40 3) (#xFF5B #xFF5B 4 #xFF5D) (#xFF5C #xFF5C 3)
(#xFF5D #xFF5D 5 #xFF5B) (#xFF5E #xFF5E 3) (#xFF5F #xFF5F 4 #xFF60)
(#xFF60 #xFF60 5 #xFF5F) (#xFF61 #xFF61 1) (#xFF62 #xFF62 4 #xFF63)
(#xFF63 #xFF63 5 #xFF62) (#xFF64 #xFF65 1) (#xFFE0 #xFFE3 3)
(#xFFE5 #xFFE5 3) (#x11660 #x1166C 1) (#x1FB00 #x1FBCA 3)
(#x1FBCB #x1FBFF 1) (#x110000 #x1100BB 3) (#x1102F0 #x11034D 3)
(#x140000 #x1400BB 3) (#x140292 #x1402EF 3) (#x148000 #x148119 3)
(#x279F94 #x27A04F 3) (#x27A16A #x27A225 3) (#x27A235 #x27A283 3)
(#x27A293 #x27A2D8 3)
))
(set-char-table-range
tbl (cons (nth 0 r) (nth 1 r))
(if (nth 3 r) (cons (nth 2 r) (nth 3 r)) (list (nth 2 r)))))
;; String quote and escape.
(aset tbl ?\" (string-to-syntax "\""))
(aset tbl ?\\ (string-to-syntax "\\"))
;; Balanced pairs: open matches close and vice versa.
(aset tbl ?\( (string-to-syntax "()"))
(aset tbl ?\) (string-to-syntax ")("))
(aset tbl ?\[ (string-to-syntax "(]"))
(aset tbl ?\] (string-to-syntax ")["))
(aset tbl ?\{ (string-to-syntax "(}"))
(aset tbl ?\} (string-to-syntax "){"))
tbl))
(setq --standard-syntax-table-- (--init-standard-syntax-table--))
(defun standard-syntax-table ()
"Return the standard syntax table.
This is the one used for new buffers."
--standard-syntax-table--)
;; The current buffer's syntax table is a buffer-local slot defaulting to the
;; standard table (Emacs keeps it in the buffer object; buffer-local var here).
(defvar-local --current-syntax-table-- nil
"The current buffer's syntax table (see `syntax-table').")
(defun syntax-table ()
"Return the current syntax table.
This is the one specified by the current buffer."
(or --current-syntax-table-- --standard-syntax-table--))
(defun set-syntax-table (table)
"Select TABLE as the syntax table for the current buffer."
(setq --current-syntax-table-- table)
table)
(defun copy-syntax-table (&optional table)
"Construct a new syntax table and return it.
It is a copy of TABLE, which defaults to the standard syntax table."
(let* ((src (or table --standard-syntax-table--))
(new (make-char-table 'syntax-table)))
(set-char-table-parent new (char-table-parent src))
;; Copy every set char over the char range. Non-ASCII beyond the modeled
;; range shares the source's word default via the range copy of ascii+.
(dotimes (c 128) (aset new c (char-table-range src c)))
(set-char-table-range new '(128 . #x3FFFFF) (char-table-range src 128))
new))
(defun make-syntax-table (&optional parent)
"Return a new syntax table.
Create a syntax table that inherits from PARENT (which defaults to the
standard syntax table)."
(let ((table (make-char-table 'syntax-table)))
(set-char-table-parent table (or parent --standard-syntax-table--))
table))
(defun syntax-table-p (object)
"Return t if OBJECT is a syntax table."
(and (char-table-p object) (eq (char-table-subtype object) 'syntax-table)))
(defun modify-syntax-entry (char newentry &optional syntax-table)
"Set syntax for the characters CHAR to the string NEWENTRY.
CHAR may be a cons (MIN . MAX), in which case, syntaxes of all characters
in the range between MIN and MAX, inclusive, are set. SYNTAX-TABLE
defaults to the current buffer's syntax table."
(interactive "cSet syntax for character: \nsSet syntax for %s to: ")
(set-char-table-range (or syntax-table (syntax-table))
char (string-to-syntax newentry))
nil)
(defun char-syntax (character)
"Return the syntax class of CHARACTER, described by a character.
For example, if CHARACTER is a word constituent, the character `?w' is
returned. The characters that correspond to various syntax codes are
listed in the documentation of `modify-syntax-entry'."
(syntax-class-to-char (syntax-class (aref (syntax-table) character))))
;; ---- capitalize / upcase-initials (casefiddle.c) ----
;; These live here, after `char-syntax', because the word test is the SYNTAX
;; TABLE's -- `case_ch_is_word (SYNTAX (ch))' -- not "is this a cased letter or
;; a digit", which is what elisprs used to ask. The difference is observable:
;; `fi' has no one-to-one upper case, so the old test called it a non-word
;; character, which made the *next* character a word start:
;; `(capitalize "find")' answered "fiNd" where Emacs answers "Find".
;;
;; The other half is that a word's first character is TITLE-cased, not
;; upper-cased. `case_character_impl' consults `special-titlecase' (one-to-many)
;; before the `titlecase' char-table and only then `upcase', which is why
;; `(capitalize "ßäöü")' is "Ssäöü" (not "ẞäöü") and `(capitalize "dza")' is
;; "Dza" (not "DZa"): Dz is the title-case digraph, distinct from DZ.
(defvar case-symbols-as-words nil
"Non-nil means the case functions treat symbol constituents as word ones.")
(defun --char-titlecase-1-- (c)
"The one-to-one title case of character C.
`case_character_impl' with a NULL buffer skips the one-to-many
`special-titlecase' table and consults the `titlecase' char-table, falling
back to `upcase' -- so `(capitalize ?\u01f3)' is the title digraph
\u01f2, while `(capitalize ?\u00df)', whose title case is two characters,
is the upper-case \u1e9e."
;; Out-of-range integers keep `upcase''s own casefiddle.c handling: a negative
;; fixnum is not a character (`char-or-string-p'), and one above the character
;; range comes back unchanged because Emacs reads the high bits as event
;; modifiers. Asking for a title case first would report `characterp' instead.
(if (or (< c 0) (> c #x3FFFFF))
(upcase c)
(let ((tc (--char-titlecase-- c)))
(if (= (length tc) 1) (aref tc 0) (upcase c)))))
(defun --case-ch-is-word-- (c)
"casefiddle.c `case_ch_is_word': is C a word constituent for casing?"
(let ((sy (--syntax-code-at-- nil c)))
(or (= sy 2) (and case-symbols-as-words (= sy 3)))))
(defun --casify-capitalize-- (s up-only)
"casefiddle.c `do_casify_multibyte_string' for the two capitalizing flags.
UP-ONLY non-nil is CASE_CAPITALIZE_UP (`upcase-initials'), which leaves the
rest of each word alone; nil is CASE_CAPITALIZE (`capitalize'), which
down-cases it."
(let ((chars (string-to-list s)) (out nil) (was nil) (in-word nil) c rest)
(while chars
(setq c (car chars))
(setq rest (cdr chars))
(setq was in-word)
(setq in-word (--case-ch-is-word-- c))
(cond
((not was) (push (--char-titlecase-- c) out))
(up-only (push (string c) out))
;; CASE_DOWN, plus `case_character''s Greek rule: a capital sigma that
;; ends a word down-cases to the FINAL sigma ς, not to σ.
((and (eq c 931) (or (null rest) (not (--case-ch-is-word-- (car rest)))))
(push (string 962) out))
(t (push (downcase (string c)) out)))
(setq chars rest))
(let ((res (apply (function concat) (reverse out))))
;; Text properties can only be carried straight across when no character
;; expanded, which the one-to-many title/lower mappings can break.
(if (= (length res) (length s))
(elisprs--carry-text-properties s res)
res))))
;; ---- skip-syntax-forward / skip-syntax-backward (syntax.c `skip_syntaxes') ----
;; The C builds a 256-entry fastmap over syntax CLASS CODES:
;;
;; if (i_byte < size_byte && SREF (string, 0) == '^') { negate = 1; i_byte++; }
;; while (i_byte < size_byte) { c = str[i_byte++]; fastmap[syntax_spec_code[c]] = 1; }
;; if (negate) for (i = 0; i < sizeof fastmap; i++) fastmap[i] ^= 1;
;;
;; then walks while `fastmap[SYNTAX (c)]' holds, stopping at LIM, and returns
;; `PT - start_point'. Here the set of accepted classes is carried as a list of
;; class indices instead of a 256-byte array; `negate' flips the membership test,
;; which is the same thing without the array.
;;
;; `syntax_spec_code' is the inverse of `--syntax-code-spec--' with one extra
;; entry: `-' is an alias for whitespace. Every other unlisted spec character
;; maps to 0377, a code no real class has -- so `(skip-syntax-forward "Z")' skips
;; nothing rather than signalling, and `(skip-syntax-forward "wZ")' behaves like
;; `"w"'. That is exactly what dropping the character from the list does.
(defun --syntax-spec-classes-- (spec)
"The list of syntax class indices SPEC's characters name (see `syntax_spec_code').
Characters that name no class contribute nothing, as in the C, where they
address a fastmap slot that no real syntax class can match."
(let ((i 0) (len (length spec)) (out nil) c class)
(while (< i len)
(setq c (aref spec i))
(setq class (if (eq c ?-) 0
(let ((j 0) (found nil) (n (length --syntax-code-spec--)))
(while (and (not found) (< j n))
(when (eq (aref --syntax-code-spec-- j) c) (setq found j))
(setq j (1+ j)))
found)))
(when class (push class out))
(setq i (1+ i)))
out))
(defun --skip-syntaxes-- (forwardp syntax lim)
"Common body of `skip-syntax-forward' and `skip-syntax-backward'."
(unless (stringp syntax) (signal 'wrong-type-argument (list 'stringp syntax)))
(let* ((negate (and (> (length syntax) 0) (eq (aref syntax 0) ?^)))
(spec (if negate (substring syntax 1) syntax))
(classes (--syntax-spec-classes-- spec))
(start (point))
;; "In any case, don't allow scan outside bounds of buffer."
(lim (max (point-min) (min (point-max)
(cond ((null lim) (if forwardp (point-max) (point-min)))
((markerp lim) (marker-position lim))
(t lim)))))
(ch nil))
(if forwardp
(while (and (< (point) lim)
(setq ch (char-after))
(let ((in (and (memq (syntax-class (aref (syntax-table) ch)) classes) t)))
(if negate (not in) in)))
(goto-char (1+ (point))))
(while (and (> (point) lim)
(setq ch (char-before))
(let ((in (and (memq (syntax-class (aref (syntax-table) ch)) classes) t)))
(if negate (not in) in)))
(goto-char (1- (point)))))
(- (point) start)))
(defun skip-syntax-forward (syntax &optional lim)
"Move point forward across chars in specified syntax classes.
SYNTAX is a string of syntax code characters.
Stop before a char whose syntax is not in SYNTAX, or at position LIM.
If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.
This function returns the distance traveled, either zero or positive."
(--skip-syntaxes-- t syntax lim))
(defun skip-syntax-backward (syntax &optional lim)
"Move point backward across chars in specified syntax classes.
SYNTAX is a string of syntax code characters.
Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.
If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.
This function returns either zero or a negative number, and the absolute value
of this is the distance traveled."
(--skip-syntaxes-- nil syntax lim))
(defmacro with-syntax-table (table &rest body)
"Evaluate BODY with syntax table TABLE as the current syntax table.
The syntax table of the current buffer is saved, BODY is evaluated, and
the saved table is restored. (Single-buffer model: the save/restore is
over the one current buffer's syntax-table slot.)"
(declare (indent 1) (debug t))
(let ((old-table (make-symbol "table")))
`(let ((,old-table (syntax-table)))
(unwind-protect
(progn
(set-syntax-table ,table)
,@body)
(set-syntax-table ,old-table)))))
;;; ---- syntax.c's sexp/comment scanner ----
;; `scan-lists', `parse-partial-sexp' and everything built on them are one
;; port, not seven: `Fforward_sexp' is `scan_lists', and `scan_lists' and
;; `Fparse_partial_sexp' share the comment/string state machine
;; (`scan_sexps_forward', `forw_comment', `back_comment', `char_quoted'),
;; including two-character comment delimiters, nested comments, the
;; `syntax-table' text property and `parse-sexp-ignore-comments'. A
;; parens-only subset would answer plausibly on the common case and wrongly
;; inside a string or a comment, so the whole machine is ported.
(defun buffer-end (arg)
"Return the \"far end\" position of the buffer, in direction ARG."
(if (> arg 0) (point-max) (point-min)))
;; ---- variables the scanner consults (syntax.c DEFVARs) ----
(defvar parse-sexp-ignore-comments nil
"Non-nil means `forward-sexp', etc., should treat comments as whitespace.")
(defvar parse-sexp-lookup-properties nil
"Non-nil means `forward-sexp', etc., obey the `syntax-table' text property.")
(defvar-local comment-end-can-be-escaped nil
"Non-nil means an escaped ender doesn't end the comment.")
(defvar multibyte-syntax-as-symbol nil
"Non-nil means `scan-sexps' treats all multibyte characters as symbol.")
(defvar open-paren-in-column-0-is-defun-start t
"Non-nil means an open paren in column 0 denotes the start of a defun.")
(defvar words-include-escapes nil
"Non-nil means `forward-word', etc., should treat escape chars part of words.")
(defvar comment-use-syntax-ppss t
"Non-nil means `forward-comment' can use `syntax-ppss' internally.")
;; ST_COMMENT_STYLE / ST_STRING_STYLE (syntax.c): sentinels for the styles that
;; the comment-fence and string-fence classes start, which no `b'/`c' flag
;; combination can name.
(defconst --st-comment-style-- 257)
(defconst --st-string-style-- 258)
;; enum syntaxcode. Smax doubles as "this position's syntax is used up".
(defconst --syn-smax-- 16)
;; ---- syntax lookup (syntax.h SYNTAX_ENTRY / SYNTAX_WITH_FLAGS / SYNTAX) ----
;; The C reads the entry through gl_state, which UPDATE_SYNTAX_TABLE_* keeps in
;; step with the `syntax-table' text property when `parse-sexp-lookup-properties'
;; is on. Here the position travels with the character instead, so the property
;; is consulted at the point of use and there is no cache to keep valid. A
;; property whose value is a syntax table selects that table for the character;
;; a cons is the raw descriptor itself, exactly as update_syntax_table does.
(defun --syntax-raw-at-- (pos c)
"The raw syntax descriptor (CODE . MATCH) for character C at POS."
(let ((prop (and parse-sexp-lookup-properties pos
(get-char-property pos 'syntax-table))))
(cond ((consp prop) prop)
((syntax-table-p prop) (aref prop c))
(t (aref (syntax-table) c)))))
(defun --syntax-flags-at-- (pos c)
"SYNTAX_WITH_FLAGS: the code+flags integer for C at POS.
A non-cons entry reads as whitespace, as in `syntax_property_with_flags'."
(let ((e (--syntax-raw-at-- pos c)))
(if (consp e) (car e) 0)))
(defun --syntax-code-at-- (pos c)
"SYNTAX: the syntax class of C at POS."
(logand (--syntax-flags-at-- pos c) 255))
(defun --syntax-match-at-- (pos c)
"SYNTAX_MATCH: the matching character of C at POS, or nil."
(let ((e (--syntax-raw-at-- pos c)))
(and (consp e) (cdr e))))
;; syntax_multibyte: with `multibyte-syntax-as-symbol', every non-ASCII
;; character reads as a symbol constituent regardless of its table entry.
(defun --syntax-code-mb-- (pos c mbsym)
(if (or (< c 128) (not mbsym)) (--syntax-code-at-- pos c) 3))
;; ---- SYNTAX_FLAGS_* (syntax.c) ----
(defun --syn-comstart-first-- (f) (/= 0 (logand f 65536))) ; 1 << 16
(defun --syn-comstart-second-- (f) (/= 0 (logand f 131072))) ; 1 << 17
(defun --syn-comend-first-- (f) (/= 0 (logand f 262144))) ; 1 << 18
(defun --syn-comend-second-- (f) (/= 0 (logand f 524288))) ; 1 << 19
(defun --syn-comstartend-first-- (f) (/= 0 (logand f 327680))) ; 0x50000
(defun --syn-prefix-- (f) (/= 0 (logand f 1048576))) ; 1 << 20
(defun --syn-styleb-- (f) (if (/= 0 (logand f 2097152)) 1 0)) ; 1 << 21
(defun --syn-nested-- (f) (/= 0 (logand f 4194304))) ; 1 << 22
(defun --syn-stylec2-- (f) (logand (ash f -22) 2)) ; 1 << 23 -> 2
;; FLAGS is the flags of the main char of the marker: the second for a comment
;; start, the first for a comment end.
(defun --syn-comment-style-- (f other)
(logior (--syn-styleb-- f) (--syn-stylec2-- f) (--syn-stylec2-- other)))
;; ---- char_quoted / prev_char_comend_first ----
(defun --char-quoted-- (charpos)
"Port of syntax.c `char_quoted': is CHARPOS preceded by an odd escape run?"
(let ((beg (point-min)) (pos charpos) (quoted nil) (stop nil) c code)
(while (and (not stop) (> pos beg))
(setq pos (1- pos))
(setq c (char-after pos))
(setq code (--syntax-code-at-- pos c))
(if (or (= code 9) (= code 10)) ; Sescape, Scharquote
(setq quoted (not quoted))
(setq stop t)))
quoted))
(defun --prev-char-comend-first-- (pos)
"Port of syntax.c `prev_char_comend_first'."
(let ((c (char-after (1- pos))))
(--syn-comend-first-- (--syntax-flags-at-- (1- pos) c))))
;; ---- find_defun_start (syntax.c), without the one-entry memo ----
;; The memo is pure speed; it caches the answer for a repeated query and is
;; invalidated on every buffer modification, so dropping it cannot change a
;; result. `open-paren-in-column-0-is-defun-start' nil means only BEGV counts.
(defun --find-defun-start-- (pos)
(let ((beg (point-min)) (found nil))
(if (not open-paren-in-column-0-is-defun-start)
beg
(save-excursion
(goto-char pos)
(while (and (not found) (> (point) beg))
(goto-char (line-beginning-position))
(if (and (< (point) (point-max))
(eq (--syntax-code-at-- (point) (char-after (point))) 4))
(setq found (point))
(if (<= (point) beg) (setq found beg) (goto-char (1- (point))))))
(or found beg)))))
;; ---- forw_comment (syntax.c) ----
;; Returns (FOUND POSITION INCOMMENT LAST-SYNTAX). INCOMMENT and LAST-SYNTAX
;; are only meaningful when FOUND is nil, exactly as the C's out-parameters are
;; only written on the not-found path.
(defun --forw-comment-- (from stop nesting style prev-syntax)
(let ((syntax prev-syntax) code c c1 other-syntax
(skip-head nil) (broke nil) (out nil))
(when (<= nesting 0) (setq nesting -1))
(setq code (logand syntax 255))
;; "Enter the loop in the middle so that we find a 2-char comment ender if
;; we start in the middle of it."
(when (and (/= syntax 0) (< from stop)) (setq skip-head t))
(while (and (not out) (not broke))
(if skip-head
(setq skip-head nil)
(if (= from stop)
(setq out (list nil from nesting
(if (or (= code 9) (= code 10)
(--syn-comend-first-- syntax)
(and (> nesting 0)
(--syn-comstart-first-- syntax)))
syntax --syn-smax--)))
(setq c (char-after from))
(setq prev-syntax syntax)
(setq syntax (--syntax-flags-at-- from c))
(setq code (logand syntax 255))
(cond
;; A comment ender of the style this comment section began with.
((and (= code 12)
(= (--syn-comment-style-- syntax 0) style)
(if (--syn-nested-- syntax)
(and (> nesting 0) (= (setq nesting (1- nesting)) 0))
(< nesting 0))
(not (and comment-end-can-be-escaped
(memq (logand prev-syntax 255) '(9 10)))))
(setq broke t))
;; A comment fence ends a fence-style comment.
((and (= code 14) (= style --st-comment-style--))
(setq broke t))
(t
(when (and (> nesting 0) (= code 11) (--syn-nested-- syntax)
(= (--syn-comment-style-- syntax 0) style))
(setq nesting (1+ nesting)))
(when (and comment-end-can-be-escaped (memq code '(9 10)))
(setq from (1+ from))
(if (= from stop)
(setq skip-head 'continue)
(setq c (char-after from))
(setq prev-syntax syntax)
(setq syntax --syn-smax--)
(setq code syntax)))
(unless (eq skip-head 'continue)
(setq from (1+ from)))))))
(when (and (not out) (not broke))
(if (eq skip-head 'continue)
(setq skip-head nil)
;; forw_incomment:
(when (and (< from stop) (--syn-comend-first-- syntax)
(progn (setq c1 (char-after from))
(setq other-syntax (--syntax-flags-at-- from c1))
(--syn-comend-second-- other-syntax))
(= (--syn-comment-style-- syntax other-syntax) style)
(if (or (--syn-nested-- syntax) (--syn-nested-- other-syntax))
(> nesting 0)
(< nesting 0)))
;; So that a two-char |# ender cannot report its # as LAST-SYNTAX.
(setq syntax --syn-smax--)
(setq nesting (1- nesting))
(if (<= nesting 0)
(setq broke t)
(setq from (1+ from))))
(when (and (not broke)
(> nesting 0) (< from stop)
(--syn-comstart-first-- syntax)
(progn (setq c1 (char-after from))
(setq other-syntax (--syntax-flags-at-- from c1))
(and (= (--syn-comment-style-- other-syntax syntax) style)
(--syn-comstart-second-- other-syntax)))
(or (--syn-nested-- syntax) (--syn-nested-- other-syntax)))
;; So that a #|# run is not also a comment ender.
(setq syntax --syn-smax--)
(setq from (1+ from))
(setq nesting (1+ nesting))))))
(or out (list t from nesting --syn-smax--))))
;; ---- back_comment (syntax.c) ----
;; Returns (FOUND POSITION). FOUND is `from != comment_end'.
(defun --back-comment-- (from stop comnested comstyle)
(let ((string-style -1) (string-lossage nil) (comment-lossage nil)
(comment-end from) (comstart-pos 0) (defun-start 0)
(nesting 1) (syntax 0) (lossage nil) (done nil) (loop t)
code c prev-syntax com2start com2end comstart)
(while (and loop (/= from stop))
(setq from (1- from))
(setq prev-syntax syntax)
(setq c (char-after from))
(setq syntax (--syntax-flags-at-- from c))
(setq code (logand syntax 255))
(setq com2start (and (--syn-comstart-first-- syntax)
(--syn-comstart-second-- prev-syntax)
(= comstyle (--syn-comment-style-- prev-syntax syntax))
(eq (and (or (--syn-nested-- prev-syntax)
(--syn-nested-- syntax))
t)
(and comnested t))))
(setq com2end (and (--syn-comend-first-- syntax)
(--syn-comend-second-- prev-syntax)))
(setq comstart (or com2start (= code 11)))
;; Overlapping 2-char markers: don't try to be clever.
(when (and (> from stop) (or com2end comstart))
(let* ((next-c (char-after (1- from)))
(next-syntax (--syntax-flags-at-- (1- from) next-c)))
(when (or (and (or comstart comnested)
(--syn-comend-second-- syntax)
(--syn-comend-first-- next-syntax))
(and (or com2end comnested)
(--syn-comstart-second-- syntax)
(= comstyle (--syn-comment-style-- syntax prev-syntax))
(--syn-comstart-first-- next-syntax)))
(setq lossage t loop nil))))
(when loop
;; The first 2-char marker seen counts as a starter, later ones as enders.
(when (and com2start (= comstart-pos 0)) (setq com2end nil))
(cond (com2end (setq code 12))
(com2start (setq code 11)))
(cond
;; Comment starters of a different style are not ours.
((and (not com2end) (not com2start) (= code 11)
(or (/= comstyle (--syn-comment-style-- syntax 0))
(not (eq (and (--syn-nested-- syntax) t) (and comnested t)))))
nil)
;; Escaped characters, except comment-enders, which cannot be escaped.
((and (or comment-end-can-be-escaped (/= code 12))
(--char-quoted-- from))
nil)
(t
(cond
((memq code '(15 14 7)) ; Sstring_fence, Scomment_fence, Sstring
(when (memq code '(15 14))
(setq c (if (= code 15) --st-string-style-- --st-comment-style--)))
(cond ((= string-style -1) (setq string-style c))
((= string-style c) (setq string-style -1))
(t (setq string-lossage t))))
((= code 11) ; Scomment
(if (or (/= string-style -1) comment-lossage string-lossage)
(setq lossage t loop nil)
(if (not comnested)
(setq comstart-pos from)
(setq nesting (1- nesting))
(when (<= nesting 0) (setq done t loop nil)))))
((= code 12) ; Sendcomment
(if (and (= (--syn-comment-style-- syntax 0) comstyle)
(eq (and (or (and com2end (--syn-nested-- prev-syntax))
(--syn-nested-- syntax))
t)
(and comnested t)))
(if comnested
(setq nesting (1+ nesting))
;; Anything before this would match this ender, not ours.
(setq from stop))
(when (or (/= comstart-pos 0) (not (eq c ?\n)))
(setq comment-lossage t))))
((= code 4) ; Sopen
(when (and open-paren-in-column-0-is-defun-start
(null comment-use-syntax-ppss)
(or (= from stop) (eq (char-after (1- from)) ?\n)))
(setq defun-start from)
(setq from stop)))
(t nil))))))
(cond
(done nil)
(lossage
;; Two kinds of string delimiter mixed together: decode going forwards
;; from a known safe place, recording where we last passed a starter.
(when (= defun-start 0)
(setq defun-start (--find-defun-start-- comment-end)))
(let ((go t) state)
(while go
(setq state (--scan-sexps-forward-- (--pps-internalize-- nil)
defun-start comment-end
--pps-no-target-- nil 0))
(setq defun-start comment-end)
(if (and (= (--pps-incomment-- state) (if comnested 1 -1))
(= (--pps-comstyle-- state) comstyle))
(setq from (--pps-comstr-start-- state))
(setq from comment-end)
(when (/= (--pps-incomment-- state) 0)
(setq defun-start (+ (--pps-comstr-start-- state) 2))))
(setq go (< defun-start comment-end)))))
((= comstart-pos 0) (setq from comment-end))
(t (setq from comstart-pos)))
(list (/= from comment-end) from)))
;; ---- the parse state of scan_sexps_forward ----
;; A 12-slot vector standing in for `struct lisp_parse_state'.
(defconst --pps-no-target-- -2305843009213693952
"Stand-in for TYPE_MINIMUM (EMACS_INT): a depth the scan cannot reach.")
(defun --pps-depth-- (s) (aref s 0))
(defun --pps-instring-- (s) (aref s 1))
(defun --pps-incomment-- (s) (aref s 2))
(defun --pps-comstyle-- (s) (aref s 3))
(defun --pps-quoted-- (s) (aref s 4))
(defun --pps-mindepth-- (s) (aref s 5))
(defun --pps-thislevelstart-- (s) (aref s 6))
(defun --pps-prevlevelstart-- (s) (aref s 7))
(defun --pps-location-- (s) (aref s 8))
(defun --pps-comstr-start-- (s) (aref s 9))
(defun --pps-levelstarts-- (s) (aref s 10))
(defun --pps-prev-syntax-- (s) (aref s 11))
(defun --pps-internalize-- (external)
"Port of syntax.c `internalize_parse_state'."
(if (null external)
(vector 0 -1 0 0 nil 0 -1 -1 0 -1 nil --syn-smax--)
(let* ((depth (let ((tem (nth 0 external))) (if (integerp tem) tem 0)))
(tem3 (nth 3 external))
(instring (if tem3 (if (characterp tem3) tem3 --st-string-style--) -1))
(tem4 (nth 4 external))
(incomment (if tem4 (if (integerp tem4) tem4 -1) 0))
(quoted (and (nth 5 external) t))
(tem7 (nth 7 external))
(comstyle (cond ((null tem7) 0)
((and (integerp tem7) (>= tem7 0)
(<= tem7 --st-comment-style--))
tem7)
(t --st-comment-style--)))
(tem8 (nth 8 external))
(comstr-start (if (integerp tem8) tem8 -1))
(levelstarts (nth 9 external))
(tem10 (nth 10 external))
(prev-syntax (if (null tem10) --syn-smax-- tem10)))
(vector depth instring incomment comstyle quoted 0 -1 -1 0
comstr-start levelstarts prev-syntax))))
;; in_2char_comment_start (syntax.c): is the char at FROM the second half of a
;; 2-character comment opener begun by PREV-FROM-SYNTAX? Updates STATE.
(defun --pps-in-2char-comment-start-- (state prev-from-syntax prev-from from)
(let (c1 syntax)
(when (and (--syn-comstart-first-- prev-from-syntax)
(progn (setq c1 (char-after from))
(setq syntax (--syntax-flags-at-- from c1))
(--syn-comstart-second-- syntax)))
(aset state 3 (--syn-comment-style-- syntax prev-from-syntax))
(aset state 2 (if (or (--syn-nested-- prev-from-syntax)
(--syn-nested-- syntax))
1 -1))
(aset state 9 prev-from)
t)))
;; ---- scan_sexps_forward (syntax.c) ----
;; The C is one function with eleven labels and a fallthrough switch. It is
;; transcribed here as an explicit label machine: LABEL holds the C's program
;; counter, each branch returns the next label, and nil ends the scan. Writing
;; it as structured elisp would need the control flow to be re-derived, which is
;; exactly the step that turns a port into a rewrite.
;;
;; `struct level levelstart[100]' becomes OUTER (a list of (LAST . PREV) conses,
;; innermost first) plus CUR-LAST/CUR-PREV for `curlevel'. The C silently
;; clamps at 100 levels rather than signalling, so NLEV does too.
(defun --scan-sexps-forward-- (state from end targetdepth stopbefore commentstop)
(let* ((depth (--pps-depth-- state))
(start-quoted (--pps-quoted-- state))
(mindepth depth)
(prev-from from)
(prev-from-syntax (--pps-prev-syntax-- state))
(prev-prev-from-syntax --syn-smax--)
(boundary-stop (eq commentstop -1))
(begv (point-min))
(cur-last -1) (cur-prev -1) (outer nil) (nlev 0)
(label 'entry)
nofence res code c c-code symchar tem)
(when (/= from begv) (setq prev-from (1- from)))
;; INC_FROM, as a closure so every call site reads like the C's macro. A
;; plain lexical closure rather than `cl-flet': `cl-flet' walks the whole
;; body to rewrite the call sites, and this body is the largest form in the
;; prelude, which pushed prelude loading past the 2 MiB stack a test thread
;; gets (the shipped binary runs on a 512 MiB interpreter stack and never
;; saw it).
(let ((inc-from (lambda ()
(setq prev-from from)
(setq tem (char-after prev-from))
(setq prev-prev-from-syntax prev-from-syntax)
(setq prev-from-syntax (--syntax-flags-at-- prev-from tem))
(setq from (1+ from)))))
(while label
(setq label
(cond
;; ---- entry dispatch ----
((eq label 'entry)
(dolist (temhd (--pps-levelstarts-- state))
(when (integerp temhd) (setq cur-last temhd))
(if (= nlev 99)
nil
(push (cons cur-last cur-prev) outer)
(setq nlev (1+ nlev)))
(setq cur-prev -1 cur-last -1))
(setq cur-prev -1 cur-last -1)
(aset state 4 nil)
(cond
((/= (--pps-incomment-- state) 0) 'startincomment)
((>= (--pps-instring-- state) 0)
(setq nofence (/= (--pps-instring-- state) --st-string-style--))
(if start-quoted 'startquotedinstring 'startinstring))
(start-quoted 'startquoted)
((and (< from end)
(--pps-in-2char-comment-start-- state prev-from-syntax
prev-from from))
(funcall inc-from)
(setq prev-from-syntax --syn-smax--)
'atcomment)
(t 'main)))
;; ---- while (from < end) ----
((eq label 'main)
(if (>= from end)
'done
(funcall inc-from)
(cond
((and (< from end)
(--pps-in-2char-comment-start-- state prev-from-syntax
prev-from from))
(funcall inc-from)
(setq prev-from-syntax --syn-smax--)
'atcomment)
((--syn-prefix-- prev-from-syntax) 'main)
(t
(setq code (logand prev-from-syntax 255))
(cond
((memq code '(9 10)) ; Sescape, Scharquote
(if stopbefore 'stop
(setq cur-last prev-from)
'startquoted))
((memq code '(2 3)) ; Sword, Ssymbol
(if stopbefore 'stop
(setq cur-last prev-from)
'symstarted))
((= code 14) ; Scomment_fence
(aset state 3 --st-comment-style--)
(aset state 2 -1)
(aset state 9 prev-from)
'atcomment)
((= code 11) ; Scomment
(aset state 3 (--syn-comment-style-- prev-from-syntax 0))
(aset state 2 (if (--syn-nested-- prev-from-syntax) 1 -1))
(aset state 9 prev-from)
'atcomment)
((= code 4) ; Sopen
(if stopbefore 'stop
(setq depth (1+ depth))
(setq cur-last prev-from)
(if (= nlev 99)
nil
(push (cons cur-last cur-prev) outer)
(setq nlev (1+ nlev)))
(setq cur-prev -1 cur-last -1)
(if (= targetdepth depth) 'done 'main)))
((= code 5) ; Sclose
(setq depth (1- depth))
(when (< depth mindepth) (setq mindepth depth))
(when (> nlev 0)
(setq cur-last (car (car outer)))
(setq cur-prev (cdr (car outer)))
(setq outer (cdr outer))
(setq nlev (1- nlev)))
(setq cur-prev cur-last)
(if (= targetdepth depth) 'done 'main))
((memq code '(7 15)) ; Sstring, Sstring_fence
(aset state 9 (1- from))
(if stopbefore 'stop
(setq cur-last prev-from)
(aset state 1 (if (= code 7)
(char-after prev-from)
--st-string-style--))
(if boundary-stop 'done 'startinstring)))
(t 'main)))))) ; Smath, whitespace, punct, ...
;; ---- startquoted ----
((eq label 'startquoted)
(if (= from end) 'endquoted (funcall inc-from) 'symstarted))
;; ---- symstarted / symdone ----
((eq label 'symstarted)
(cond
((>= from end) (setq cur-prev cur-last) 'main)
((--pps-in-2char-comment-start-- state prev-from-syntax
prev-from from)
(funcall inc-from)
(setq prev-from-syntax --syn-smax--)
'atcomment)
(t
(setq symchar (char-after from))
(setq code (--syntax-code-at-- from symchar))
(cond
((memq code '(9 10)) ; Scharquote, Sescape
(funcall inc-from)
(if (= from end) 'endquoted (funcall inc-from) 'symstarted))
((memq code '(2 3 6)) ; Sword, Ssymbol, Squote
(funcall inc-from)
'symstarted)
(t (setq cur-prev cur-last) 'main)))))
;; ---- atcomment / startincomment ----
((eq label 'atcomment)
(if (or (/= commentstop 0) boundary-stop)
'done
'startincomment))
((eq label 'startincomment)
;; The (from == BEGV) test enters forw_comment in the middle so
;; that a 2-char ender is found even when the scan starts inside
;; it -- but not when we are only just at the comment's start
;; (think of "(*) ... (*)").
(setq res (--forw-comment-- from end
(--pps-incomment-- state)
(--pps-comstyle-- state)
(if (= from begv) 0 prev-from-syntax)))
(setq from (nth 1 res))
(setq prev-from-syntax (nth 3 res))
(if (not (nth 0 res))
(progn
(aset state 2 (nth 2 res))
(if (memq (logand prev-from-syntax 255) '(9 10))
'endquoted
'done))
(funcall inc-from)
(aset state 2 0)
(aset state 3 0)
(setq prev-from-syntax --syn-smax--)
(if boundary-stop 'done 'main)))
;; ---- startinstring / startquotedinstring / string_end ----
((eq label 'startinstring)
(setq nofence (/= (--pps-instring-- state) --st-string-style--))
'instring-loop)
((eq label 'startquotedinstring)
(if (>= from end) 'endquoted (funcall inc-from) 'instring-loop))
((eq label 'instring-loop)
(if (>= from end)
'done
(setq c (char-after from))
(setq c-code (--syntax-code-at-- from c))
(if (and nofence (eq c (--pps-instring-- state)) (= c-code 7))
'string-end
(cond
((= c-code 15) ; Sstring_fence
(if (not nofence) 'string-end (funcall inc-from) 'instring-loop))
((memq c-code '(9 10)) ; Scharquote, Sescape
(funcall inc-from)
(if (>= from end) 'endquoted (funcall inc-from) 'instring-loop))
(t (funcall inc-from) 'instring-loop)))))
((eq label 'string-end)
(aset state 1 -1)
(setq cur-prev cur-last)
(funcall inc-from)
(if boundary-stop 'done 'main))
;; ---- stop / endquoted / done ----
((eq label 'stop)
(setq from prev-from)
(setq prev-from-syntax prev-prev-from-syntax)
'done)
((eq label 'endquoted)
(aset state 4 t)
'done)
((eq label 'done)
(aset state 0 depth)
(aset state 5 mindepth)
(aset state 6 cur-prev)
(aset state 7 (if (= nlev 0) -1 (car (car outer))))
(aset state 8 from)
(aset state 10 (reverse (mapcar #'car outer)))
(aset state 11 (if (or (--syn-comstartend-first-- prev-from-syntax)
(--pps-quoted-- state))
prev-from-syntax
--syn-smax--))
nil)))))
state))
;; ---- scan_lists (syntax.c) ----
;; The C's `goto lose' is a signal, so it stays a signal here. `done'/`done2'
;; end one iteration of the count loop and `return Qnil' leaves the whole scan,
;; so those two are catch tags.
(defun --scan-lists-- (from0 count depth sexpflag)
(let* ((stop (if (> count 0) (point-max) (point-min)))
(min-depth (if (> depth 0) 0 depth))
(from (max (point-min) (min (point-max) from0)))
(last-good from0)
(comstyle 0) (comnested nil) (mathexit nil)
(mbsym (and sexpflag multibyte-syntax-as-symbol t))
c c1 code syntax other-syntax comstart-first prefix
stringterm c-code quoted temp-pos res act inner)
(catch '--sl-return--
(while (> count 0)
(catch '--sl-done--
(while (< from stop)
(setq c (char-after from))
(setq syntax (--syntax-flags-at-- from c))
(setq code (--syntax-code-mb-- from c mbsym))
(setq comstart-first (--syn-comstart-first-- syntax))
(setq comnested (--syn-nested-- syntax))
(setq comstyle (--syn-comment-style-- syntax 0))
(setq prefix (--syn-prefix-- syntax))
(when (= depth min-depth) (setq last-good from))
(setq from (1+ from))
;; The C reassigns C inside the && chain, so it is clobbered
;; whenever the first two conjuncts hold -- even if
;; `parse-sexp-ignore-comments' is nil and the branch is not taken.
(when (and (< from stop) comstart-first)
(setq c (char-after from))
(setq other-syntax (--syntax-flags-at-- from c))
(when (and (--syn-comstart-second-- other-syntax)
parse-sexp-ignore-comments)
(setq code 11)
(setq comstyle (--syn-comment-style-- other-syntax syntax))
(setq comnested (or comnested (--syn-nested-- other-syntax)))
(setq from (1+ from))))
(unless prefix
(setq act nil)
(when (memq code '(9 10)) ; Sescape, Scharquote
(when (= from stop) (--sl-lose-- last-good from))
(setq from (1+ from))
(setq code 2)) ; fall through to Sword
(cond
((memq code '(2 3)) ; Sword, Ssymbol
(unless (or (/= depth 0) (not sexpflag))
(setq inner t)
(while (and inner (< from stop))
(setq c (char-after from))
(setq c-code (--syntax-code-mb-- from c mbsym))
(cond
((memq c-code '(9 10))
(setq from (1+ from))
(when (= from stop) (--sl-lose-- last-good from)))
((memq c-code '(2 3 6)) nil) ; Sword, Ssymbol, Squote
(t (setq inner nil)))
(when inner (setq from (1+ from))))
(throw '--sl-done-- nil)))
((memq code '(11 14)) ; Scomment, Scomment_fence
(when (= code 14) (setq comstyle --st-comment-style--))
(when parse-sexp-ignore-comments
(setq res (--forw-comment-- from stop
(if comnested 1 0) comstyle 0))
(setq from (nth 1 res))
(unless (nth 0 res)
(if (= depth 0)
(throw '--sl-done-- nil)
(--sl-lose-- last-good from)))
(setq from (1+ from))))
((= code 8) ; Smath
(when sexpflag
(when (and (/= from stop) (eq c (char-after from)))
(setq from (1+ from)))
(if mathexit
(progn (setq mathexit nil) (setq act 'close))
(setq mathexit t)
(setq act 'open))))
((= code 4) (setq act 'open)) ; Sopen
((= code 5) (setq act 'close)) ; Sclose
((memq code '(7 15)) ; Sstring, Sstring_fence
(setq stringterm (char-after (1- from)))
(setq inner t)
(while inner
(when (>= from stop) (--sl-lose-- last-good from))
(setq c (char-after from))
(setq c-code (--syntax-code-mb-- from c mbsym))
(if (if (= code 7)
(and (eq c stringterm) (= c-code 7))
(= c-code 15))
(setq inner nil)
(when (memq c-code '(9 10)) (setq from (1+ from)))
(setq from (1+ from))))
(setq from (1+ from))
(when (and (= depth 0) sexpflag) (throw '--sl-done-- nil)))
(t nil)) ; whitespace, punct, quote...
(cond
((eq act 'open)
(setq depth (1+ depth))
(when (= depth 0) (throw '--sl-done-- nil)))
((eq act 'close)
(setq depth (1- depth))
(when (= depth 0) (throw '--sl-done-- nil))
(when (< depth min-depth)
(signal 'scan-error
(list "Containing expression ends prematurely"
last-good from)))))))
;; Reached end of buffer: error if within an object, nil if between.
(when (/= depth 0) (--sl-lose-- last-good from))
(throw '--sl-return-- nil))
(setq count (1- count)))
(while (< count 0)
(catch '--sl-done--
(while (> from stop)
(setq from (1- from))
(setq c (char-after from))
(setq syntax (--syntax-flags-at-- from c))
(setq code (--syntax-code-mb-- from c mbsym))
(when (= depth min-depth) (setq last-good from))
(setq comstyle 0)
(setq comnested (--syn-nested-- syntax))
(when (= code 12) (setq comstyle (--syn-comment-style-- syntax 0)))
(setq prefix nil)
(when (and (> from stop) (--syn-comend-second-- syntax)
(--prev-char-comend-first-- from)
parse-sexp-ignore-comments)
(setq from (1- from))
(setq code 12)
(setq c1 (char-after from))
(setq other-syntax (--syntax-flags-at-- from c1))
(setq comstyle (--syn-comment-style-- other-syntax syntax))
(setq comnested (or comnested (--syn-nested-- other-syntax))))
;; Quoting turns anything but a comment-ender into a word char.
(if (and (/= code 12) (--char-quoted-- from))
(progn (setq from (1- from)) (setq code 2))
(when (--syn-prefix-- syntax) (setq prefix t)))
(unless prefix
(setq act nil)
(cond
((memq code '(2 3 9 10)) ; Sword, Ssymbol, Sescape, ...
(unless (or (/= depth 0) (not sexpflag))
(setq inner t)
(while (and inner (> from stop))
(setq temp-pos (1- from))
(setq c1 (char-after temp-pos))
;; Don't allow comment-end to be quoted.
(if (= (--syntax-code-mb-- temp-pos c1 mbsym) 12)
(setq inner nil)
(setq quoted (--char-quoted-- (1- from)))
(when quoted
(setq from (1- from))
(setq temp-pos (1- temp-pos)))
(setq c1 (char-after temp-pos))
(if (and (not quoted)
(not (memq (--syntax-code-mb-- temp-pos c1 mbsym)
'(2 3 6))))
(setq inner nil)
(setq from (1- from)))))
(throw '--sl-done-- nil)))
((= code 8) ; Smath
(when sexpflag
(when (> from (point-min))
(setq temp-pos (1- from))
(when (and (/= from stop) (eq c (char-after temp-pos)))
(setq from (1- from))))
(if mathexit
(progn (setq mathexit nil) (setq act 'open))
(setq mathexit t)
(setq act 'close))))
((= code 5) (setq act 'close)) ; Sclose
((= code 4) (setq act 'open)) ; Sopen
((= code 12) ; Sendcomment
(when parse-sexp-ignore-comments
(setq res (--back-comment-- from stop comnested comstyle))
(when (nth 0 res) (setq from (nth 1 res)))))
((memq code '(14 15)) ; Scomment_fence, Sstring_fence
(setq inner t)
(while inner
(when (= from stop) (--sl-lose-- last-good from))
(setq from (1- from))
(unless (--char-quoted-- from)
(setq c (char-after from))
(when (= (--syntax-code-mb-- from c mbsym) code)
(setq inner nil))))
(when (and (= code 15) (= depth 0) sexpflag)
(throw '--sl-done-- nil)))
((= code 7) ; Sstring
(setq stringterm (char-after from))
(setq inner t)
(while inner
(when (= from stop) (--sl-lose-- last-good from))
(setq from (1- from))
(unless (--char-quoted-- from)
(setq c (char-after from))
(when (and (eq c stringterm)
(= (--syntax-code-mb-- from c mbsym) 7))
(setq inner nil))))
(when (and (= depth 0) sexpflag) (throw '--sl-done-- nil)))
(t nil))
(cond
((eq act 'close)
(setq depth (1+ depth))
(when (= depth 0) (throw '--sl-done-- nil)))
((eq act 'open)
(setq depth (1- depth))
(when (= depth 0) (throw '--sl-done-- nil))
(when (< depth min-depth)
(signal 'scan-error
(list "Containing expression ends prematurely"
last-good from)))))))
(when (/= depth 0) (--sl-lose-- last-good from))
(throw '--sl-return-- nil))
(setq count (1+ count)))
from)))
(defun --sl-lose-- (last-good from)
(signal 'scan-error (list "Unbalanced parentheses" last-good from)))
;; ---- the scanner's Lisp entry points ----
(defun scan-lists (from count depth)
"Scan from character number FROM by COUNT lists.
Scan forward if COUNT is positive, backward if COUNT is negative.
Return the character number of the position thus found.
A \"list\", in this context, refers to a balanced parenthetical
grouping, as determined by the syntax table.
If DEPTH is nonzero, treat that as the nesting depth of the starting
point (i.e. the starting point is DEPTH parentheses deep). This
function scans over parentheses until the depth goes to zero COUNT
times. Hence, positive DEPTH moves out that number of levels of
parentheses, while negative DEPTH moves to a deeper level.
Comments are ignored if `parse-sexp-ignore-comments' is non-nil.
If we reach the beginning or end of the accessible part of the buffer
before we have scanned over COUNT lists, return nil if the depth at
that point is zero, and signal an error if the depth is nonzero."
(unless (integerp from) (signal 'wrong-type-argument (list 'fixnump from)))
(unless (integerp count) (signal 'wrong-type-argument (list 'fixnump count)))
(unless (integerp depth) (signal 'wrong-type-argument (list 'fixnump depth)))
(--scan-lists-- from count depth nil))
(defun scan-sexps (from count)
"Scan from character number FROM by COUNT balanced expressions.
If COUNT is negative, scan backwards.
Returns the character number of the position thus found.
Comments are ignored if `parse-sexp-ignore-comments' is non-nil.
If the beginning or end of (the accessible part of) the buffer is reached
in the middle of a parenthetical grouping, an error is signaled.
If the beginning or end is reached between groupings
but before count is used up, nil is returned."
(unless (integerp from) (signal 'wrong-type-argument (list 'fixnump from)))
(unless (integerp count) (signal 'wrong-type-argument (list 'fixnump count)))
(--scan-lists-- from count 0 t))
(defun matching-paren (character)
"Return the matching parenthesis of CHARACTER, or nil if none."
(unless (characterp character)
(signal 'wrong-type-argument (list 'characterp character)))
(let ((code (--syntax-code-at-- nil character)))
(and (memq code '(4 5)) (--syntax-match-at-- nil character))))
(defun syntax-after (pos)
"Return the raw syntax descriptor for the char after POS.
If POS is outside the buffer's accessible portion, return nil."
(unless (or (< pos (point-min)) (>= pos (point-max)))
(let ((st (and parse-sexp-lookup-properties
(get-char-property pos 'syntax-table))))
(if (consp st) st (aref (syntax-table) (char-after pos))))))
(defun syntax-prefix-flag-p (c)
"Whether the syntax of character C has the prefix flag set."
(--syn-prefix-- (--syntax-flags-at-- nil c)))
(defun backward-prefix-chars ()
"Move point backward over any number of chars with prefix syntax.
This includes chars with expression prefix syntax class (') and those with
the prefix syntax flag (p)."
(let* ((beg (point-min)) (opoint (point)) (pos (point)) (go t) c)
(if (<= pos beg)
(progn (goto-char opoint) nil)
(setq pos (1- pos))
(while (and go
(not (--char-quoted-- pos))
(progn (setq c (char-after pos))
(or (= (--syntax-code-at-- pos c) 6)
(syntax-prefix-flag-p c))))
(setq opoint pos)
(if (<= pos beg)
(setq go nil)
(setq pos (1- pos))))
(goto-char opoint)
nil)))
;; ── indentation and whitespace commands (indent.c, simple.el) ──
(defvar indent-tabs-mode t)
(defvar delete-trailing-lines t)
(defun back-to-indentation ()
"Move point to the first non-whitespace character on this line."
(beginning-of-line 1)
(skip-syntax-forward " " (line-end-position))
(backward-prefix-chars))
(defun delete-horizontal-space (&optional backward-only)
"Delete all spaces and tabs around point.
If BACKWARD-ONLY is non-nil, delete them only before point."
(let ((orig-pos (point)))
(delete-region
(if backward-only
orig-pos
(progn (skip-chars-forward " \t") (point)))
(progn (skip-chars-backward " \t") (point)))))
(defun delete-trailing-whitespace (&optional start end)
"Delete trailing whitespace between START and END (default: whole buffer).
With no END, also delete trailing empty lines at the end of the buffer when
`delete-trailing-lines' is non-nil. Returns nil."
(save-match-data
(save-excursion
(let ((end-marker (and end (copy-marker end))))
(goto-char (or start (point-min)))
(with-syntax-table (make-syntax-table (syntax-table))
;; Don't delete formfeeds, even if they are considered whitespace.
(modify-syntax-entry ?\f "_")
(while (re-search-forward "\\s-$" end-marker t)
(skip-syntax-backward "-" (line-beginning-position))
(delete-region (point) (match-end 0))))
(if end
(set-marker end-marker nil)
(and delete-trailing-lines
(= (goto-char (point-max)) (1+ (buffer-size)))
(<= (skip-chars-backward "\n") -2)
(delete-region (1+ (point)) (point-max)))))))
nil)
;; simple.el whitespace commands. elisprs has no `field' text properties, so
;; simple.el's `(constrain-to-field nil ORIG-POS)' calls — which only differ
;; from point inside a field — are spelled as point.
(defvar fill-prefix nil)
(defvar deactivate-mark nil)
(defun fixup-whitespace ()
"Fixup white space between objects around point.
Leave one space or none, according to the context."
(save-excursion
(delete-horizontal-space)
(if (or (looking-at "^\\|$\\|\\s)")
(save-excursion (forward-char -1)
(looking-at "$\\|\\s(\\|\\s'")))
nil
(insert ?\s))))
(defun delete-indentation (&optional arg beg end)
"Join this line to previous and fix up whitespace at join.
With ARG, join the current line to the following line. When BEG and END are
non-nil, join all lines in the region they define."
(setq deactivate-mark t)
(if (and beg (not arg))
(and (goto-char beg)
(> end (line-end-position))
(goto-char end))
(setq beg (1- (line-beginning-position (and arg 2))))
(when arg (forward-line)))
(let ((prefix (and (> (length fill-prefix) 0)
(regexp-quote fill-prefix))))
(while (and (> (line-beginning-position) beg)
(forward-line 0)
(= (preceding-char) ?\n))
(delete-char -1)
(if (and prefix (looking-at prefix))
(replace-match "" t t))
(fixup-whitespace))))
(defalias 'join-line #'delete-indentation)
(defun delete-blank-lines ()
"On blank line, delete all surrounding blank lines, leaving just one.
On isolated blank line, delete that one.
On nonblank line, delete any immediately following blank lines."
(let (thisblank singleblank)
(save-excursion
(beginning-of-line)
(setq thisblank (looking-at "[ \t]*$"))
(setq singleblank
(and thisblank
(not (looking-at "[ \t]*\n[ \t]*$"))
(or (bobp)
(progn (forward-line -1)
(not (looking-at "[ \t]*$")))))))
(if thisblank
(progn
(beginning-of-line)
(if singleblank (forward-line 1))
(delete-region (point)
(if (re-search-backward "[^ \t\n]" nil t)
(progn (forward-line 1) (point))
(point-min)))))
(if (not (and thisblank singleblank))
(save-excursion
(end-of-line)
(forward-line 1)
(delete-region (point)
(if (re-search-forward "[^ \t\n]" nil t)
(progn (beginning-of-line) (point))
(point-max)))))
(if (looking-at "^[ \t]*\n\\'")
(delete-region (point) (point-max)))))
(defun just-one-space (&optional n)
"Delete all spaces and tabs around point, leaving one space (or N spaces).
If N is negative, delete newlines as well, leaving -N spaces."
(let ((skip-characters (if (and n (< n 0)) " \t\n\r" " \t"))
(num (abs (or n 1))))
(skip-chars-backward skip-characters)
(let* ((num (- num (skip-chars-forward " " (+ num (point)))))
(mid (point))
(end (progn
(skip-chars-forward skip-characters)
(point))))
(delete-region mid end)
(insert (make-string num ?\s)))))
;; subr.el `shell-quote-argument', POSIX branch: the ms-dos and windows-nt
;; branches are for `system-type's elisprs never runs as.
(defun shell-quote-argument (argument &optional _posix)
"Quote ARGUMENT for passing as argument to an inferior POSIX shell."
(if (equal argument "")
"''"
(string-replace
"\n" "'\n'"
(replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))
;; ── round 32: buffer primitives and commands that were void ──
;; The C ones are written against their editfns.c / indent.c contracts; the
;; Lisp ones are ports of the 31.1 sources (simple.el, sort.el, tabify.el,
;; replace.el, subr.el, float-sup.el).
(defalias 'point-at-eol #'line-end-position)
(defalias 'point-at-bol #'line-beginning-position)
(defconst degrees-to-radians (/ float-pi 180.0)
"Degrees to radian conversion constant.")
(defconst radians-to-degrees (/ 180.0 float-pi)
"Radian to degree conversion constant.")
(defmacro degrees-to-radians (x)
"Convert X from degrees to radians."
(list '* degrees-to-radians x))
(defmacro radians-to-degrees (x)
"Convert X from radians to degrees."
(list '* radians-to-degrees x))
(defun function-alias-p (func &optional _noerror)
"Return nil if FUNC is not a function alias.
If FUNC is a function alias, return the function alias chain."
(let ((chain nil))
(while (and (symbolp func)
(setq func (symbol-function func))
(symbolp func))
(push func chain))
(nreverse chain)))
(defun add-to-ordered-list (list-var element &optional order)
"Add ELEMENT to the value of LIST-VAR if it isn't there yet, keeping the
list ordered by the numbers recorded in LIST-VAR's `list-order' property."
(let ((ordering (get list-var 'list-order)))
(unless ordering
(put list-var 'list-order
(setq ordering (make-hash-table :weakness 'key :test 'eq))))
(when order
(puthash element (and (numberp order) order) ordering))
(unless (memq element (symbol-value list-var))
(set list-var (cons element (symbol-value list-var))))
(set list-var (sort (symbol-value list-var)
(lambda (a b)
(let ((oa (gethash a ordering))
(ob (gethash b ordering)))
(if (and oa ob)
(< oa ob)
oa)))))))
(defun insert-buffer-substring-no-properties (buffer &optional start end)
"Insert before point a substring of BUFFER, without text properties."
(let ((opoint (point)))
(insert-buffer-substring buffer start end)
(let ((inhibit-read-only t))
(set-text-properties opoint (point) nil))))
(defun compare-buffer-substrings (buffer1 start1 end1 buffer2 start2 end2)
"Compare two substrings of two buffers; return result as number.
editfns.c: -N if the first is less after N-1 equal characters, N if greater,
0 if equal; `case-fold-search' non-nil folds case."
(let ((text (lambda (buffer start end)
(with-current-buffer (if buffer (or (get-buffer buffer)
(error "No buffer named %s" buffer))
(current-buffer))
(let ((b (or start (point-min))) (e (or end (point-max))))
(when (> b e) (setq b (prog1 e (setq e b))))
(unless (and (<= (point-min) b) (<= e (point-max)))
(signal 'args-out-of-range (list start end)))
(buffer-substring-no-properties b e))))))
(let ((r (compare-strings (funcall text buffer1 start1 end1) nil nil
(funcall text buffer2 start2 end2) nil nil
case-fold-search)))
(if (eq r t) 0 r))))
(defun current-word (&optional strict really-word)
"Return the word at or near point, as a string, without text properties."
(save-excursion
(let* ((oldpoint (point)) (start (point)) (end (point))
(syntaxes (if really-word "w" "w_"))
(not-syntaxes (concat "^" syntaxes)))
(skip-syntax-backward syntaxes) (setq start (point))
(goto-char oldpoint)
(skip-syntax-forward syntaxes) (setq end (point))
(when (and (eq start oldpoint) (eq end oldpoint)
;; Point is neither within nor adjacent to a word.
(not strict))
;; Look for preceding word in same line.
(skip-syntax-backward not-syntaxes (line-beginning-position))
(if (bolp)
;; No preceding word in same line.
;; Look for following word in same line.
(progn
(skip-syntax-forward not-syntaxes (line-end-position))
(setq start (point))
(skip-syntax-forward syntaxes)
(setq end (point)))
(setq end (point))
(skip-syntax-backward syntaxes)
(setq start (point))))
;; If we found something nonempty, return it as a string.
(unless (= start end)
(buffer-substring-no-properties start end)))))
(defun indent-line-to (column)
"Indent current line to COLUMN."
(beginning-of-line 1)
(skip-chars-forward " \t")
(let ((cur-col (current-column)))
(cond ((< cur-col column)
(if (>= (- column (* (/ cur-col tab-width) tab-width)) tab-width)
(delete-region (point)
(progn (skip-chars-backward " ") (point))))
(indent-to column))
((> cur-col column) ; too far right (after tab?)
(delete-region (progn (move-to-column column t) (point))
;; The `move-to-column' call may replace
;; tabs with spaces, so we can't reuse the
;; previous start point.
(progn (beginning-of-line 1)
(skip-chars-forward " \t")
(point)))))))
;; tabify.el
(defun untabify (start end &optional _arg)
"Convert all tabs in region to multiple spaces, preserving columns."
(let ((c (current-column)))
(save-excursion
(save-restriction
(narrow-to-region (point-min) end)
(goto-char start)
(while (search-forward "\t" nil t) ; faster than re-search
(forward-char -1)
(let ((tab-beg (point))
(indent-tabs-mode nil)
column)
(skip-chars-forward "\t")
(setq column (current-column))
(delete-region tab-beg (point))
(indent-to column)))))
(move-to-column c)))
(defvar tabify-regexp " [ \t]+"
"Regexp matching whitespace that tabify should consider.")
(defun tabify (start end &optional _arg)
"Convert multiple spaces in region to tabs when possible."
(save-excursion
(save-restriction
;; Include the beginning of the line in the narrowing
;; since otherwise it will throw off current-column.
(goto-char start)
(beginning-of-line)
(narrow-to-region (point) end)
(goto-char start)
(let ((indent-tabs-mode t))
(while (re-search-forward tabify-regexp nil t)
(let ((end-col (current-column))
(beg-col (save-excursion (goto-char (match-beginning 0))
(skip-chars-forward "\t")
(current-column))))
(if (= (/ end-col tab-width) (/ beg-col tab-width))
nil
(delete-region (match-beginning 0) (point))
(indent-to end-col))))))))
;; replace.el: `keep-lines', `flush-lines', `how-many' (`count-matches').
;; The INTERACTIVE argument only adds the region default and a message.
(defcustom search-upper-case 'not-yanks
"If non-nil, upper case chars disable case fold searching."
:type '(choice (const :tag "off" nil) (const not-yanks) (other :tag "on" t)))
(defun isearch-no-upper-case-p (string regexp-flag)
"Return t if there are no upper case chars in STRING."
(let (quote-flag (i 0) (len (length string)) found)
(while (and (not found) (< i len))
(let ((char (aref string i)))
(if (and regexp-flag (eq char ?\\))
(setq quote-flag (not quote-flag))
(if (and (not quote-flag) (not (eq char (downcase char))))
(setq found t))
(setq quote-flag nil)))
(setq i (1+ i)))
(not (or found
(and regexp-flag (string-match "\\[:\\(upp\\|low\\)er:]" string)
(condition-case err
(progn
(string-match (substring string 0 (match-beginning 0))
"")
nil)
(invalid-regexp
(equal "Unmatched [ or [^" (cadr err)))))))))
(defun keep-lines (regexp &optional rstart rend interactive)
"Delete all lines except those containing matches for REGEXP."
(if rstart
(progn
(goto-char (min rstart rend))
(setq rend
(progn
(save-excursion
(goto-char (max rstart rend))
(unless (or (bolp) (eobp))
(forward-line 0))
(point-marker)))))
(if (and interactive (use-region-p))
(setq rstart (region-beginning)
rend (progn
(goto-char (region-end))
(unless (or (bolp) (eobp))
(forward-line 0))
(point-marker)))
(setq rstart (point)
rend (point-max-marker)))
(goto-char rstart))
(save-excursion
(or (bolp) (forward-line 1))
(let ((start (point))
(case-fold-search
(if (and case-fold-search search-upper-case)
(isearch-no-upper-case-p regexp t)
case-fold-search)))
(while (< (point) rend)
;; Start is first char not preserved by previous match.
(if (not (re-search-forward regexp rend 'move))
(delete-region start rend)
(let ((end (save-excursion (goto-char (match-beginning 0))
(forward-line 0)
(point))))
;; Now end is first char preserved by the new match.
(if (< start end)
(delete-region start end))))
(setq start (save-excursion (forward-line 1) (point)))
;; If the match was empty, avoid matching again at same place.
(and (< (point) rend)
(= (match-beginning 0) (match-end 0))
(forward-char 1)))))
(set-marker rend nil)
nil)
(defun flush-lines (regexp &optional rstart rend interactive)
"Delete lines containing matches for REGEXP; return the number deleted."
(if rstart
(progn
(goto-char (min rstart rend))
(setq rend (copy-marker (max rstart rend))))
(if (and interactive (use-region-p))
(setq rstart (region-beginning)
rend (copy-marker (region-end)))
(setq rstart (point)
rend (point-max-marker)))
(goto-char rstart))
(let ((count 0)
(case-fold-search
(if (and case-fold-search search-upper-case)
(isearch-no-upper-case-p regexp t)
case-fold-search)))
(save-excursion
(while (and (< (point) rend)
(re-search-forward regexp rend t))
(delete-region (save-excursion (goto-char (match-beginning 0))
(forward-line 0)
(point))
(progn (forward-line 1) (point)))
(setq count (1+ count))))
(set-marker rend nil)
(when interactive (message (ngettext "Deleted %d matching line"
"Deleted %d matching lines"
count)
count))
count))
(defalias 'count-matches 'how-many)
;; sort.el. `sort-reorder-buffer' copies through a temporary buffer exactly as
;; sort.el does; elisprs buffers carry no multibyte flag and no modified flag,
;; so `set-buffer-multibyte' and `with-buffer-unmodified-if-unchanged' have
;; nothing to preserve and are left out.
(defcustom sort-fold-case nil
"Non-nil if the buffer sort functions should ignore case."
:type 'boolean)
(defun sort-subr (reverse nextrecfun endrecfun
&optional startkeyfun endkeyfun predicate)
"General text sorting routine to divide buffer into records and sort them."
(save-excursion
(let* ((sort-lists (sort-build-lists nextrecfun endrecfun
startkeyfun endkeyfun))
(old (reverse sort-lists))
(case-fold-search sort-fold-case))
(if (null sort-lists)
()
(or reverse (setq sort-lists (nreverse sort-lists)))
(setq sort-lists
(sort sort-lists
(cond (predicate
(lambda (a b) (funcall predicate (car a) (car b))))
((numberp (car (car sort-lists)))
'car-less-than-car)
((consp (car (car sort-lists)))
(lambda (a b)
(> 0 (compare-buffer-substrings
nil (car (car a)) (cdr (car a))
nil (car (car b)) (cdr (car b))))))
(t
(lambda (a b) (string< (car a) (car b)))))))
(if reverse (setq sort-lists (nreverse sort-lists)))
(sort-reorder-buffer sort-lists old))))
nil)
(defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
(let ((sort-lists ())
(start-rec nil)
done key)
(while (not (eobp))
(setq start-rec (point)) ;save record start
(setq done nil)
;; Get key value, or move to start of key.
(setq key (catch 'key
(or (and startkeyfun (funcall startkeyfun))
;; If key was not returned as value,
;; move to end of key and get key from the buffer.
(let ((start (point)))
(funcall (or endkeyfun
(prog1 endrecfun (setq done t))))
(cons start (point))))))
;; Move to end of this record (start of next one, or end of buffer).
(cond ((prog1 done (setq done nil)))
(endrecfun (funcall endrecfun))
(nextrecfun (funcall nextrecfun) (setq done t)))
(if key (push
;; consing optimization in case in which key is same as record.
(if (and (consp key)
(equal (car key) start-rec)
(equal (cdr key) (point)))
(cons key key)
(cons key (cons start-rec (point))))
sort-lists))
(and (not done) nextrecfun (funcall nextrecfun)))
sort-lists))
(defun sort-reorder-buffer (sort-lists old)
(let ((last (point-min))
(min (point-min)) (max (point-max))
(old-buffer (current-buffer))
temp-buffer)
(with-temp-buffer
(setq temp-buffer (current-buffer))
;; Copy the sorted text into the temporary buffer.
(while sort-lists
(goto-char (point-max))
(insert-buffer-substring old-buffer
last
(nth 1 (car old)))
(goto-char (point-max))
(insert-buffer-substring old-buffer
(nth 1 (car sort-lists))
(cdr (cdr (car sort-lists))))
(setq last (cdr (cdr (car old)))
sort-lists (cdr sort-lists)
old (cdr old)))
(goto-char (point-max))
(insert-buffer-substring old-buffer last max)
;; Copy the reordered text from the temporary buffer
;; to the buffer we sorted (OLD-BUFFER).
(set-buffer old-buffer)
(let ((inhibit-quit t))
;; Leave the last character of the region so markers at its end stay.
(delete-region min (1- max))
;; Now replace the one remaining old character with the sorted text.
(goto-char (point-min))
(insert-buffer-substring temp-buffer)
(delete-region max (1+ max))))))
(defvar inhibit-field-text-motion nil)
(defun sort-lines (reverse beg end)
"Sort lines in region alphabetically; REVERSE non-nil means descending order."
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(let ((inhibit-field-text-motion t))
(sort-subr reverse 'forward-line 'end-of-line)))))
(defvar sort-numeric-base 10
"The default base used by `sort-numeric-fields'.")
(defvar sort-fields-syntax-table nil)
(if sort-fields-syntax-table nil
(let ((table (make-syntax-table))
(i 0))
(while (< i 256)
(modify-syntax-entry i "w" table)
(setq i (1+ i)))
(modify-syntax-entry ?\s " " table)
(modify-syntax-entry ?\t " " table)
(modify-syntax-entry ?\n " " table)
(modify-syntax-entry ?\. "_" table) ; for floating pt. numbers. -wsr
(setq sort-fields-syntax-table table)))
(defun sort-numeric-fields (field beg end)
"Sort lines in region numerically by the FIELDth field of each line."
(let ((inhibit-field-text-motion t))
(sort-fields-1
field beg end
(lambda ()
;; Don't try to parse blank lines (they'll be sorted at the start).
(if (looking-at "[\t ]*$")
0
(sort-skip-fields field)
(let* ((case-fold-search t)
(base
(if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
(cond ((match-beginning 1)
(goto-char (match-end 1))
16)
((match-beginning 2)
(goto-char (match-end 2))
8)
(t nil)))))
(string-to-number (buffer-substring (point)
(save-excursion
(forward-sexp 1)
(point)))
(or base sort-numeric-base)))))
nil)))
(defun sort-fields (field beg end)
"Sort lines in region lexicographically by the FIELDth field of each line."
(let ((inhibit-field-text-motion t))
(sort-fields-1 field beg end
(lambda ()
(sort-skip-fields field)
nil)
(lambda () (skip-chars-forward "^ \t\n")))))
(defun sort-skip-fields (n)
(if (> n 0)
;; Skip across N - 1 fields.
(let ((i (1- n)))
(while (> i 0)
(skip-chars-forward " \t")
(skip-chars-forward "^ \t\n")
(setq i (1- i)))
(skip-chars-forward " \t")
(if (eolp)
(error "Line has too few fields: %s"
(buffer-substring
(line-beginning-position)
(line-end-position)))))
(end-of-line)
;; Skip back across - N - 1 fields.
(let ((i (1- (- n))))
(while (> i 0)
(skip-chars-backward " \t")
(skip-chars-backward "^ \t\n")
(setq i (1- i)))
(skip-chars-backward " \t"))
(if (bolp)
(error "Line has too few fields: %s"
(buffer-substring
(line-beginning-position)
(line-end-position))))
;; Position at the front of the field even if moving backwards.
(skip-chars-backward "^ \t\n")))
(defun sort-fields-1 (field beg end startkeyfun endkeyfun)
(let ((tbl (syntax-table)))
(if (zerop field) (setq field 1))
(unwind-protect
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(set-syntax-table sort-fields-syntax-table)
(sort-subr nil
'forward-line 'end-of-line
startkeyfun endkeyfun)))
(set-syntax-table tbl))))
(defvar sort-regexp-fields-regexp)
(defvar sort-regexp-record-end)
(defun sort-regexp-fields (reverse record-regexp key-regexp beg end)
"Sort the text in the region lexicographically by REGEXP-defined records/keys."
(cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
(setq key-regexp 0))
((string-match "\\`\\\\[1-9]\\'" key-regexp)
(setq key-regexp (- (aref key-regexp 1) ?0))))
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(let (sort-regexp-record-end
(sort-regexp-fields-regexp record-regexp))
(re-search-forward sort-regexp-fields-regexp nil t)
(setq sort-regexp-record-end (point))
(goto-char (match-beginning 0))
(sort-subr reverse
'sort-regexp-fields-next-record
(lambda ()
(goto-char sort-regexp-record-end))
(lambda ()
(let ((n 0))
(cond ((numberp key-regexp)
(setq n key-regexp))
((re-search-forward
key-regexp sort-regexp-record-end t)
(setq n 0))
(t (throw 'key nil)))
(condition-case ()
(cons (match-beginning n)
(match-end n))
;; if there was no such register
(error (throw 'key nil))))))))))
(defun sort-regexp-fields-next-record ()
(let ((oldpos (point)))
(and (re-search-forward sort-regexp-fields-regexp nil 'move)
(setq sort-regexp-record-end (match-end 0))
(if (= sort-regexp-record-end oldpos)
(progn
(forward-char 1)
(re-search-forward sort-regexp-fields-regexp nil 'move)
(setq sort-regexp-record-end (match-end 0)))
t)
(goto-char (match-beginning 0)))))
(defun reverse-region (beg end)
"Reverse the order of lines in a region."
(if (> beg end)
(let (mid) (setq mid end end beg beg mid)))
(save-excursion
;; Put beg at the start of a line and end and the end of one --
;; the largest possible region which fits this criteria.
(goto-char beg)
(or (bolp) (forward-line 1))
(setq beg (point))
(goto-char end)
(or (and (eolp) (not (bolp))) (progn (forward-line -1) (end-of-line)))
(setq end (point-marker))
(when (<= end beg)
(user-error "There are no full lines in the region"))
(let (ll (do t))
(while do
(goto-char beg)
(setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
ll))
(setq do (/= (point) end))
(delete-region beg (if do (1+ (point)) (point))))
(while (cdr ll)
(insert (car ll) "\n")
(setq ll (cdr ll)))
(insert (car ll)))))
(defun delete-duplicate-lines (beg end &optional reverse adjacent keep-blanks
interactive)
"Delete all but one copy of any identical lines in the region; return count."
(let ((lines (unless adjacent (make-hash-table :test 'equal)))
line prev-line first-line
(count 0)
(beg (copy-marker beg))
(end (copy-marker end)))
(save-excursion
(goto-char (if reverse end beg))
(if (and reverse (bolp)) (forward-char -1))
(while (if reverse
(not first-line)
(and (< (point) end) (not (eobp))))
(setq first-line (and reverse (or (<= (point) beg) (bobp))))
(setq line (buffer-substring-no-properties
(line-beginning-position) (line-end-position)))
(if (and keep-blanks (string= "" line))
(forward-line 1)
(if (if adjacent (equal line prev-line) (gethash line lines))
(progn
(delete-region (progn (forward-line 0) (point))
(progn (forward-line 1) (point)))
(if reverse (forward-line -1))
(setq count (1+ count)))
(if adjacent (setq prev-line line) (puthash line t lines))
(forward-line (if reverse -1 1))))))
(set-marker beg nil)
(set-marker end nil)
(when interactive
(message "Deleted %d %sduplicate line%s%s"
count
(if adjacent "adjacent " "")
(if (= count 1) "" "s")
(if reverse " backward" "")))
count))
(defun forward-comment (count)
"Move forward across up to COUNT comments. If COUNT is negative, move backward.
Stop scanning if we find something other than a comment or whitespace.
Set point to where scanning stops.
If COUNT comments are found as expected, with nothing except whitespace
between them, return t; otherwise return nil."
(unless (integerp count) (signal 'wrong-type-argument (list 'fixnump count)))
(let* ((stop (if (> count 0) (point-max) (point-min)))
(from (point))
(comstyle 0) (comnested nil) (count1 count)
c c1 code syntax other-syntax comstart-first found res quoted
(fence-found nil) ini)
(catch '--fc--
(while (> count1 0)
(setq code nil)
(while (or (null code) (= code 0) (and (= code 12) (eq c ?\n)))
(when (= from stop) (goto-char from) (throw '--fc-- nil))
(setq c (char-after from))
(setq syntax (--syntax-flags-at-- from c))
(setq code (logand syntax 255))
(setq comstart-first (--syn-comstart-first-- syntax))
(setq comnested (--syn-nested-- syntax))
(setq comstyle (--syn-comment-style-- syntax 0))
(setq from (1+ from))
(when (and (< from stop) comstart-first)
(setq c1 (char-after from))
(setq other-syntax (--syntax-flags-at-- from c1))
(when (--syn-comstart-second-- other-syntax)
(setq code 11)
(setq comstyle (--syn-comment-style-- other-syntax syntax))
(setq comnested (or comnested (--syn-nested-- other-syntax)))
(setq from (1+ from)))))
(cond ((= code 14) (setq comstyle --st-comment-style--))
((/= code 11)
(setq from (1- from))
(goto-char from)
(throw '--fc-- nil)))
(setq res (--forw-comment-- from stop (if comnested 1 0) comstyle 0))
(setq from (nth 1 res))
(unless (nth 0 res) (goto-char from) (throw '--fc-- nil))
(setq from (1+ from))
(setq count1 (1- count1)))
(while (< count1 0)
(catch '--fc-one--
(while t
(when (<= from stop) (goto-char (point-min)) (throw '--fc-- nil))
(setq from (1- from))
(setq quoted (--char-quoted-- from))
(setq c (char-after from))
(setq syntax (--syntax-flags-at-- from c))
(setq code (logand syntax 255))
(setq comstyle 0)
(setq comnested (--syn-nested-- syntax))
(when (= code 12) (setq comstyle (--syn-comment-style-- syntax 0)))
(when (and (> from stop) (--syn-comend-second-- syntax)
(--prev-char-comend-first-- from)
(not (--char-quoted-- (1- from))))
(setq from (1- from))
(setq code 12)
(setq c1 (char-after from))
(setq other-syntax (--syntax-flags-at-- from c1))
(setq comstyle (--syn-comment-style-- other-syntax syntax))
(setq comnested (or comnested (--syn-nested-- other-syntax))))
(cond
((= code 14) ; Scomment_fence
(setq fence-found nil)
(setq ini from)
(when (> from stop)
(catch '--fc-fence--
(while t
(setq from (1- from))
(setq c (char-after from))
(cond ((and (= (--syntax-code-at-- from c) 14)
(not (--char-quoted-- from)))
(setq fence-found t)
(throw '--fc-fence-- nil))
((= from stop) (throw '--fc-fence-- nil))))))
(if fence-found
(throw '--fc-one-- nil)
(setq from ini)
(setq from (1+ from))
(goto-char from)
(throw '--fc-- nil)))
((= code 12) ; Sendcomment
(setq found (and (or (not quoted) (not comment-end-can-be-escaped))
(--back-comment-- from stop comnested comstyle)))
(if (and found (nth 0 found))
(progn (setq from (nth 1 found)) (throw '--fc-one-- nil))
(unless (eq c ?\n)
;; Go back to the end of this not-quite-endcomment.
(when (/= (--syntax-code-at-- from (char-after from)) code)
(setq from (1+ from)))
(setq from (1+ from))
(goto-char from)
(throw '--fc-- nil))))
((or (/= code 0) quoted)
(setq from (1+ from))
(goto-char from)
(throw '--fc-- nil)))))
(setq count1 (1+ count1)))
(goto-char from)
t)))
;; ---- parse-partial-sexp (syntax.c Fparse_partial_sexp) ----
(defun parse-partial-sexp (from to &optional targetdepth stopbefore oldstate commentstop)
"Parse Lisp syntax starting at FROM until TO; return status of parse at TO.
Parsing stops at TO or when certain criteria are met;
point is set to where parsing stops.
If OLDSTATE is omitted or nil, parsing assumes that FROM is the
beginning of a function. If not, OLDSTATE should be the state at FROM."
(let ((target (if targetdepth
(progn
(unless (integerp targetdepth)
(signal 'wrong-type-argument (list 'fixnump targetdepth)))
targetdepth)
--pps-no-target--))
(f (if (markerp from) (marker-position from) from))
(t2 (if (markerp to) (marker-position to) to))
state)
(when (< t2 f) (error "End position is smaller than start position"))
;; `validate_region' (editfns.c) rejects an out-of-range pair outright --
;; it does not clamp -- and names the buffer and the arguments AS PASSED:
;; (parse-partial-sexp 1 40) in an empty buffer
;; => (args-out-of-range #<buffer *scratch*> 1 40)
;; Clamping instead makes the call answer a plausible state for a region
;; that does not exist.
(unless (and (<= (point-min) f) (<= t2 (point-max)))
(signal 'args-out-of-range (list (current-buffer) from to)))
(setq state (--pps-internalize-- oldstate))
(--scan-sexps-forward-- state f t2 target (and stopbefore t)
(cond ((null commentstop) 0)
((eq commentstop 'syntax-table) -1)
(t 1)))
(goto-char (--pps-location-- state))
(list (--pps-depth-- state)
(if (< (--pps-prevlevelstart-- state) 0) nil (--pps-prevlevelstart-- state))
(if (< (--pps-thislevelstart-- state) 0) nil (--pps-thislevelstart-- state))
(if (>= (--pps-instring-- state) 0)
(if (= (--pps-instring-- state) --st-string-style--)
t
(--pps-instring-- state))
nil)
(cond ((< (--pps-incomment-- state) 0) t)
((= (--pps-incomment-- state) 0) nil)
(t (--pps-incomment-- state)))
(and (--pps-quoted-- state) t)
(--pps-mindepth-- state)
(if (= (--pps-comstyle-- state) 0)
nil
(if (= (--pps-comstyle-- state) --st-comment-style--)
'syntax-table
(--pps-comstyle-- state)))
(if (or (/= (--pps-incomment-- state) 0)
(>= (--pps-instring-- state) 0))
(--pps-comstr-start-- state)
nil)
(--pps-levelstarts-- state)
(if (= (--pps-prev-syntax-- state) --syn-smax--)
nil
(--pps-prev-syntax-- state)))))
;; ---- cl-macs.el (31.1) lambda-list machinery, verbatim ----
;; `cl-defun', `cl-defmacro' and `cl-function' are `cl--transform-lambda': the
;; leading plain arguments stay in the lambda list (so a simple arglist is an
;; ordinary function and its arity errors name the closure), the rest arrive as
;; `&rest --cl-rest--' and are parsed by the code `cl--do-arglist' generates,
;; which signals `(wrong-number-of-arguments NAME N)' and the keyword errors
;; Emacs signals; and the body is wrapped in `(cl-block NAME ...)'. Placed
;; before the first top-level `cl-defstruct' (`ppss', below), whose
;; constructor is a `cl-defsubst', because
;; elisprs expands macros when a form is defined.
;; macroexp.el, needed by `cl--transform-lambda' at the first expansion.
(defun macroexp-parse-body (body)
"Parse a function BODY into (DECLARATIONS . EXPS)."
(let ((decls ()))
(while
(and body
(let ((e (car body)))
(or (and (stringp e) (cdr body))
(memq (car-safe e)
'(:documentation declare interactive cl-declare)))))
(push (pop body) decls))
(cons (nreverse decls) body)))
(defvar cl--bind-block) (defvar cl--bind-defs) (defvar cl--bind-enquote)
(defvar cl--bind-lets) (defvar cl--bind-forms)
(defconst cl--lambda-list-keywords
'(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
;; cl-macs.el: the variables a cl lambda list binds -- what `cl-defstruct' uses
;; to tell a slot that a constructor argument names from one it fills itself.
(defun cl--arglist-args (args)
(if (nlistp args) (list args)
(let ((res nil) (kind nil) arg)
(while (consp args)
(setq arg (pop args))
(if (memq arg cl--lambda-list-keywords) (setq kind arg)
(if (eq arg '&cl-defs) (pop args)
(and (consp arg) kind (setq arg (car arg)))
(and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
(setq res (nconc res (cl--arglist-args arg))))))
(nconc res (and args (list args))))))
(defmacro cl--pop2 (place)
`(prog1 (car (cdr ,place))
(setq ,place (cdr (cdr ,place)))))
(defun cl--const-expr-p (x)
"Check if X is constant (i.e., no side effects or dependencies).
See `macroexp-const-p' for similar functionality without cl-lib dependency."
(cond ((consp x)
(or (eq (car x) 'quote)
(and (memq (car x) '(function cl-function))
(or (symbolp (nth 1 x))
(and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
((symbolp x) (and (memq x '(nil t)) t))
(t t)))
(defun cl--const-expr-val (x)
"Return the value of X known at compile-time.
If X is not known at compile time, return nil. Before testing
whether X is known at compile time, macroexpand it completely in
`macroexpand-all-environment'."
(let ((x (macroexpand-all x macroexpand-all-environment)))
(if (macroexp-const-p x)
(if (consp x) (nth 1 x) x))))
;; macroexp.el (31.1).
(defun macroexp--dynamic-variable-p (var)
"Whether the variable VAR is dynamically scoped.
Only valid during macro-expansion."
(or (not lexical-binding)
(special-variable-p var)
(memq var macroexp--dynvars)
(and (boundp 'byte-compile-bound-variables)
(memq var byte-compile-bound-variables))))
(defun cl--slet (bindings body &optional nowarn)
"Like `cl--slet*' but for \"parallel let\"."
(let ((dyns nil)) ;Vars declared as dynbound among the bindings?
(when lexical-binding
(dolist (binding bindings) ;; `seq-some' lead to bootstrap problems.
(when (macroexp--dynamic-variable-p (car binding))
(push (car binding) dyns))))
(cond
(dyns
(let ((form `(funcall (lambda (,@(mapcar #'car bindings))
,@(macroexp-unprogn body))
,@(mapcar #'cadr bindings))))
(if (not nowarn) form
`(with-suppressed-warnings ((lexical ,@dyns)) ,form))))
((null (cdr bindings))
(macroexp-let* bindings body))
(t `(let ,bindings ,@(macroexp-unprogn body))))))
(defun cl--slet* (bindings body)
"Like `macroexp-let*' but uses static scoping for all the BINDINGS."
(if (null bindings) body
(cl--slet `(,(car bindings)) (cl--slet* (cdr bindings) body))))
(defun cl--transform-lambda (form bind-block)
"Transform a function form FORM of name BIND-BLOCK.
BIND-BLOCK is the name of the symbol to which the function will be bound,
and which will be used for the name of the `cl-block' surrounding the
function's body.
FORM is of the form (ARGS . BODY)."
(let* ((args (car form)) (body (cdr form)) (orig-args args)
(cl--bind-block bind-block) (cl--bind-defs nil) (cl--bind-enquote nil)
(parsed-body (macroexp-parse-body body))
(header (car parsed-body)) (simple-args nil))
(setq body (cdr parsed-body))
;; "(. X) to (&rest X)" conversion already done in cl--do-arglist, but we
;; do it here as well, so as to be able to see if we can avoid
;; cl--do-arglist.
(setq args (if (listp args) (cl-copy-list args) (list '&rest args)))
(let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
(let ((cl-defs (memq '&cl-defs args)))
(when cl-defs
(setq cl--bind-defs (cadr cl-defs))
;; Remove "&cl-defs DEFS" from args.
(setcdr cl-defs (cddr cl-defs))
(setq args (delq '&cl-defs args))))
(if (setq cl--bind-enquote (memq '&cl-quote args))
(setq args (delq '&cl-quote args)))
(if (memq '&whole args) (error "&whole not currently implemented"))
(let* ((p (memq '&environment args))
(v (cadr p)))
(if p (setq args (nconc (delq (car p) (delq v args))
`(&aux (,v macroexpand-all-environment))))))
;; Take away all the simple args whose parsing can be handled more
;; efficiently by a plain old `lambda' than the manual parsing generated
;; by `cl--do-arglist'.
(let ((optional nil))
(while (and args (symbolp (car args))
(not (memq (car args) '(nil &rest &body &key &aux)))
(or (not optional)
;; Optional args whose default is nil are simple.
(null (nth 1 (assq (car args) (cdr cl--bind-defs)))))
(not (and (eq (car args) '&optional) (setq optional t)
(car cl--bind-defs))))
(push (pop args) simple-args))
(when optional
(if args (push '&optional args))
;; Don't keep a dummy trailing &optional without actual optional args.
(if (eq '&optional (car simple-args)) (pop simple-args))))
(or (eq cl--bind-block 'cl-none)
(setq body (list `(cl-block ,cl--bind-block ,@body))))
(let* ((cl--bind-lets nil) (cl--bind-forms nil)
(rest-args
(cond
((null args) nil)
((eq (car args) '&aux)
(cl--do-&aux args)
(setq cl--bind-lets (nreverse cl--bind-lets))
nil)
(t ;; `simple-args' doesn't handle all the parsing that we need,
;; so we pass the rest to cl--do-arglist which will do
;; "manual" parsing.
(let ((slen (length simple-args))
(usage-str
;; Macro expansion can take place in the middle of
;; apparently harmless computation, so it should not
;; touch the match-data.
(save-match-data
;; (require (quote help)) -- help.el is preloaded.
(help--docstring-quote
(let ((print-gensym nil) (print-quoted t)
(print-escape-newlines t))
(format "%S" (cons 'fn (cl--make-usage-args
orig-args))))))))
(when (memq '&optional simple-args)
(decf slen))
(setq header
(cons
(if (eq :documentation (car-safe (car header)))
`(:documentation (help-add-fundoc-usage
,(cadr (pop header))
,usage-str))
(help-add-fundoc-usage
(if (stringp (car header)) (pop header))
;; Be careful with make-symbol and (back)quote,
;; see bug#12884.
usage-str))
header))
;; FIXME: we'd want to choose an arg name for the &rest param
;; and pass that as `expr' to cl--do-arglist, but that ends up
;; generating code with a redundant let-binding, so we instead
;; pass a dummy and then look in cl--bind-lets to find what var
;; this was bound to.
(cl--do-arglist args :dummy slen)
(setq cl--bind-lets (nreverse cl--bind-lets))
;; (cl-assert (eq :dummy (nth 1 (car cl--bind-lets))))
(list '&rest (car (pop cl--bind-lets))))))))
`((,@(nreverse simple-args) ,@rest-args)
,@header
;; Function arguments are unconditionally statically scoped (bug#47552).
,(cl--slet* cl--bind-lets
(macroexp-progn
`(,@(nreverse cl--bind-forms)
,@body)))))))
(defmacro cl-defun (name args &rest body)
"Define NAME as a function.
Like normal `defun', except ARGLIST allows full Common Lisp conventions,
and BODY is implicitly surrounded by (cl-block NAME ...).
\(fn NAME ARGLIST [DOCSTRING] BODY...)"
(declare (doc-string 3) (indent 2))
`(defun ,name ,@(cl--transform-lambda (cons args body) name)))
(defmacro cl-defmacro (name args &rest body)
"Define NAME as a macro.
Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
and BODY is implicitly surrounded by (cl-block NAME ...).
\(fn NAME ARGLIST [DOCSTRING] BODY...)"
(declare (doc-string 3) (indent 2))
`(defmacro ,name ,@(cl--transform-lambda (cons args body) name)))
(defmacro cl-function (func)
"Introduce a function.
Like normal `function', except that if argument is a lambda form,
its argument list allows full Common Lisp conventions."
(if (eq (car-safe func) 'lambda)
`(function (lambda . ,(cl--transform-lambda (cdr func) 'cl-none)))
`(function ,func)))
(defun cl--make-usage-var (x)
"X can be a var or a (destructuring) lambda-list."
(cond
((symbolp x) (make-symbol (upcase (symbol-name x))))
((consp x) (cl--make-usage-args x))
(t x)))
(defun cl--make-usage-args (arglist)
(let ((aux (ignore-errors (cl-position '&aux arglist))))
(when aux
;; `&aux' args aren't arguments, so let's just drop them from the
;; usage info.
(setq arglist (take aux arglist))))
(if (not (proper-list-p arglist))
(let* ((last (last arglist))
(tail (cdr last)))
(unwind-protect
(progn
(setcdr last nil)
(nconc (cl--make-usage-args arglist) (cl--make-usage-var tail)))
(setcdr last tail)))
;; `orig-args' can contain &cl-defs.
(let ((x (memq '&cl-defs arglist)))
(when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
(let ((state nil))
(mapcar (lambda (x)
(cond
((symbolp x)
(let ((first (aref (symbol-name x) 0)))
(if (eq ?\& first)
(setq state x)
;; Strip a leading underscore, since it only
;; means that this argument is unused.
(make-symbol (upcase (if (eq ?_ first)
(substring (symbol-name x) 1)
(symbol-name x)))))))
((not (consp x)) x)
((memq state '(nil &rest)) (cl--make-usage-args x))
(t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
(cl-list*
(if (and (consp (car x)) (eq state '&key))
(list (caar x) (cl--make-usage-var (nth 1 (car x))))
(cl--make-usage-var (car x)))
(nth 1 x) ;INITFORM.
(cl--make-usage-args (nthcdr 2 x)) ;SVAR.
))))
arglist))))
(defun cl--do-&aux (args)
(while (and (eq (car args) '&aux) (pop args))
(while (and args (not (memq (car args) cl--lambda-list-keywords)))
(if (consp (car args))
(if (and cl--bind-enquote (cadar args))
(cl--do-arglist (caar args)
`',(cadr (pop args)))
(cl--do-arglist (caar args) (cadr (pop args))))
(cl--do-arglist (pop args) nil))))
(if args (error "Malformed argument list ends with: %S" args)))
(defun cl--do-arglist (args expr &optional num) ; uses cl--bind-*
(if (nlistp args)
(if (or (memq args cl--lambda-list-keywords) (not (symbolp args)))
(error "Invalid argument name: %s" args)
(push (list args expr) cl--bind-lets))
(setq args (cl-copy-list args))
(let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
(let ((p (memq '&body args))) (if p (setcar p '&rest)))
(if (memq '&environment args) (error "&environment used incorrectly"))
(let ((restarg (memq '&rest args))
(safety (if (macroexp-compiling-p) cl--optimize-safety 3))
(keys t)
(laterarg nil) (exactarg nil) minarg)
(or num (setq num 0))
(setq restarg (if (listp (cadr restarg))
(make-symbol "--cl-rest--")
(cadr restarg)))
(push (list restarg expr) cl--bind-lets)
(if (eq (car args) '&whole)
(push (list (cl--pop2 args) restarg) cl--bind-lets))
(let ((p args))
(setq minarg restarg)
(while (and p (not (memq (car p) cl--lambda-list-keywords)))
(or (eq p args) (setq minarg (list 'cdr minarg)))
(setq p (cdr p)))
(if (memq (car p) '(nil &aux))
(setq minarg `(= (length ,restarg)
,(length (cl-ldiff args p)))
exactarg (not (eq args p)))))
(while (and args (not (memq (car args) cl--lambda-list-keywords)))
(let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car-safe)
restarg)))
(cl--do-arglist
(pop args)
(if (or laterarg (= safety 0)) poparg
`(if ,minarg ,poparg
(signal 'wrong-number-of-arguments
(list ,(and (not (eq cl--bind-block 'cl-none))
`',cl--bind-block)
(length ,restarg)))))))
(setq num (1+ num) laterarg t))
(while (and (eq (car args) '&optional) (pop args))
(while (and args (not (memq (car args) cl--lambda-list-keywords)))
(let ((arg (pop args)))
(or (consp arg) (setq arg (list arg)))
(if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
(let ((def (if (cdr arg) (nth 1 arg)
(or (car cl--bind-defs)
(nth 1 (assq (car arg) cl--bind-defs)))))
(poparg `(pop ,restarg)))
(and def cl--bind-enquote (setq def `',def))
(cl--do-arglist (car arg)
(if def `(if ,restarg ,poparg ,def) poparg))
(setq num (1+ num))))))
(if (eq (car args) '&rest)
(let ((arg (cl--pop2 args)))
(if (consp arg) (cl--do-arglist arg restarg)))
(or (eq (car args) '&key) (= safety 0) exactarg
(push `(if ,restarg
(signal 'wrong-number-of-arguments
(list
,(and (not (eq cl--bind-block 'cl-none))
`',cl--bind-block)
(+ ,num (length ,restarg)))))
cl--bind-forms)))
(while (and (eq (car args) '&key) (pop args))
(unless (listp keys) (setq keys nil))
(while (and args (not (memq (car args) cl--lambda-list-keywords)))
(let ((arg (pop args)))
(or (consp arg) (setq arg (list arg)))
(let* ((karg (if (consp (car arg)) (caar arg)
(let ((name (symbol-name (car arg))))
;; Strip a leading underscore, since it only
;; means that this argument is unused, but
;; shouldn't affect the key's name (bug#12367).
(if (eq ?_ (aref name 0))
(setq name (substring name 1)))
(intern (format ":%s" name)))))
(varg (if (consp (car arg)) (cadar arg) (car arg)))
(def (if (cdr arg) (cadr arg)
;; The ordering between those two or clauses is
;; irrelevant, since in practice only one of the two
;; is ever non-nil (the car is only used for
;; cl-deftype which doesn't use the cdr).
(or (car cl--bind-defs)
(cadr (assq varg cl--bind-defs)))))
(look `(plist-member ,restarg ',karg)))
(and def cl--bind-enquote (setq def `',def))
(if (cddr arg)
(let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
(val `(car (cdr ,temp))))
(cl--do-arglist temp look)
(cl--do-arglist varg
`(if ,temp
(prog1 ,val (setq ,temp t))
,def)))
(cl--do-arglist
varg
`(car (cdr ,(if (null def)
look
`(or ,look
,(if (eq (cl--const-expr-p def) t)
`'(nil ,(cl--const-expr-val def))
`(list nil ,def))))))))
(push karg keys)))))
(when (consp keys) (setq keys (nreverse keys)))
(or (and (eq (car args) '&allow-other-keys) (pop args))
(= safety 0)
(cond
((eq keys t) nil) ;No &keys at all
((null keys) ;A &key but no actual keys specified.
(push `(when ,restarg
(error ,(format "Keyword argument %%S not one of %S"
keys)
(car ,restarg)))
cl--bind-forms))
(t
(let* ((var (make-symbol "--cl-keys--"))
(allow '(:allow-other-keys))
(check `(while ,var
(cond
((memq (car ,var) ',(append keys allow))
(unless (cdr ,var)
(error "Missing argument for %s" (car ,var)))
(setq ,var (cdr (cdr ,var))))
((car (cdr (memq (quote ,@allow) ,restarg)))
(setq ,var nil))
(t
(error
,(format "Keyword argument %%S not one of %S"
keys)
(car ,var)))))))
(push `(let ((,var ,restarg)) ,check) cl--bind-forms)))))
(cl--do-&aux args)
nil)))
;; ---- syntax.el: the ppss accessors, syntax-propertize and syntax-ppss ----
(cl-defstruct (ppss (:constructor make-ppss) (:copier nil) (:type list))
(depth nil) (innermost-start nil) (last-complete-sexp-start nil)
(string-terminator nil) (comment-depth nil) (quoted-p nil)
(min-depth nil) (comment-style nil) (comment-or-string-start nil)
(open-parens nil) (two-character-syntax nil))
(defvar-local syntax-propertize-function nil
"Mode-specific function to apply `syntax-table' text properties.")
(defvar-local syntax-propertize--done -1
"Position up to which syntax-table properties have been set.")
(defvar-local syntax-ppss-table nil
"Syntax-table to use during `syntax-ppss', if any.")
(defun syntax-propertize (pos)
"Ensure that syntax-table properties are set until POS (a buffer point)."
(when (and syntax-propertize-function
(< syntax-propertize--done pos))
(let ((start (max (point-min) syntax-propertize--done))
(end (min (point-max) pos)))
(setq syntax-propertize--done end)
(save-excursion (funcall syntax-propertize-function start end))))
nil)
(defun syntax-ppss-depth (ppss) (nth 0 ppss))
(defun syntax-ppss-toplevel-pos (ppss)
"Get the latest syntactically outermost position found in a syntactic scan.
PPSS is a scan state, as returned by `parse-partial-sexp' or `syntax-ppss'."
(or (car (nth 9 ppss)) (nth 8 ppss)))
(defun syntax-ppss-context (ppss)
"Say whether PPSS is a string, a comment, or something else."
(cond ((nth 3 ppss) 'string) ((nth 4 ppss) 'comment) (t nil)))
(defun syntax-ppss-flush-cache (_beg &rest _ignored)
"Flush the `syntax-ppss' cache from BEG onward."
nil)
;; NAMED boundary: Emacs memoizes the parse in `syntax-ppss-last' and
;; `syntax-ppss-cache' and restarts from the nearest cached position, so its
;; elements 2 and 6 depend on where the cache happened to have an entry -- which
;; is exactly why its docstring says those two "cannot be relied upon". This
;; parses from `point-min' every time, which is what Emacs itself does on a cold
;; cache, so every element including 2 and 6 matches a first call in a fresh
;; buffer. The difference is speed, and element 2/6 drift that Emacs already
;; disclaims.
(defun syntax-ppss (&optional pos)
"Parse-Partial-Sexp State at POS, defaulting to point.
If POS is given, this function moves point to POS.
The returned value is the same as that of `parse-partial-sexp'
run from `point-min' to POS except that values at positions 2 and 6
in the returned list (counting from 0) cannot be relied upon."
(unless pos (setq pos (point)))
(syntax-propertize pos)
(with-syntax-table (or syntax-ppss-table (syntax-table))
(parse-partial-sexp (point-min) pos)))
;; ---- lisp.el: sexp and list motion ----
(defvar forward-sexp-function nil
"If non-nil, `forward-sexp' delegates to this function.
Should take the same arguments and behave similarly to `forward-sexp'.")
(defun forward-sexp-default-function (&optional arg)
"Default function for `forward-sexp-function'."
(goto-char (or (scan-sexps (point) arg) (buffer-end arg)))
(if (< arg 0) (backward-prefix-chars)))
(defun forward-sexp (&optional arg interactive)
"Move forward across one balanced expression (sexp).
With ARG, do it that many times. Negative arg -N means move
backward across N balanced expressions. This command assumes
point is not in a string or comment. Calls
`forward-sexp-function' to do the work, if that is non-nil."
(if interactive
(condition-case _
(forward-sexp arg nil)
(scan-error (user-error (if (> arg 0) "No next sexp" "No previous sexp"))))
(or arg (setq arg 1))
(if forward-sexp-function
(funcall forward-sexp-function arg)
(forward-sexp-default-function arg))))
(defun backward-sexp (&optional arg interactive)
"Move backward across one balanced expression (sexp).
With ARG, do it that many times. Negative arg -N means
move forward across N balanced expressions."
(or arg (setq arg 1))
(forward-sexp (- arg) interactive))
(defun forward-list (&optional arg interactive)
"Move forward across one balanced group of parentheses.
With ARG, do it that many times.
Negative arg -N means move backward across N groups of parentheses."
(if interactive
(condition-case _
(forward-list arg nil)
(scan-error (user-error (if (> arg 0) "No next group" "No previous group"))))
(or arg (setq arg 1))
(goto-char (or (scan-lists (point) arg 0) (buffer-end arg)))))
(defun backward-list (&optional arg interactive)
"Move backward across one balanced group of parentheses.
With ARG, do it that many times.
Negative arg -N means move forward across N groups of parentheses."
(or arg (setq arg 1))
(forward-list (- arg) interactive))
(defun down-list (&optional arg interactive)
"Move forward down one level of parentheses.
With ARG, do this that many times.
A negative argument means move backward but still go down a level."
(when (ppss-comment-or-string-start (syntax-ppss))
(user-error "This command doesn't work in strings or comments"))
(if interactive
(condition-case _
(down-list arg nil)
(scan-error (user-error "At bottom level")))
(or arg (setq arg 1))
(let ((inc (if (> arg 0) 1 -1)))
(while (/= arg 0)
(goto-char (or (scan-lists (point) inc -1) (buffer-end arg)))
(setq arg (- arg inc))))))
(defun backward-up-list (&optional arg escape-strings no-syntax-crossing)
"Move backward out of one level of parentheses.
With ARG, do this that many times. A negative argument means move
forward but still to a less deep spot."
(up-list (- (or arg 1)) escape-strings no-syntax-crossing))
(defun up-list (&optional arg escape-strings no-syntax-crossing)
"Move forward out of one level of parentheses.
With ARG, do this that many times. A negative argument means move
backward but still to a less deep spot."
(or arg (setq arg 1))
(let ((inc (if (> arg 0) 1 -1))
(pos nil))
(while (/= arg 0)
(condition-case err
(save-restriction
;; If we've been asked not to cross string boundaries and we're
;; inside a string, narrow to that string so that scan-lists
;; doesn't find a match in a different string.
(when no-syntax-crossing
(let* ((syntax (syntax-ppss))
(string-comment-start (nth 8 syntax)))
(when string-comment-start
(save-excursion
(goto-char string-comment-start)
(narrow-to-region
(point)
(if (nth 3 syntax)
(condition-case nil
(progn (forward-sexp) (point))
(scan-error (point-max)))
(forward-comment 1)
(point)))))))
(if (null forward-sexp-function)
(goto-char (or (scan-lists (point) inc 1) (buffer-end arg)))
(condition-case err2
(while (progn (setq pos (point))
(forward-sexp inc)
(/= (point) pos)))
(scan-error (goto-char (nth (if (> arg 0) 3 2) err2))))
(if (= (point) pos)
(signal 'scan-error
(list "Unbalanced parentheses" (point) (point))))))
(scan-error
(let ((syntax nil))
(or
(and escape-strings
(or syntax (setq syntax (syntax-ppss)))
(nth 3 syntax)
(goto-char (nth 8 syntax))
(progn (when (> inc 0) (forward-sexp)) t))
(and no-syntax-crossing
(or syntax (setq syntax (syntax-ppss)))
(nth 4 syntax)
(goto-char (nth 8 syntax))
(or (< inc 0) (forward-comment 1))
(setq arg (+ arg inc)))
(if no-syntax-crossing
(user-error "At top level")
(signal (car err) (cdr err)))))))
(setq arg (- arg inc)))))
;; ---- Lisp-mode syntax tables (lisp-mode.el / elisp-mode.el) ----
;; Pure make-syntax-table + modify-syntax-entry constructions; ported verbatim so
;; libraries that base their own parse tables on them (ietf-drums, rfc2047, the
;; url-* parsers, mail-parse) load with the exact upstream syntax classes.
(defvar lisp-data-mode-syntax-table
(let ((table (make-syntax-table))
(i 0))
(while (< i ?0)
(modify-syntax-entry i "_ " table)
(setq i (1+ i)))
(setq i (1+ ?9))
(while (< i ?A)
(modify-syntax-entry i "_ " table)
(setq i (1+ i)))
(setq i (1+ ?Z))
(while (< i ?a)
(modify-syntax-entry i "_ " table)
(setq i (1+ i)))
(setq i (1+ ?z))
(while (< i 128)
(modify-syntax-entry i "_ " table)
(setq i (1+ i)))
(modify-syntax-entry ?\s " " table)
;; Non-break space acts as whitespace.
(modify-syntax-entry ?\xa0 " " table)
(modify-syntax-entry ?\t " " table)
(modify-syntax-entry ?\f " " table)
(modify-syntax-entry ?\n "> " table)
(modify-syntax-entry ?\; "< " table)
(modify-syntax-entry ?` "' " table)
(modify-syntax-entry ?' "' " table)
(modify-syntax-entry ?, "' " table)
(modify-syntax-entry ?@ "_ p" table)
;; Used to be singlequote; changed for flonums.
(modify-syntax-entry ?. "_ " table)
(modify-syntax-entry ?# "' " table)
(modify-syntax-entry ?\" "\" " table)
(modify-syntax-entry ?\\ "\\ " table)
(modify-syntax-entry ?\( "() " table)
(modify-syntax-entry ?\) ")( " table)
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
table)
"Parent syntax table used in Lisp modes.")
(defvar lisp-mode-syntax-table
(let ((table (make-syntax-table lisp-data-mode-syntax-table)))
(modify-syntax-entry ?\[ "_ " table)
(modify-syntax-entry ?\] "_ " table)
(modify-syntax-entry ?# "' 14" table)
(modify-syntax-entry ?| "\" 23bn" table)
table)
"Syntax table used in `lisp-mode'.")
(defvar emacs-lisp-mode-syntax-table
(let ((table (make-syntax-table lisp-data-mode-syntax-table)))
;; Remove the "p" flag from the entry of `@' because we use instead
;; `syntax-propertize' to take care of `,@', which is more precise.
(modify-syntax-entry ?@ "_" table)
table)
"Syntax table used in `emacs-lisp-mode'.")
;; `emacs -Q --batch' starts in `*scratch*', and `initial-major-mode' puts that
;; buffer in `lisp-interaction-mode' -- a `define-derived-mode' child of
;; `emacs-lisp-mode', so it inherits that mode's syntax table. Every
;; `char-syntax' / `\sC' answer a batch script sees therefore comes from the
;; elisp table, not from `standard-syntax-table':
;;
;; emacs -Q --batch --eval '(prin1 (list (char-syntax ?\;) (char-syntax ?.) \
;; (char-syntax ?$) (char-syntax ?{)))'
;; => (60 95 95 95)
;;
;; where the standard table answers (46 46 119 40). Install it as the initial
;; buffer's table so the prelude's own forms read the elisp table. The mode
;; itself comes later: `prelude_31::STARTUP_SCRATCH' runs `initial-major-mode'
;; in `*scratch*' once elisp-mode.el has loaded, which installs
;; `lisp-interaction-mode-syntax-table' (a child of this one) over it.
(set-syntax-table emacs-lisp-mode-syntax-table)
;; ---- abbrev tables (abbrev.el) ----
;; An abbrev table IS an obarray: each abbrev is a symbol interned in it whose
;; VALUE is the expansion, and the table's own properties live on the symbol
;; named "" interned in the same table. This used to be a documented
;; placeholder built on a plain vector with a side-table for the properties,
;; because elisprs had no obarrays; it does now, so this is the real thing and
;; `(abbrev-table-p (make-abbrev-table))' and `(obarrayp ...)' both answer t
;; while a bare `(obarray-make)' answers nil to the first.
(defun obarray-get (ob name) (intern-soft name ob))
(defun obarray-put (ob name) (intern name ob))
(defun obarray-map (fn ob) (mapatoms fn ob))
(defun abbrev-table-get (table prop)
"Get the property PROP of abbrev table TABLE."
(let ((sym (obarray-get table ""))) (if sym (get sym prop))))
(defun abbrev-table-put (table prop val)
"Set the property PROP of abbrev table TABLE to VAL."
(let ((sym (obarray-put table "")))
(set sym nil) ; so it is never mistaken for an abbrev
(put sym prop val)))
(defun make-abbrev-table (&optional props)
"Create a new, empty abbrev table object.
PROPS is a list of properties."
(let ((table (obarray-make)))
;; The `modiff' counter doubles as the tag that says this obarray is an
;; abbrev table -- which is how `abbrev-table-p' tells the two apart.
(abbrev-table-put table :abbrev-table-modiff 0)
(while (consp props)
(abbrev-table-put table (pop props) (pop props)))
table))
(defun abbrev-table-p (object)
"Return non-nil if OBJECT is an abbrev table."
(and (obarrayp object)
(numberp (ignore-error wrong-type-argument
(abbrev-table-get object :abbrev-table-modiff)))))
(defun abbrev-table-empty-p (object &optional ignore-system)
"Return nil if there are any abbrev symbols in OBJECT.
The table's own \"\" property symbol does not count."
(unless (abbrev-table-p object) (error "Non abbrev table object"))
(not (catch 'some
(obarray-map (lambda (abbrev)
(unless (or (zerop (length (symbol-name abbrev)))
(and ignore-system (abbrev-get abbrev :system)))
(throw 'some t)))
object))))
(defalias 'abbrev-get #'get)
(defalias 'abbrev-put #'put)
(defvar abbrev-minor-mode-table-alist nil
"Alist of abbrev tables to use for minor modes.")
(defvar abbrev-table-name-list '(global-abbrev-table)
"List of symbols whose values are abbrev tables.")
(defun define-abbrev (table name expansion &optional hook &rest props)
"Define an abbrev NAME in TABLE expanding to EXPANSION.
Answers the abbrev's symbol, whose VALUE is the expansion -- which is what
`abbrev-expansion' reads back."
(declare (indent defun))
;; The obsolete positional calling convention: (… HOOK COUNT SYSTEM).
(when (and (consp props) (or (null (car props)) (numberp (car props))))
(setq props (append (list :count (car props))
(if (nth 1 props) (list :system (nth 1 props))))))
(unless (plist-get props :count) (setq props (plist-put props :count 0)))
(setq props (plist-put props :abbrev-table-modiff
(abbrev-table-get table :abbrev-table-modiff)))
(let ((sym (obarray-put table name)))
(set sym expansion)
(fset sym hook)
(setplist sym props)
(abbrev-table-put table :abbrev-table-modiff
(1+ (abbrev-table-get table :abbrev-table-modiff)))
sym))
(defun abbrev-symbol (abbrev &optional table)
"The symbol representing ABBREV in TABLE (default the global table)."
(let ((sym (obarray-get (or table global-abbrev-table) abbrev)))
(and sym (symbol-value sym) sym)))
(defun abbrev-expansion (abbrev &optional table)
"Return the string ABBREV expands into, or nil."
(let ((sym (abbrev-symbol abbrev table)))
(and sym (symbol-value sym))))
(defvar global-abbrev-table (make-abbrev-table)
"The abbrev table whose abbrevs affect all buffers.")
(defun define-abbrev-table (tablename &optional definitions _docstring &rest props)
"Define TABLENAME as an abbrev table name, with DEFINITIONS in it.
Answers nil, as Emacs does -- the table is reached through the variable."
(declare (doc-string 3) (indent defun))
(unless (and (boundp tablename) (abbrev-table-p (symbol-value tablename)))
(set tablename (make-abbrev-table)))
(let ((table (symbol-value tablename)))
(while (consp props)
(abbrev-table-put table (pop props) (pop props)))
(dolist (d definitions)
(apply #'define-abbrev table d)))
(unless (memq tablename abbrev-table-name-list)
(setq abbrev-table-name-list (cons tablename abbrev-table-name-list)))
nil)
;; merge-ordered-lists (subr.el): merge LISTS into one, removing duplicates and
;; obeying each list's relative order (C3-style). Used by derived-mode-all-parents.
(defun merge-ordered-lists (lists &optional error-function)
"Merge LISTS in a consistent order.
LISTS is a list of lists of elements."
(let ((result '()))
(setq lists (remq nil lists))
(while (cdr (setq lists (delq nil lists)))
(let* ((next nil)
(tail lists))
(while tail
(let ((candidate (caar tail))
(other-lists lists))
(while other-lists
(if (not (memql candidate (cdr (car other-lists))))
(setq other-lists (cdr other-lists))
(setq candidate nil)
(setq other-lists nil)))
(if (not candidate)
(setq tail (cdr tail))
(setq next candidate)
(setq tail nil))))
(unless next
(setq next (funcall (or error-function #'caar) lists))
(unless (assoc next lists #'eql)
(error "Invalid candidate returned by error-function: %S" next)))
(push next result)
(setq lists
(mapcar (lambda (l) (if (eql (car l) next) (cdr l) l))
lists))))
(if (null result) (car lists)
(append (nreverse result) (car lists)))))
;; Mode-line/hook variables (subr.el, buffer.c defaults).
(defvar-local major-mode 'fundamental-mode
"Symbol for current buffer's major mode.")
(defvar-local mode-name nil
"Pretty name of current buffer's major mode.")
(defvar delay-mode-hooks nil
"If non-nil, `run-mode-hooks' should delay running the hooks.")
(defvar-local delayed-mode-hooks nil
"List of delayed mode hooks waiting to be run.")
(put 'delay-mode-hooks 'permanent-local t)
(defvar-local delayed-after-hook-functions nil
"List of delayed :after-hook forms waiting to be run.")
(defvar change-major-mode-after-body-hook nil
"Normal hook run in major mode functions, before the mode hooks.")
(defvar after-change-major-mode-hook nil
"Normal hook run at the very end of major mode functions.")
(defvar change-major-mode-hook nil
"Normal hook run by `kill-all-local-variables' before it kills locals.")
(defvar-local local-abbrev-table nil
"Local (mode-specific) abbrev table of current buffer.")
;; kill-all-local-variables (buffer.c documented behavior): run
;; `change-major-mode-hook', then eliminate the current buffer's local variables
;; except those with a non-nil `permanent-local' property, and reset the local
;; keymap. (Syntax-table/abbrev-table resets belong to subsystems not modeled.)
;; The always-local slots survive, but `reset_buffer_local_variables' stores
;; Fundamental mode's `major-mode' and `mode-name' and a t
;; `buffer-invisibility-spec' into them.
(defun kill-all-local-variables (&optional kill-permanent)
"Switch to Fundamental mode by killing current buffer's local variables."
(run-hooks 'change-major-mode-hook)
(dolist (sym (--buffer-local-symbols--))
(unless (and (not kill-permanent) (get sym 'permanent-local))
(kill-local-variable sym)))
(use-local-map nil)
(setq major-mode 'fundamental-mode
mode-name "Fundamental"
buffer-invisibility-spec t)
nil)
;; buffer.c `Fbuffer_local_variables': the per-buffer slots in the order of
;; `struct buffer' (`FOR_EACH_PER_BUFFER_OBJECT_AT'), then the Lisp locals of
;; `local_var_alist', oldest binding first. A void local is a bare symbol.
;; The slot order is measured: make every DEFVAR_PER_BUFFER variable local in a
;; temp buffer of `emacs -Q --batch' and read back `buffer-local-variables'.
(defconst buffer--per-buffer-slot-order
'(buffer-undo-list cursor-in-non-selected-windows text-conversion-style
line-spacing cursor-type scroll-down-aggressively scroll-up-aggressively
buffer-display-time fringe-cursor-alist fringe-indicator-alist
indicate-buffer-boundaries indicate-empty-lines horizontal-scroll-bar
vertical-scroll-bar scroll-bar-height scroll-bar-width
fringes-outside-margins right-fringe-width left-fringe-width
right-margin-width left-margin-width buffer-display-count
buffer-invisibility-spec buffer-file-truename point-before-scroll
cache-long-scans buffer-auto-save-file-format buffer-file-format
buffer-file-coding-system enable-multibyte-characters mark-active
buffer-display-table abbrev-mode overwrite-mode selective-display-ellipses
selective-display bidi-paragraph-start-re bidi-paragraph-separate-re
bidi-paragraph-direction bidi-display-reordering ctl-arrow word-wrap
truncate-lines auto-fill-function left-margin fill-column tab-width
local-abbrev-table tab-line-format header-line-format mode-line-format
mode-name local-minor-modes major-mode buffer-read-only
buffer-auto-save-file-name buffer-saved-size buffer-backed-up
default-directory buffer-file-name)
"The DEFVAR_PER_BUFFER variables in `struct buffer' order.")
(defun buffer-local-variables (&optional buffer)
"Return an alist of variables that are buffer-local in BUFFER."
(unless (or (null buffer) (bufferp buffer))
(signal 'wrong-type-argument (list 'bufferp buffer)))
(with-current-buffer (or buffer (current-buffer))
(let* ((locals (--buffer-local-symbols--))
(slots nil)
(rest nil))
(dolist (sym buffer--per-buffer-slot-order)
(when (memq sym locals) (push sym slots)))
(dolist (sym locals)
(unless (memq sym buffer--per-buffer-slot-order) (push sym rest)))
(mapcar (lambda (sym) (if (boundp sym) (cons sym (symbol-value sym)) sym))
(nconc (nreverse slots) (nreverse rest))))))
;; run-mode-hooks / delay-mode-hooks (subr.el, ported faithfully). The
;; `hack-local-variables' branch is inert here — `buffer-file-name' is always nil
;; (no file-visiting buffers).
(defun run-mode-hooks (&rest hooks)
"Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS."
(if delay-mode-hooks
(dolist (hook hooks)
(push hook delayed-mode-hooks))
(setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
(and (bound-and-true-p syntax-propertize-function)
(not (local-variable-p 'parse-sexp-lookup-properties))
(setq-local parse-sexp-lookup-properties t))
(setq delayed-mode-hooks nil)
(apply #'run-hooks (cons 'change-major-mode-after-body-hook hooks))
(if (buffer-file-name)
(with-demoted-errors "File local-variables error: %s"
(hack-local-variables 'no-mode)))
(run-hooks 'after-change-major-mode-hook)
(dolist (fun (prog1 (nreverse delayed-after-hook-functions)
(setq delayed-after-hook-functions nil)))
(funcall fun))))
(defmacro delay-mode-hooks (&rest body)
"Execute BODY, but delay any `run-mode-hooks'."
(declare (debug t) (indent 0))
`(progn
(make-local-variable 'delay-mode-hooks)
(let ((delay-mode-hooks t))
,@body)))
;; Derived-mode parent tracking (subr.el).
(defun derived-mode--flush (mode)
(put mode 'derived-mode--all-parents nil)
(let ((followers (get mode 'derived-mode--followers)))
(when followers
(put mode 'derived-mode--followers nil)
(mapc #'derived-mode--flush followers))))
(defun derived-mode-set-parent (mode parent)
"Declare PARENT to be the parent of MODE."
(put mode 'derived-mode-parent parent)
(derived-mode--flush mode))
(defun derived-mode-add-parents (mode extra-parents)
"Add EXTRA-PARENTS to the parents of MODE."
(put mode 'derived-mode-extra-parents extra-parents)
(derived-mode--flush mode))
(defun derived-mode-all-parents (mode &optional known-children)
"Return all the parents of MODE, starting with MODE."
(let ((ps (get mode 'derived-mode--all-parents)))
(cond
(ps ps)
((memq mode known-children)
(memq mode (reverse known-children)))
(t
(let* ((new-children (cons mode known-children))
(get-all-parents
(lambda (parent)
(let ((followers (get parent 'derived-mode--followers)))
(unless (memq mode followers)
(put parent 'derived-mode--followers
(cons mode followers))))
(derived-mode-all-parents parent new-children)))
(parent (or (get mode 'derived-mode-parent)
(let ((alias (symbol-function mode)))
(and (symbolp alias) alias))))
(extras (get mode 'derived-mode-extra-parents))
(all-parents
(merge-ordered-lists
(cons (if (and parent (not (memq parent extras)))
(funcall get-all-parents parent))
(mapcar get-all-parents extras)))))
(if (and (memq mode all-parents) known-children)
(cons mode (remq mode all-parents))
(put mode 'derived-mode--all-parents (cons mode all-parents))))))))
(defun provided-mode-derived-p (mode &optional modes &rest old-modes)
"Non-nil if MODE is derived from a mode that is a member of the list MODES."
(cond
(old-modes (setq modes (cons modes old-modes)))
((not (listp modes)) (setq modes (list modes))))
(let ((ps (derived-mode-all-parents mode)))
(while (and modes (not (memq (car modes) ps)))
(setq modes (cdr modes)))
(car modes)))
(defun derived-mode-p (&optional modes &rest old-modes)
"Return non-nil if the current major mode is derived from one of MODES."
(provided-mode-derived-p major-mode (if old-modes (cons modes old-modes)
modes)))
;; use-local-map / current-local-map are C primitives (builtins.rs) backed by the
;; current buffer's local keymap slot.
;; Docstring helpers (subr.el / derived.el). internal--format-docstring-line does
;; not fill/wrap here (fill is cosmetic; the string content matches Emacs).
(defun internal--format-docstring-line (string &rest objects)
"Format a single documentation line from STRING and OBJECTS."
(when (string-match "\n" string)
(error "Unable to fill string containing newline: %S" string))
(apply #'format string objects))
(defsubst derived-mode-hook-name (mode)
"Construct a mode-hook name based on the symbol MODE."
(intern (concat (symbol-name mode) "-hook")))
(defsubst derived-mode-map-name (mode)
"Construct a map name based on the symbol MODE."
(intern (concat (symbol-name mode) "-map")))
(defsubst derived-mode-syntax-table-name (mode)
"Construct a syntax-table name based on the symbol MODE."
(intern (concat (symbol-name mode) "-syntax-table")))
(defsubst derived-mode-abbrev-table-name (mode)
"Construct an abbrev-table name based on the symbol MODE."
(intern (concat (symbol-name mode) "-abbrev-table")))
(defun derived-mode-make-docstring (parent child &optional
docstring syntax abbrev)
"Construct a docstring for a new mode if none is provided."
(let ((map (derived-mode-map-name child))
(hook (derived-mode-hook-name child)))
(unless (stringp docstring)
(setq docstring
(if (null parent)
(concat
"Major-mode.\n"
(internal--format-docstring-line
"Uses keymap `%s'%s%s." map
(if abbrev (format "%s abbrev table `%s'"
(if syntax "," " and") abbrev) "")
(if syntax (format " and syntax-table `%s'" syntax) "")))
(format "Major mode derived from `%s' by `define-derived-mode'.
It inherits all of the parent's attributes, but has its own keymap%s:
%s
which more-or-less shadow%s %s's corresponding table%s."
parent
(cond ((and abbrev syntax)
",\nabbrev table and syntax table")
(abbrev "\nand abbrev table")
(syntax "\nand syntax table")
(t ""))
(internal--format-docstring-line
" `%s'%s"
map
(cond ((and abbrev syntax)
(format ", `%s' and `%s'" abbrev syntax))
((or abbrev syntax)
(format " and `%s'" (or abbrev syntax)))
(t "")))
(if (or abbrev syntax) "" "s")
parent
(if (or abbrev syntax) "s" "")))))
(unless (string-match (regexp-quote (symbol-name hook)) docstring)
(setq docstring
(concat docstring "\n\n"
(internal--format-docstring-line
"%s%s%s"
(if (null parent)
"This mode "
(concat
"In addition to any hooks its parent mode "
(if (string-match (format "[`‘]%s['’]"
(regexp-quote
(symbol-name parent)))
docstring)
nil
(format "`%s' " parent))
"might have run, this mode "))
(format "runs the hook `%s'" hook)
", as the final or penultimate step during initialization."))))
(unless (string-match "\\\\[{[]" docstring)
(setq docstring (concat docstring "\n\n\\{" (symbol-name map) "}")))
docstring))
;; define-derived-mode (derived.el), ported faithfully.
(defmacro define-derived-mode (child parent name &optional docstring &rest body)
"Create a new mode CHILD which is a variant of an existing mode PARENT."
(declare (debug (&define name symbolp sexp [&optional stringp]
[&rest keywordp sexp] def-body))
(doc-string 4)
(indent defun))
(when (and docstring (not (stringp docstring)))
(push docstring body)
(setq docstring nil))
(when (eq parent 'fundamental-mode) (setq parent nil))
(let ((map (derived-mode-map-name child))
(syntax (derived-mode-syntax-table-name child))
(abbrev (derived-mode-abbrev-table-name child))
(declare-abbrev t)
(declare-syntax t)
(hook (derived-mode-hook-name child))
(group nil)
(interactive t)
(after-hook nil))
(while (keywordp (car body))
(pcase (pop body)
(:group (setq group (pop body)))
(:abbrev-table (setq abbrev (pop body)) (setq declare-abbrev nil))
(:syntax-table (setq syntax (pop body)) (setq declare-syntax nil))
(:after-hook (setq after-hook (pop body)))
(:interactive (setq interactive (pop body)))
(_ (pop body))))
(setq docstring (derived-mode-make-docstring
parent child docstring syntax abbrev))
`(progn
(defvar ,hook nil)
(unless (get ',hook 'variable-documentation)
(put ',hook 'variable-documentation
,(format "Hook run after entering `%S'.
No problems result if this variable is not bound.
`add-hook' automatically binds it. (This is true for all hook variables.)"
child)))
;; Mark the map special (bare `defvar', no value) always, but only
;; INITIALIZE it when unbound -- mirroring Emacs's no-clobber `defvar'
;; and the syntax/abbrev guards below. A mode whose map is preloaded
;; (e.g. `special-mode-map' via `defvar-keymap') keeps its bindings.
(with-no-warnings (defvar ,map))
(unless (boundp ',map)
(put ',map 'definition-name ',child)
(defvar ,map (make-sparse-keymap)))
(unless (get ',map 'variable-documentation)
(put ',map 'variable-documentation
(purecopy ,(format "Keymap for `%s'." child))))
,(if declare-syntax
`(progn
(defvar ,syntax)
(unless (boundp ',syntax)
(put ',syntax 'definition-name ',child)
(defvar ,syntax (make-syntax-table)))
(unless (get ',syntax 'variable-documentation)
(put ',syntax 'variable-documentation
(purecopy ,(format "Syntax table for `%s'." child))))))
,(if declare-abbrev
`(progn
(defvar ,abbrev)
(unless (boundp ',abbrev)
(put ',abbrev 'definition-name ',child)
(defvar ,abbrev
(progn (define-abbrev-table ',abbrev nil) ,abbrev)))
(unless (get ',abbrev 'variable-documentation)
(put ',abbrev 'variable-documentation
(purecopy ,(format "Abbrev table for `%s'." child))))))
(if (fboundp 'derived-mode-set-parent)
(derived-mode-set-parent ',child ',parent)
(put ',child 'derived-mode-parent ',parent))
,(if group `(put ',child 'custom-mode-group ,group))
(defun ,child ()
,docstring
,(and interactive '(interactive))
(delay-mode-hooks
(,(or parent 'kill-all-local-variables))
(setq major-mode (quote ,child))
(setq mode-name ,name)
,(when parent
`(progn
(if (get (quote ,parent) 'mode-class)
(put (quote ,child) 'mode-class
(get (quote ,parent) 'mode-class)))
(unless (keymap-parent ,map)
(set-keymap-parent ,map (current-local-map)))
,(when declare-syntax
`(let ((parent (char-table-parent ,syntax)))
(unless (and parent
(not (eq parent (standard-syntax-table))))
(set-char-table-parent ,syntax (syntax-table)))))
,(when declare-abbrev
`(unless (or (abbrev-table-get ,abbrev :parents)
(eq ,abbrev local-abbrev-table))
(abbrev-table-put ,abbrev :parents
(list local-abbrev-table))))))
(use-local-map ,map)
,(when syntax `(set-syntax-table ,syntax))
,(when abbrev `(setq local-abbrev-table ,abbrev))
,@body)
,@(when after-hook
`((push (lambda () ,after-hook) delayed-after-hook-functions)))
(run-mode-hooks ',hook)))))
;; ---- fundamental-mode + special-mode (simple.el) ----
;; Buffer-local state slots these modes touch (buffer.c C variables in Emacs;
;; buffer-local Lisp variables here).
(defvar-local buffer-read-only nil
"Non-nil if this buffer is read-only.")
(defvar-local buffer-undo-list nil
"List of undo entries in current buffer.
A value of t means undo information is not being recorded.")
;; buffer-disable-undo (simple.el): stop keeping undo information.
(defun buffer-disable-undo (&optional _buffer)
"Make current buffer stop keeping undo information."
(setq buffer-undo-list t))
(defun buffer-enable-undo (&optional _buffer)
"Start keeping undo information for the current buffer."
(interactive "")
(when (eq buffer-undo-list t)
(setq buffer-undo-list nil)))
;; subr.el `with-silent-modifications': run BODY without it counting as a
;; modification -- the modified flag is restored unless the buffer was already
;; modified (and not merely auto-saved) on entry.
(defvar inhibit-modification-hooks nil)
(defmacro with-silent-modifications (&rest body)
"Execute BODY, pretending it does not modify the buffer."
(declare (debug t) (indent 0))
(let ((modified (make-symbol "modified")))
`(let* ((,modified (buffer-modified-p))
(buffer-undo-list t)
(inhibit-read-only t)
(inhibit-modification-hooks t))
(unwind-protect
(progn
,@body)
(when (memq ,modified '(nil autosaved))
(restore-buffer-modified-p ,modified))))))
;; fundamental-mode (simple.el): the root major mode. Body is empty; it just
;; resets local variables and installs itself as `major-mode'.
(defun fundamental-mode ()
"Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one."
(interactive)
(kill-all-local-variables)
(setq major-mode 'fundamental-mode)
(setq mode-name "Fundamental")
(run-mode-hooks))
;; Display-engine state variables (C `character.c'/`xdisp.c' + `simple.el').
;; These are the real variable declarations, not stubs; the redisplay engine
;; that acts on them is a separate subsystem and is not modeled here.
;; `glyphless-char-display' is itself a char-table (subtype glyphless-char-display,
;; one extra slot), so it also exercises the char-table type.
(put 'glyphless-char-display 'char-table-extra-slots 1)
(defvar glyphless-char-display (make-char-table 'glyphless-char-display)
"Char-table defining glyphless characters.")
(defvar-local truncate-lines nil
"Non-nil means do not display continuation lines.")
(defvar-local bidi-paragraph-direction nil
"If non-nil, forces a paragraph direction in the current buffer.")
(defvar-local text-scale-remap-header-line nil
"If non-nil, text scaling may change the height of the header line.")
(defvar-local revert-buffer-function nil
"Function to use to revert this buffer.")
;; special-mode (simple.el): parent mode for buffers that view formatted data.
(put 'special-mode 'mode-class 'special)
(define-derived-mode special-mode nil "Special"
"Parent major mode from which special major modes should inherit.
A special major mode is intended to view specially formatted data
rather than files. These modes usually use read-only buffers."
(setq buffer-read-only t))
;; ---- define-minor-mode (easy-mmode.el) + supporting subr.el pieces ----
;; prefix-numeric-value (C callint.c documented behavior): the numeric value of a
;; raw prefix argument. nil -> 1, `-' -> -1, (N) -> N, a number -> itself.
(defun prefix-numeric-value (arg)
"Return numeric meaning of raw prefix argument ARG."
(cond ((null arg) 1)
((eq arg '-) -1)
((consp arg) (car arg))
((integerp arg) arg)
(t 1)))
(defvar current-prefix-arg nil
"The raw prefix argument for the next command.")
;; Interactive invocation is not modeled (no `call-interactively'); a command
;; called from Lisp — the only path here — is never an interactive call.
(defun called-interactively-p (&optional _kind) nil)
;; Batch has no echo area / mode line.
(defun current-message () nil)
(defun force-mode-line-update (&optional _all) nil)
;; Warnings are not modeled; return the form unchanged.
(defun macroexp-warn-and-return (_msg form &rest _) form)
;;; ---- declaration handlers (byte-run.el) -----------------------------------
;; `declare' specs that have a *runtime* effect (register a gv-setter, set the
;; obsolete/indent/doc-string properties, …) are processed at defun/defmacro
;; macroexpansion time. In Emacs `defun'/`defmacro' are themselves macros that
;; do this; in elisprs they are compiler special forms, so the host's
;; defun/defmacro expander (macroexpand_all) delegates to
;; `elisprs--expand-defun-declarations' below once these handlers are defined.
;; Each `defun-declarations-alist' entry is (PROP FUN [DOC]); FUN is applied to
;; (NAME ARGLIST . VALUES) and returns a form to eval after the definition.
;; Ported faithfully from byte-run.el.
(defalias 'byte-run--set-advertised-calling-convention
(lambda (f _args arglist when)
(list 'set-advertised-calling-convention
(list 'quote f) (list 'quote arglist) (list 'quote when))))
(defalias 'byte-run--set-obsolete
(lambda (f _args new-name when)
(list 'make-obsolete
(list 'quote f) (list 'quote new-name) when)))
(defalias 'byte-run--set-interactive-only
(lambda (f _args instead)
(list 'function-put (list 'quote f)
''interactive-only (list 'quote instead))))
(defalias 'byte-run--set-pure
(lambda (f _args val)
(list 'function-put (list 'quote f)
''pure (list 'quote val))))
(defalias 'byte-run--set-side-effect-free
(lambda (f _args val)
(list 'function-put (list 'quote f)
''side-effect-free (list 'quote val))))
(defalias 'byte-run--set-important-return-value
(lambda (f _args val)
(list 'function-put (list 'quote f)
''important-return-value (list 'quote val))))
(defalias 'byte-run--set-compiler-macro
(lambda (f args compiler-function)
(if (not (eq (car-safe compiler-function) 'lambda))
`(eval-and-compile
(function-put ',f 'compiler-macro #',compiler-function))
(let ((cfname (intern (concat (symbol-name f) "--anon-cmacro")))
(data (cdr compiler-function)))
`(progn
(eval-and-compile
(function-put ',f 'compiler-macro #',cfname))
:autoload-end
(eval-and-compile
(defun ,cfname (,@(car data) ,@args)
(ignore ,@(delq '&rest (delq '&optional (copy-sequence args))))
,@(cdr data))))))))
;; `add-to-list' is defined far above, before this bridge exists, so its
;; compiler macro is registered by hand -- in exactly the shape
;; `byte-run--set-compiler-macro' would have produced from a `declare'.
;;
;; The handler is subr.el's own. It DECLINES -- answering the form unchanged,
;; so the ordinary function runs -- unless VAR is a literally-quoted symbol
;; that is not special and APPEND is a constant, which is precisely the case
;; the function cannot serve: it reads and writes a symbol's value cell, and a
;; lexical variable has none. (subr.el also emits a byte-compiler warning here;
;; elisprs has no `macroexp-compiling-p' path, and Emacs skips the warning on
;; that branch too.)
(defun add-to-list--anon-cmacro (exp var elt &optional append compare-fn)
(if (or (not (eq 'quote (car-safe var)))
(special-variable-p (car (cdr var)))
(not (macroexp-const-p append)))
exp
(let ((sym (car (cdr var)))
(appendp (eval append t)))
(list 'if (if compare-fn
(list 'cl-member elt sym :test compare-fn)
(list 'member elt sym))
sym
(if appendp
(list 'setq sym (list 'append sym (list 'list elt)))
(list 'setq sym (list 'cons elt sym)))))))
(function-put 'add-to-list 'compiler-macro #'add-to-list--anon-cmacro)
(defalias 'byte-run--set-doc-string
(lambda (f _args pos)
(list 'function-put (list 'quote f)
''doc-string-elt (if (numberp pos) pos (list 'quote pos)))))
(defalias 'byte-run--set-indent
(lambda (f _args val)
(list 'function-put (list 'quote f)
''lisp-indent-function (if (numberp val) val (list 'quote val)))))
(defalias 'byte-run--set-speed
(lambda (f _args val)
(list 'function-put (list 'quote f) ''speed (list 'quote val))))
(defalias 'byte-run--set-safety
(lambda (f _args val)
(list 'function-put (list 'quote f) ''safety (list 'quote val))))
(defalias 'byte-run--set-completion
(lambda (f _args val)
(list 'function-put (list 'quote f)
''completion-predicate (list 'function val))))
(defalias 'byte-run--set-modes
(lambda (f _args &rest val)
(list 'function-put (list 'quote f) ''command-modes (list 'quote val))))
(defalias 'byte-run--set-interactive-args
(lambda (f args &rest val)
(setq args (remove '&optional (remove '&rest args)))
(list 'function-put (list 'quote f)
''interactive-args
(list 'quote
(mapcar (lambda (elem)
(cons (seq-position args (car elem)) (cadr elem)))
val)))))
(defalias 'byte-run--set-function-type
(lambda (f _args val &optional f2)
(when (and f2 (not (eq f2 f)))
(error "`%s' does not match top level function `%s' inside function type declaration"
f2 f))
(list 'function-put (list 'quote f) ''function-type (list 'quote val))))
(defalias 'byte-run--set-debug
(lambda (name _args spec)
(list 'progn :autoload-end
(list 'put (list 'quote name) ''edebug-form-spec (list 'quote spec)))))
(defalias 'byte-run--set-no-font-lock-keyword
(lambda (name _args val)
(list 'function-put (list 'quote name) ''no-font-lock-keyword (list 'quote val))))
;; Populate the alists declared earlier as nil (byte-run.el:235,349).
(setq defun-declarations-alist
(list
(list 'advertised-calling-convention
#'byte-run--set-advertised-calling-convention)
(list 'obsolete #'byte-run--set-obsolete)
(list 'interactive-only #'byte-run--set-interactive-only)
(list 'pure #'byte-run--set-pure)
(list 'side-effect-free #'byte-run--set-side-effect-free)
(list 'important-return-value #'byte-run--set-important-return-value)
(list 'compiler-macro #'byte-run--set-compiler-macro)
(list 'doc-string #'byte-run--set-doc-string)
(list 'indent #'byte-run--set-indent)
(list 'speed #'byte-run--set-speed)
(list 'safety #'byte-run--set-safety)
(list 'completion #'byte-run--set-completion)
(list 'modes #'byte-run--set-modes)
(list 'interactive-args #'byte-run--set-interactive-args)
(list 'ftype #'byte-run--set-function-type)))
(setq macro-declarations-alist
(cons (list 'debug #'byte-run--set-debug)
(cons (list 'no-font-lock-keyword #'byte-run--set-no-font-lock-keyword)
defun-declarations-alist)))
;; byte-run.el:279 — split BODY into (DOCSTRING DECLARE INTERACTIVE REST WARNINGS).
(defun byte-run--parse-body (body allow-interactive)
"Decompose BODY into (DOCSTRING DECLARE INTERACTIVE BODY-REST WARNINGS)."
(let* ((top body)
(docstring nil)
(declare-form nil)
(interactive-form nil)
(warnings nil)
(warn (lambda (msg form)
(push (macroexp-warn-and-return
(format-message msg) nil nil t form)
warnings))))
(while
(and body
(let* ((form (car body))
(head (car-safe form)))
(cond
((or (and (stringp form) (cdr body))
(eq head :documentation))
(cond
(docstring (funcall warn "More than one doc string" top))
(declare-form
(funcall warn "Doc string after `declare'" declare-form))
(interactive-form
(funcall warn "Doc string after `interactive'" interactive-form))
(t (setq docstring form)))
t)
((eq head 'declare)
(cond
(declare-form
(funcall warn "More than one `declare' form" form))
(interactive-form
(funcall warn "`declare' after `interactive'" form))
(t (setq declare-form form)))
t)
((eq head 'interactive)
(cond
((not allow-interactive)
(funcall warn "No `interactive' form allowed here" form))
(interactive-form
(funcall warn "More than one `interactive' form" form))
(t (setq interactive-form form)))
t))))
(setq body (cdr body)))
(list docstring declare-form interactive-form body warnings)))
;; byte-run.el:326 — map each declaration clause through DECLARATIONS-ALIST.
(defun byte-run--parse-declarations (name arglist clauses construct declarations-alist)
(let* ((cl-decls nil)
(actions
(mapcar
(lambda (x)
(let ((f (cdr (assq (car x) declarations-alist))))
(cond
(f (apply (car f) name arglist (cdr x)))
((and (featurep 'cl)
(memq (car x)
'(special inline notinline optimize warn)))
(push (list 'declare x) cl-decls)
nil)
(t
(macroexp-warn-and-return
(format-message "Unknown %s property `%S'"
construct (car x))
nil nil nil (car x))))))
clauses)))
(cons actions cl-decls)))
;; gv.el:159 — turn a (gv-setter …)/(gv-expander …) declaration into the form
;; that registers the corresponding generalized-variable handler.
(defun gv--defun-declaration (symbol name args handler &optional fix)
`(progn
:autoload-end
,(pcase (cons symbol handler)
(`(gv-expander . (lambda (,do) . ,body))
`(gv-define-expander ,name (lambda (,do ,@args) ,@body)))
(`(gv-expander . ,(pred symbolp))
`(gv-define-expander ,name #',handler))
(`(gv-setter . (lambda (,store) . ,body))
`(gv-define-setter ,name (,store ,@args) ,@body))
(`(gv-setter . ,(pred symbolp))
`(gv-define-simple-setter ,name ,handler ,fix))
(_ (message "Unknown %s declaration %S" symbol handler) nil))))
(defsubst gv--expander-defun-declaration (&rest args)
(apply #'gv--defun-declaration 'gv-expander args))
(defsubst gv--setter-defun-declaration (&rest args)
(apply #'gv--defun-declaration 'gv-setter args))
(or (assq 'gv-expander defun-declarations-alist)
(let ((x (list 'gv-expander #'gv--expander-defun-declaration)))
(push x macro-declarations-alist)
(push x defun-declarations-alist)))
(or (assq 'gv-setter defun-declarations-alist)
(push (list 'gv-setter #'gv--setter-defun-declaration)
defun-declarations-alist))
;; Bridge invoked by the host's defun/defmacro expander (macroexpand_all).
;; CONSTRUCT is `defun' or `defmacro'; NAME/ARGLIST/BODY are the raw pieces.
;; Returns the replacement form threading each declaration's runtime side-effect
;; form after the (unchanged-shape) definition, mirroring byte-run.el's `defun'
;; and `defmacro' macros — or nil when BODY has no `declare' (host falls through
;; to plain body expansion).
(defun elisprs--expand-defun-declarations (construct name arglist body)
(let* ((allow-interactive (eq construct 'defun))
(parse (byte-run--parse-body body allow-interactive))
(docstring (nth 0 parse))
(declare-form (nth 1 parse))
(interactive-form (nth 2 parse))
(rest (nth 3 parse))
(warnings (nth 4 parse))
(alist (if (eq construct 'defmacro)
macro-declarations-alist
defun-declarations-alist))
(declarations
(and declare-form
(byte-run--parse-declarations
name arglist (cdr declare-form) construct alist))))
(when declare-form
(setq rest (nconc warnings rest))
(setq rest (nconc (cdr declarations) rest))
(when interactive-form (setq rest (cons interactive-form rest)))
(when docstring (setq rest (cons docstring rest)))
(when (null rest) (setq rest '(nil)))
(let ((def (cons construct (cons name (cons arglist rest)))))
(if declarations
(cons 'prog1 (cons def (car declarations)))
def)))))
;; A `defun'/`defmacro' the prelude defined before this bridge existed kept
;; its `declare' unprocessed; Emacs's preloaded files are byte-compiled with
;; every declaration applied, so run the side-effect forms the bridge would
;; have threaded after each of those definitions (without redefining them).
(dolist (def (--early-declarations--))
(let ((replaced (elisprs--expand-defun-declarations
(car def) (nth 1 def) (nth 2 def) (nthcdr 3 def))))
(when (eq (car-safe replaced) 'prog1)
(dolist (form (cddr replaced))
(eval form t)))))
;; custom-local-buffer (custom.el): when non-nil in a Customization buffer,
;; :set functions target that buffer's local binding instead of the default.
(defvar custom-local-buffer nil
"Non-nil, in a Customization buffer, means customize a specific buffer.
If this variable is non-nil, it should be a buffer,
and it means customize the local bindings of that buffer.
This variable is a permanent local, and it normally has a local binding
in every Customization buffer.")
(put 'custom-local-buffer 'permanent-local t)
;; custom-set-default (custom.el): the default :set function for a customizable
;; variable. Sets the default value of VARIABLE to VALUE, unless a
;; `custom-local-buffer' is active (Customize buffer), in which case the local
;; binding in that buffer is set instead.
(defun custom-set-default (variable value)
"Default :set function for a customizable variable.
Normally, this sets the default value of VARIABLE to VALUE,
but if `custom-local-buffer' is non-nil,
this sets the local binding in that buffer instead."
(if custom-local-buffer
(with-current-buffer custom-local-buffer
(set variable value))
(set-default-toplevel-value variable value)))
;; ---------------------------------------------------------------------------
;; custom-set-variables / custom-theme-set-variables (custom.el).
;;
;; This is the machinery a user's Customize block generates. Ported faithfully
;; from custom.el (Emacs 30.2). It is pure Lisp: no widgets, keymaps, eieio, or
;; face machinery on this path -- only theme-value/saved-value bookkeeping via
;; get/put plus the default :set (custom-set-default).
;; ---------------------------------------------------------------------------
;; load-history (lread.c global): normally a list of loaded files and the
;; symbols they defined. elisprs does not track it; nil means "nothing known
;; to be loaded", which only affects the autoload branch of custom-load-symbol.
(defvar load-history nil
"Alist mapping loaded file names to symbols and features.")
;; custom.el:690
(defvar custom-load-recursion nil
"Hack to avoid recursive dependencies.")
;; custom.el:884
(defvar custom-known-themes '(user changed)
"Themes that have been defined with `deftheme'.")
;; custom.el:892
(defsubst custom-theme-p (theme)
"Non-nil when THEME has been defined."
(memq theme custom-known-themes))
;; custom.el:895
(defsubst custom-check-theme (theme)
"Check whether THEME is valid, and signal an error if it is not."
(unless (custom-theme-p theme)
(error "Unknown theme `%s'" theme)))
;; custom.el:753
(defun custom-quote (sexp)
"Quote SEXP if it is not self quoting."
(if (and (not (consp sexp))
(or (keywordp sexp)
(not (symbolp sexp))
(booleanp sexp)))
sexp
(list 'quote sexp)))
;; custom.el:1234
(defvar custom--inhibit-theme-enable 'apply-only-user
"Whether the custom-theme-set-* functions act immediately.
If nil, `custom-theme-set-variables' and `custom-theme-set-faces'
change the current values of the given variable or face. If t,
they just make a record of the theme's settings. If the value is
`apply-only-user', then only the `user' theme is allowed to
change the current values.")
;; custom.el:901
(defun custom--should-apply-setting (theme)
(or (null custom--inhibit-theme-enable)
(and (eq custom--inhibit-theme-enable 'apply-only-user)
(eq theme 'user))))
;; custom.el:906
(defun custom-push-theme (prop symbol theme mode &optional value)
"Record VALUE for face or variable SYMBOL in custom theme THEME.
PROP is `theme-face' for a face, `theme-value' for a variable.
MODE can be either the symbol `set' or the symbol `reset'."
(unless (memq prop '(theme-value theme-face theme-icon))
(error "Unknown theme property"))
(let* ((old (get symbol prop))
(setting (assq theme old))
(theme-settings
(get theme 'theme-settings)))
(cond
((eq mode 'reset)
(when setting
(let (res)
(dolist (theme-setting theme-settings)
(if (and (eq (car theme-setting) prop)
(eq (cadr theme-setting) symbol))
(setq res theme-setting)))
(put theme 'theme-settings (delq res theme-settings)))
(put symbol prop (delq setting old))))
(setting
(let (res)
(dolist (theme-setting theme-settings)
(if (and (eq (car theme-setting) prop)
(eq (cadr theme-setting) symbol))
(setq res theme-setting)))
(put theme 'theme-settings
(cons (list prop symbol theme value)
(delq res theme-settings)))
(put symbol prop (cons (list theme value) (delq setting old)))))
(t
(when (custom--should-apply-setting theme)
(unless old
(when (and (eq prop 'theme-value)
(boundp symbol))
(let ((sv (get symbol 'standard-value))
(val (symbol-value symbol)))
(unless (or
(and sv (equal (eval (car sv)) val))
(and (eq theme 'user) (equal (custom-quote val) value)))
(setq old `((changed ,(custom-quote val))))))))
(put symbol prop (cons (list theme value) old)))
(put theme 'theme-settings
(cons (list prop symbol theme value) theme-settings))))))
;; custom.el:693
(defun custom-load-symbol (symbol)
"Load all dependencies for SYMBOL."
(unless custom-load-recursion
(let ((custom-load-recursion t))
(ignore-errors
(require 'cus-load))
(ignore-errors
(require 'cus-start))
(dolist (load (get symbol 'custom-loads))
(cond ((symbolp load) (ignore-errors (require load)))
((assoc load load-history))
((let ((regexp (concat "\\(\\`\\|/\\)" (regexp-quote load)
"\\(\\'\\|\\.\\)"))
(found nil))
(dolist (loaded load-history)
(and (stringp (car loaded))
(string-match-p regexp (car loaded))
(setq found t)))
found))
((equal load "cus-edit"))
(t (ignore-errors (load load))))))))
;; custom.el:1085 (defvars for the topological sort)
(defvar custom--sort-vars-table)
(defvar custom--sort-vars-result)
;; custom.el:1123
(defun custom--sort-vars-1 (sym &optional _ignored)
(let ((elt (gethash sym custom--sort-vars-table)))
(when elt
(cond
((eq (car elt) 'dependant)
(error "Circular custom dependency on `%s'" sym))
((car elt)
(setcar elt 'dependant)
(dolist (dep (get sym 'custom-dependencies))
(custom--sort-vars-1 dep))
(setcar elt nil)
(push (cdr elt) custom--sort-vars-result))))))
;; custom.el:1088
(defun custom--sort-vars (vars)
"Sort VARS based on custom dependencies."
(let ((custom--sort-vars-table (make-hash-table))
(dependants (make-hash-table))
(custom--sort-vars-result nil)
last)
(dolist (var vars)
(puthash (car var) (cons t var) custom--sort-vars-table)
(puthash (car var) var dependants))
(dolist (var vars)
(dolist (dep (get (car var) 'custom-dependencies))
(remhash dep dependants)))
(maphash (lambda (sym var)
(when (and (null (get sym 'custom-dependencies))
(or (nth 3 var)
(eq (get sym 'custom-set)
'custom-set-minor-mode)))
(remhash sym dependants)
(push var last)))
dependants)
(maphash #'custom--sort-vars-1 dependants)
(nconc (nreverse custom--sort-vars-result) last)))
;; custom.el:1017
(defun custom-theme-set-variables (theme &rest args)
"Initialize variables for theme THEME according to settings in ARGS.
Each of the arguments in ARGS should be a list of this form:
(SYMBOL EXP [NOW [REQUEST [COMMENT]]])"
(custom-check-theme theme)
(dolist (entry args)
(let* ((symbol (indirect-variable (nth 0 entry))))
(unless (or (get symbol 'standard-value)
(memq (get symbol 'custom-autoload) '(nil noset)))
(custom-load-symbol symbol))))
(setq args (custom--sort-vars args))
(dolist (entry args)
(unless (listp entry)
(error "Incompatible Custom theme spec"))
(let* ((symbol (indirect-variable (nth 0 entry)))
(value (nth 1 entry)))
(custom-push-theme 'theme-value symbol theme 'set value)
(when (custom--should-apply-setting theme)
(let* ((now (nth 2 entry))
(requests (nth 3 entry))
(comment (nth 4 entry))
set)
(when requests
(put symbol 'custom-requests requests)
(mapc (lambda (lib) (require lib nil t)) requests))
(setq set (or (get symbol 'custom-set) #'custom-set-default))
(put symbol 'saved-value (list value))
(put symbol 'saved-variable-comment comment)
(condition-case data
(cond (now
(put symbol 'force-value t)
(funcall set symbol (eval value)))
((default-boundp symbol)
(funcall set symbol (eval value))))
(error
(message "Error setting %s: %s" symbol data)))
(and (or now (default-boundp symbol))
(put symbol 'variable-comment comment)))))))
;; custom.el:1001
(defun custom-set-variables (&rest args)
"Install user customizations of variable values specified in ARGS.
These settings are registered as theme `user'.
The arguments should each be a list of the form:
(SYMBOL EXP [NOW [REQUEST [COMMENT]]])"
(apply #'custom-theme-set-variables 'user args))
;; custom-set-minor-mode (custom.el): a defcustom :set that toggles the mode.
;; (Reached only via Customize, which is out of the mode-run path.)
(defun custom-set-minor-mode (variable value)
(funcall variable (if value 1 0)))
;; minor-mode registries (subr.el defvars).
(defvar minor-mode-list nil
"List of all minor mode functions.")
(defvar minor-mode-alist nil
"Alist saying how to show minor modes in the mode line.")
(defvar minor-mode-map-alist nil
"Alist of keymaps to use for minor modes.")
(defvar global-minor-modes nil
"A list of the currently enabled global minor modes.")
(defvar-local local-minor-modes nil
"A list of the currently enabled minor modes in the current buffer.")
(defvar mode-line-mode-menu (make-sparse-keymap "Minor Modes")
"Menu of mode operations in the mode line.")
;; add-minor-mode (subr.el), ported faithfully.
(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
"Register a new minor mode."
(unless (memq toggle minor-mode-list)
(push toggle minor-mode-list))
(unless toggle-fun (setq toggle-fun toggle))
(unless (eq toggle-fun toggle)
(put toggle :minor-mode-function toggle-fun))
(when name
(let ((existing (assq toggle minor-mode-alist)))
(if existing
(setcdr existing (list name))
(let ((tail minor-mode-alist) found)
(while (and tail (not found))
(if (eq after (caar tail))
(setq found tail)
(setq tail (cdr tail))))
(if found
(let ((rest (cdr found)))
(setcdr found nil)
(nconc found (list (list toggle name)) rest))
(push (list toggle name) minor-mode-alist))))))
(when (get toggle :included)
(define-key mode-line-mode-menu
(vector toggle)
(list 'menu-item
(concat
(or (get toggle :menu-tag)
(if (stringp name) name (symbol-name toggle)))
(let ((mode-name (if (symbolp name) (symbol-value name))))
(if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
(concat " (" (match-string 0 mode-name) ")"))))
toggle-fun
:button (cons :toggle toggle))))
(when keymap
(let ((existing (assq toggle minor-mode-map-alist)))
(if existing
(setcdr existing keymap)
(let ((tail minor-mode-map-alist) found)
(while (and tail (not found))
(if (eq after (caar tail))
(setq found tail)
(setq tail (cdr tail))))
(if found
(let ((rest (cdr found)))
(setcdr found nil)
(nconc found (list (cons toggle keymap)) rest))
(push (cons toggle keymap) minor-mode-map-alist)))))))
;; easy-mmode-pretty-mode-name (easy-mmode.el).
(defun easy-mmode-pretty-mode-name (mode &optional lighter)
"Turn the symbol MODE into a string intended for the user."
(let* ((case-fold-search t)
(name (concat (replace-regexp-in-string
"-Minor" " minor"
(capitalize (replace-regexp-in-string
"toggle-\\|-mode\\'" ""
(symbol-name mode))))
" mode")))
(setq name (replace-regexp-in-string "\\`Global-" "Global " name))
(if (not (stringp lighter)) name
(setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
lighter))
(replace-regexp-in-string (regexp-quote lighter) lighter name t t))))
;; ensure-empty-lines (subr.el): ensure LINES empty lines before point.
(defun ensure-empty-lines (&optional lines)
"Ensure that there are LINES number of empty lines before point."
(unless (bolp)
(insert "\n"))
(let ((lines (or lines 1))
(start (save-excursion
(if (re-search-backward "[^\n]" nil t)
(+ (point) 2)
(point-min)))))
(cond
((> (- (point) start) lines)
(delete-region (point) (- (point) (- (point) start lines))))
((< (- (point) start) lines)
(insert (make-string (- lines (- (point) start)) ?\n))))))
(defconst easy-mmode--arg-docstring
"This is a %sminor mode. If called interactively, toggle the
`%s' mode. If the prefix argument is positive, enable the mode,
and if it is zero or negative, disable the mode.
If called from Lisp, toggle the mode if ARG is `toggle'.
Enable the mode if ARG is nil, omitted, or is a positive number.
Disable the mode if ARG is a negative number.
To check whether the minor mode is enabled in the current buffer,
evaluate %s.
The mode's hook is called both when the mode is enabled and when
it is disabled.")
;; easy-mmode--mode-docstring (easy-mmode.el). Uses a temp buffer to compose the
;; docstring; `fill-region' is skipped when unbound (no line-wrap; cosmetic).
(defun easy-mmode--mode-docstring (doc mode-pretty-name keymap-sym getter global)
(if (and doc (string-match-p "\\bARG\\b" doc))
doc
(with-temp-buffer
(let ((lines (if doc
(string-lines doc)
(list (format "Toggle %s on or off." mode-pretty-name)))))
(insert (pop lines))
(ensure-empty-lines)
(while (and lines (equal (car lines) ""))
(pop lines))
(dolist (line lines)
(insert line "\n"))
(ensure-empty-lines)
(let* ((fill-prefix nil)
(docs-fc (bound-and-true-p emacs-lisp-docstring-fill-column))
(fill-column (if (integerp docs-fc) docs-fc 65))
(argdoc (format
easy-mmode--arg-docstring
(if global "global " "")
mode-pretty-name
(concat
(if (symbolp getter) "the variable ")
(format "`%s'"
(string-replace "'" "\\='" (format "%S" getter)))))))
(let ((start (point)))
(insert argdoc)
(when (fboundp 'fill-region)
(fill-region start (point) 'left t))))
(when (and (boundp keymap-sym)
(or (not doc)
(not (string-search "\\{" doc))))
(ensure-empty-lines)
(insert (format "\\{%s}" keymap-sym)))
(buffer-string)))))
;; define-minor-mode (easy-mmode.el), ported faithfully.
(defmacro define-minor-mode (mode doc &rest body)
"Define a new minor mode MODE."
(declare (doc-string 2) (indent defun))
(let* ((last-message (make-symbol "last-message"))
(mode-name (symbol-name mode))
(init-value nil)
(keymap nil)
(lighter nil)
(pretty-name nil)
(globalp nil)
(set nil)
(initialize nil)
(type nil)
(extra-args nil)
(extra-keywords nil)
(variable nil)
(setter `(setq ,mode))
(getter mode)
(modefun mode)
(after-hook nil)
(hook (intern (concat mode-name "-hook")))
(hook-on (intern (concat mode-name "-on-hook")))
(hook-off (intern (concat mode-name "-off-hook")))
(interactive t)
(warnwrap (if (or (null body) (keywordp (car body))) #'identity
(lambda (exp)
(macroexp-warn-and-return
(format-message
"Use keywords rather than deprecated positional arguments to `define-minor-mode'")
exp))))
keyw keymap-sym tmp)
(unless (keywordp (car body))
(setq init-value (pop body))
(unless (keywordp (car body))
(setq lighter (pop body))
(unless (keywordp (car body))
(setq keymap (pop body)))))
(while (keywordp (setq keyw (car body)))
(setq body (cdr body))
(pcase keyw
(:init-value (setq init-value (pop body)))
(:lighter (setq lighter (purecopy (pop body))))
(:global (setq globalp (pop body))
(when (and globalp (symbolp mode))
(setq setter `(setq-default ,mode))
(setq getter `(default-value ',mode))))
(:extra-args (setq extra-args (pop body)))
(:set (setq set (list :set (pop body))))
(:initialize (setq initialize (list :initialize (pop body))))
(:type (setq type (list :type (pop body))))
(:keymap (setq keymap (pop body)))
(:interactive (setq interactive (pop body)))
(:variable (setq variable (pop body))
(if (not (and (setq tmp (cdr-safe variable))
(or (symbolp tmp)
(functionp tmp))))
(progn
(setq setter `(setf ,variable))
(setq getter variable))
(setq getter (car variable))
(setq setter `(funcall #',(cdr variable)))))
(:after-hook (setq after-hook (pop body)))
(_ (push keyw extra-keywords) (push (pop body) extra-keywords))))
(setq pretty-name (easy-mmode-pretty-mode-name mode lighter))
(setq keymap-sym (if (and keymap (symbolp keymap)) keymap
(intern (concat mode-name "-map"))))
(unless set (setq set '(:set #'custom-set-minor-mode)))
(unless initialize
(setq initialize '(:initialize #'custom-initialize-default)))
(unless type (setq type '(:type 'boolean)))
`(progn
,(cond
(variable nil)
((not globalp)
`(progn
:autoload-end
(defvar-local ,mode ,init-value
,(concat (format "Non-nil if %s is enabled.\n" pretty-name)
(internal--format-docstring-line
"Use the command `%s' to change this variable." mode)))))
(t
(let ((base-doc-string
(concat "Non-nil if %s is enabled.
See the `%s' command
for a description of this minor mode."
(if body "
Setting this variable directly does not take effect;
either customize it (see the info node `Easy Customization')
or call the function `%s'."))))
`(defcustom ,mode ,init-value
,(format base-doc-string pretty-name mode mode)
,@set
,@initialize
,@type
,@(nreverse extra-keywords)))))
,(funcall
warnwrap
`(defun ,modefun (&optional arg ,@extra-args)
,(easy-mmode--mode-docstring doc pretty-name keymap-sym
getter globalp)
,(when interactive
(if (consp interactive)
`(interactive
(list (if current-prefix-arg
(prefix-numeric-value current-prefix-arg)
'toggle))
,@interactive)
'(interactive
(list (if current-prefix-arg
(prefix-numeric-value current-prefix-arg)
'toggle)))))
(let ((,last-message (current-message)))
(,@setter
(cond ((eq arg 'toggle)
(not ,getter))
((and (numberp arg)
(< arg 1))
nil)
(t
t)))
,@(if globalp
`((when (boundp 'global-minor-modes)
(setq global-minor-modes
(delq ',modefun global-minor-modes))
(when ,getter
(push ',modefun global-minor-modes))))
`((when (boundp 'local-minor-modes)
(setq local-minor-modes
(delq ',modefun local-minor-modes))
(when ,getter
(push ',modefun local-minor-modes)))))
,@body
(run-hooks ',hook (if ,getter ',hook-on ',hook-off))
(if (called-interactively-p 'any)
(progn
,(if (and globalp (not variable))
`(customize-mark-as-set ',mode))
(unless (and (current-message)
(not (equal ,last-message
(current-message))))
(let ((local ,(if globalp "" " in current buffer")))
(message "%s %sabled%s" ,pretty-name
(if ,getter "en" "dis") local)))))
,@(when after-hook `(,after-hook)))
(force-mode-line-update)
,getter))
:autoload-end
(defvar ,hook nil)
(unless (get ',hook 'variable-documentation)
(put ',hook 'variable-documentation
,(format "Hook run after entering or leaving `%s'.
No problems result if this variable is not bound.
`add-hook' automatically binds it. (This is true for all hook variables.)"
modefun)))
(put ',hook 'custom-type 'hook)
(put ',hook 'standard-value (list nil))
,(unless (symbolp keymap)
`(defvar ,keymap-sym
(let ((m ,keymap))
(cond ((keymapp m) m)
((listp m)
(easy-mmode-define-keymap m))
(t (error "Invalid keymap %S" m))))
,(format "Keymap for `%s'." mode-name)))
,(let ((modevar (pcase getter (`(default-value ',v) v) (_ getter))))
(if (not (symbolp modevar))
(if (or lighter keymap)
(error ":lighter and :keymap unsupported with mode expression %S" getter))
`(with-no-warnings
(add-minor-mode ',modevar ',lighter
,(if keymap keymap-sym
`(if (boundp ',keymap-sym) ,keymap-sym))
nil
,(unless (eq mode modefun) `',modefun))))))))
;;; ---- ERT: Emacs Lisp Regression Testing (subset) ----
;; Ported from ERT: `should` / `should-not` / `should-error` / `skip-unless`
;; assertions, `ert-fail` / `ert-pass`, and `ert-deftest` with an optional
;; docstring plus `:expected-result` and `:tags` keyword args. Assertions signal
;; `ert-test-failed`; `skip-unless` signals `ert-test-skipped`. The runner
;; classifies each test as pass / fail / skip / expected-fail (XFAIL) /
;; unexpected-pass and returns the number of UNEXPECTED results (0 = all as
;; expected). `ert-run-tests-batch-and-exit` errors out on any unexpected one.
(defvar ert--tests nil) ; alist of (name . expected-result), :passed | :failed
(define-error 'ert-test-failed "Test failed")
(define-error 'ert-test-skipped "Test skipped")
;; should-failure explanation: for an assertion `(PRED ARG...)`, each ARG is
;; evaluated once and its value reported next to the form on failure — the way
;; ERT explains a failing `should`. Limited to known pure predicates so eager
;; argument evaluation can't change semantics; anything else falls back to a
;; plain truthiness check.
(defvar ert--explain-fns
'(= /= < > <= >= eq eql equal not null member memq assoc assq
stringp numberp integerp consp listp atom symbolp zerop))
(defun ert--let-binds (syms args)
(if (null syms) nil
(cons (list (car syms) (car args)) (ert--let-binds (cdr syms) (cdr args)))))
(defun ert--value-pairs (args syms)
(if (null args) nil
(cons (list 'cons (list 'quote (car args)) (car syms))
(ert--value-pairs (cdr args) (cdr syms)))))
(defun ert--argsyms (n)
(let ((i 0) (out nil))
(while (< i n)
(setq out (cons (intern (concat "--ert-a" (number-to-string i) "--")) out))
(setq i (1+ i)))
(reverse out)))
(defmacro should (form)
(if (and (consp form) (memq (car form) ert--explain-fns))
(let* ((fn (car form))
(args (cdr form))
(syms (ert--argsyms (length args))))
`(let ,(ert--let-binds syms args)
(if (,fn ,@syms) t
(signal 'ert-test-failed
(list 'should ',form :values (list ,@(ert--value-pairs args syms)))))))
`(if ,form t (signal 'ert-test-failed (list 'should ',form)))))
(defmacro should-not (form)
`(if ,form (signal 'ert-test-failed (list 'should-not ',form)) t))
(defmacro ert-info (_spec &rest body)
;; Compatibility shim: real ERT attaches the info string to failure reports
;; (which needs the ERT UI); here `ert-info` simply evaluates its BODY.
`(progn ,@body))
(defmacro should-error (form &rest keys)
(let* ((type (plist-get keys :type))
(check (if type (list 'not (list 'eq (list 'car '--ert-c--) type)) nil)))
`(let ((--ert-c-- (condition-case --ert-e-- (progn ,form 'ert--no-error)
(error --ert-e--))))
(cond
((eq --ert-c-- 'ert--no-error)
(signal 'ert-test-failed (list 'should-error :no-error ',form)))
(,check
(signal 'ert-test-failed (list 'should-error :wrong-type --ert-c--)))
(t --ert-c--)))))
(defmacro skip-unless (form)
`(unless ,form (signal 'ert-test-skipped (list 'skip-unless ',form))))
(defun ert-fail (data) (signal 'ert-test-failed data))
(defun ert-pass () t)
(defmacro ert-deftest (name arglist &rest body)
(declare (doc-string 3) (indent 2))
;; Strip an optional docstring, then leading :expected-result / :tags args.
(if (stringp (car body)) (setq body (cdr body)))
(let ((expected :passed))
(while (memq (car body) '(:expected-result :tags))
(if (eq (car body) :expected-result) (setq expected (car (cdr body))))
(setq body (cdr (cdr body))))
`(progn
(defun ,name ,arglist ,@body)
(setq ert--tests (cons (cons ',name ,expected) ert--tests))
',name)))
(defun ert-run-tests-batch ()
;; Test ORDER is by name, not by definition order. `ert-select-tests' walks
;; `ert--test-obarray' and `ert-run-tests-batch' takes them as they come out,
;; which for an obarray is alphabetical -- measured on 30.2 with ten
;; deliberately unsorted names (defined q7 b2 z9 a1 m5 c3 y8 d4 x6 e0, run
;; a1 b2 c3 d4 e0 m5 q7 x6 y8 z9). Running in definition order let a test
;; depend on an earlier one's side effects and pass here while failing under
;; `emacs -Q --batch -l'.
(let ((tests (sort (reverse ert--tests)
(lambda (a b) (string-lessp (symbol-name (car a))
(symbol-name (car b))))))
(total 0) (unexpected 0) (skipped 0))
(while tests
(let* ((entry (car tests)) (name (car entry)) (expected (cdr entry)))
(setq total (1+ total))
(condition-case --ert-err--
;; `ert--run-test-internal' (ert.el:796) runs the body inside
;; `(with-temp-buffer (save-window-excursion …))', so a test body
;; starts in ` *temp*' with the standard syntax table -- not in
;; `*scratch*' under `emacs-lisp-mode-syntax-table'. Measured:
;; emacs: TOP buf="*scratch*" cs.=95 BODY buf=" *temp*" cs.=46
;; and elisprs used to answer 95 in the body too.
(with-temp-buffer
(funcall name)
(if (eq expected :failed)
(progn (setq unexpected (1+ unexpected))
(message " UNEXPECTED-OK %s" name))
(message " PASS %s" name)))
(ert-test-skipped
(setq skipped (1+ skipped))
(message " SKIP %s" name))
(error
(if (eq expected :failed)
(message " XFAIL %s" name)
(progn (setq unexpected (1+ unexpected))
(message " FAIL %s -- %S" name --ert-err--))))))
(setq tests (cdr tests)))
(message "Ran %d tests: %d unexpected, %d skipped." total unexpected skipped)
unexpected))
(defun ert-run-tests-batch-and-exit ()
"Run all tests; raise an error (→ non-zero exit) on any unexpected result."
(let ((bad (ert-run-tests-batch)))
(if (> bad 0) (error "%d unexpected ERT result(s)" bad) t)))
;;; ---- oclosure (Open Closures) ----
;; Faithful port of emacs-lisp/oclosure.el (Emacs 30.2). An OClosure is a
;; closure that also carries a type (for cl-generic dispatch) and named,
;; optionally-mutable slots reachable from outside via generated accessors.
;;
;; elisprs divergences from oclosure.el (NAMED — the observable API matches the
;; Emacs binary exactly; only the host-specific internals differ):
;; * The C primitives `oclosure--get/--set/--copy/--fix-type', `oclosure-type'
;; and `closurep' are Rust builtins (src/builtins.rs), because elisprs closures
;; are compiled (a fusevm Chunk + captured env), not aref-indexable
;; interpreted-functions. Slot values live in the closure's captured lexical
;; env (the same storage the body reads), so `oclosure--set' and an in-body
;; `setq' stay mutually visible — exactly as Emacs stores slots in the env.
;; * `oclosure-define' installs the class AND the accessors/copiers in one
;; runtime call (`oclosure--define'); Emacs splits this across an
;; eval-and-compile class registration and a compile-time
;; `oclosure--define-functions' macro. Merging is safe because top-level forms
;; are evaluated in order, so the class is registered before the next form's
;; macroexpansion (which `oclosure-lambda' needs).
;; * The cl--class / cl-slot-descriptor substrate (from cl-preloaded.el) is
;; provided here minimally: the `closure' parent is a plain class object rather
;; than the full built-in-type hierarchy.
;; * The cl-print pretty-printer methods for accessors are omitted (cosmetic).
;; -- helpers not yet in the prelude --
;; macroexp--fgrep (macroexp.el:724): return those of BINDINGS whose var/func
;; symbol appears anywhere in SEXP — a poor-man's free-variable test used by
;; cl-generic to decide whether a method body references `cl-call-next-method'.
;; Faithful port, including the tortoise/hare cycle guard for cyclic data.
(defun macroexp--fgrep (bindings sexp)
(let ((res '())
(seen (make-hash-table :test #'eq))
(sexpss (list (list sexp))))
(while (and sexpss bindings)
(let ((sexps (pop sexpss)))
(unless (gethash sexps seen)
(puthash sexps t seen)
(if (vectorp sexps) (setq sexps (mapcar #'identity sexps)))
(let ((tortoise sexps) (skip t))
(while sexps
(let ((sexp (if (consp sexps) (pop sexps)
(prog1 sexps (setq sexps nil)))))
(if skip
(setq skip nil)
(setq tortoise (cdr tortoise))
(if (eq tortoise sexps)
(setq sexps nil)
(setq skip t)))
(cond
((or (consp sexp) (vectorp sexp)) (push sexp sexpss))
(t
(let ((tmp (assq sexp bindings)))
(when tmp
(push tmp res)
(setq bindings (remove tmp bindings))))))))))))
res))
(defconst cl--lambda-list-keywords
'(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
(defun cl--arglist-args (args)
(if (not (listp args)) (list args)
(let ((res nil) (kind nil) arg)
(while (consp args)
(setq arg (pop args))
(if (memq arg cl--lambda-list-keywords) (setq kind arg)
(if (eq arg '&cl-defs) (pop args)
(and (consp arg) kind (setq arg (car arg)))
(and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
(setq res (nconc res (cl--arglist-args arg))))))
(nconc res (and args (list args))))))
(defun gv-setter (name)
"Return the symbol where the (setf NAME) function should be placed."
(intern (format "(setf %s)" name)))
;; -- cl--class / cl-slot-descriptor substrate (subset of cl-preloaded.el) --
(defun cl--find-class (name) (get name 'cl--class))
(cl-defstruct (cl-slot-descriptor
(:conc-name cl--slot-descriptor-)
(:constructor nil)
(:constructor cl--make-slot-descriptor (name &optional initform type props)))
name initform type props)
(cl-defstruct (cl--class (:constructor nil))
name docstring parents slots index-table)
(cl-defstruct (oclosure--class (:include cl--class))
allparents)
;; -- built-in type class registry (faithful port of cl-preloaded.el) --
;; cl-generic's typeof generalizer dispatches on the class DAG registered here:
;; `cl--generic-type-specializers' looks up the class of `cl-type-of' and walks
;; `cl--class-allparents'. Without this, cl-generic-generalizers signals
;; "Unknown specializer integer" on the built-in-type prefill in cl-generic.el.
;; cl-preloaded.el:299 — the linearised parent list, most specific first.
(defun cl--class-allparents (class)
(cons (cl--class-name class)
(merge-ordered-lists (mapcar #'cl--class-allparents
(cl--class-parents class)))))
;; cl-preloaded.el:304 — type descriptors for built-in types.
(cl-defstruct (built-in-class
(:include cl--class)
(:noinline t)
(:constructor nil)
(:constructor built-in-class--make (name docstring parents))
(:copier nil))
"Type descriptors for built-in types.
The `slots' (and hence `index-table') are currently unused."
)
;; cl-preloaded.el:314 — register a built-in type NAME with PARENTS.
(defmacro cl--define-built-in-type (name parents &optional docstring &rest slots)
(declare (indent 2) (doc-string 3))
(unless (listp parents) (setq parents (list parents)))
(unless (or parents (eq name t))
(error "Missing parents for %S: %S" name parents))
(let ((predicate (intern-soft (format
(if (string-match "-" (symbol-name name))
"%s-p" "%sp")
name))))
(unless (fboundp predicate) (setq predicate nil))
(while (keywordp (car slots))
(let ((kw (pop slots)) (val (pop slots)))
(pcase kw
(:predicate (setq predicate val))
(_ (error "Unknown keyword arg: %S" kw)))))
`(progn
,(if predicate `(put ',name 'cl-deftype-satisfies #',predicate)
nil)
(put ',name 'cl--class
(built-in-class--make ',name ,docstring
(mapcar (lambda (type)
(let ((class (get type 'cl--class)))
(unless class
(error "Unknown type: %S" type))
class))
',parents))))))
;; cl-preloaded.el:353 — like `functionp' but nil for lists and symbols.
(defun cl-functionp (object)
"Return non-nil if OBJECT is a member of type `function'.
This is like `functionp' except that it returns nil for all lists and symbols,
regardless if `funcall' would accept to call them."
(memq (cl-type-of object)
'(primitive-function native-comp-function module-function
interpreted-function byte-code-function)))
;; cl-preloaded.el:361-472 — the built-in type DAG, parents before children.
(cl--define-built-in-type t nil "Abstract supertype of everything.")
(cl--define-built-in-type atom t "Abstract supertype of anything but cons cells."
:predicate atom)
(cl--define-built-in-type tree-sitter-compiled-query atom)
(cl--define-built-in-type tree-sitter-node atom)
(cl--define-built-in-type tree-sitter-parser atom)
(when (fboundp 'user-ptrp)
(cl--define-built-in-type user-ptr atom nil
:predicate user-ptrp))
(cl--define-built-in-type font-object atom)
(cl--define-built-in-type font-entity atom)
(cl--define-built-in-type font-spec atom)
(cl--define-built-in-type condvar atom)
(cl--define-built-in-type mutex atom)
(cl--define-built-in-type thread atom)
(cl--define-built-in-type terminal atom)
(cl--define-built-in-type hash-table atom)
(cl--define-built-in-type frame atom)
(cl--define-built-in-type buffer atom)
(cl--define-built-in-type window atom)
(cl--define-built-in-type process atom)
(cl--define-built-in-type finalizer atom)
(cl--define-built-in-type window-configuration atom)
(cl--define-built-in-type overlay atom)
(cl--define-built-in-type number-or-marker atom
"Abstract supertype of both `number's and `marker's.")
(cl--define-built-in-type symbol atom
"Type of symbols."
(name symbol-name)
(value symbol-value)
(function symbol-function)
(plist symbol-plist))
(cl--define-built-in-type obarray atom)
(cl--define-built-in-type native-comp-unit atom)
(cl--define-built-in-type sequence t "Abstract supertype of sequences.")
(cl--define-built-in-type list sequence)
(cl--define-built-in-type array (sequence atom) "Abstract supertype of arrays.")
(cl--define-built-in-type number (number-or-marker)
"Abstract supertype of numbers.")
(cl--define-built-in-type float (number))
(cl--define-built-in-type integer-or-marker (number-or-marker)
"Abstract supertype of both `integer's and `marker's.")
(cl--define-built-in-type integer (number integer-or-marker))
(cl--define-built-in-type marker (integer-or-marker))
(cl--define-built-in-type bignum (integer)
"Type of those integers too large to fit in a `fixnum'.")
(cl--define-built-in-type fixnum (integer)
"Type of small (fixed-size) integers.")
(cl--define-built-in-type boolean (symbol)
"Type of the canonical boolean values, i.e. either nil or t.")
(cl--define-built-in-type symbol-with-pos (symbol)
"Type of symbols augmented with source-position information.")
(cl--define-built-in-type vector (array))
(cl--define-built-in-type record (atom)
"Abstract type of objects with slots.")
(cl--define-built-in-type bool-vector (array) "Type of bitvectors.")
(cl--define-built-in-type char-table (array)
"Type of special arrays that are indexed by characters.")
(cl--define-built-in-type string (array))
(cl--define-built-in-type null (boolean list)
"Type of the nil value."
:predicate null)
(cl--define-built-in-type cons (list)
"Type of cons cells."
(car car) (cdr cdr))
(cl--define-built-in-type function (atom)
"Abstract supertype of function values.")
(cl--define-built-in-type compiled-function (function)
"Abstract type of functions that have been compiled.")
(cl--define-built-in-type closure (function)
"Abstract type of functions represented by a vector-like object.")
(cl--define-built-in-type byte-code-function (compiled-function closure)
"Type of functions that have been byte-compiled.")
(cl--define-built-in-type subr (atom)
"Abstract type of functions compiled to machine code.")
(cl--define-built-in-type module-function (function)
"Type of functions provided via the module API.")
(cl--define-built-in-type interpreted-function (closure)
"Type of functions that have not been compiled.")
(cl--define-built-in-type special-form (subr)
"Type of the core syntactic elements of the Emacs Lisp language.")
(cl--define-built-in-type native-comp-function (subr compiled-function)
"Type of functions that have been compiled by the native compiler.")
(cl--define-built-in-type primitive-function (subr compiled-function)
"Type of functions hand written in C.")
;; cl-preloaded.el: the derived types defined alongside the built-in ones.
(cl-deftype natnum () (declare (parents integer)) '(satisfies natnump))
(cl-deftype keyword () (declare (parents symbol)) '(satisfies keywordp))
(cl-deftype command () '(satisfies commandp))
;; cl-macs.el: the character and real-number derived types.
(cl-deftype character () (declare (parents fixnum natnum))
'(and fixnum natnum))
(cl-deftype base-char () (declare (parents character))
'(satisfies characterp))
(cl-deftype extended-char () (declare (parents character))
'(and character (not base-char)))
(cl-deftype real (&optional min max)
(list 'and 'number
(if (memq min '(* nil)) t
`(satisfies . ,(if (consp min)
(lambda (val) (> val (car min)))
(lambda (val) (>= val min)))))
(if (memq max '(* nil)) t
`(satisfies . ,(if (consp max)
(lambda (val) (< val (car max)))
(lambda (val) (<= val max)))))))
;; -- cl-defstruct class registry (faithful subset of cl-preloaded.el) --
;; cl-generic's typeof generalizer also dispatches on cl-defstruct types: it
;; needs `cl--find-class NAME' to return a `cl-structure-class' object. Every
;; `cl-defstruct' now registers one (see the guarded form emitted by the macro);
;; the two metaclasses below and their parent chain (record → cl-structure-object
;; → cl--class → cl-structure-class) are bootstrapped by hand, matching the DAG
;; `cl--class-allparents' walks (binary-verified against GNU Emacs 30.2).
;; cl-preloaded.el:207 — the type of CL struct descriptors. Extra slots beyond
;; those inherited from cl--class are kept for layout fidelity though the
;; cluster's load path only reads name/parents.
(cl-defstruct (cl-structure-class
(:include cl--class)
(:conc-name cl--struct-class-)
(:predicate cl--struct-class-p)
(:constructor nil)
(:constructor cl--struct-new-class
(name docstring parents type named slots index-table
children-sym tag print))
(:copier nil))
"The type of CL structs descriptors."
(tag nil) (type nil) (named nil) (print nil) (children-sym nil))
;; cl-preloaded.el:232 — the root parent of all "normal" CL structs.
(cl-defstruct (cl-structure-object
(:predicate cl-struct-p)
(:constructor nil)
(:copier nil))
"The root parent of all \"normal\" CL structs")
;; Bootstrap the metaclass chain by hand (the `cl-defstruct' auto-registration
;; above short-circuits until cl-structure-object is registered).
(put 'cl-structure-object 'cl--class
(cl--struct-new-class 'cl-structure-object nil (list (cl--find-class 'record))
nil nil nil nil nil nil nil))
(put 'cl--class 'cl--class
(cl--struct-new-class 'cl--class nil (list (cl--find-class 'cl-structure-object))
nil nil nil nil nil nil nil))
(put 'cl-structure-class 'cl--class
(cl--struct-new-class 'cl-structure-class nil (list (cl--find-class 'cl--class))
nil nil nil nil nil nil nil))
(defun oclosure--index-table (slotdescs)
(let ((i -1)
(it (make-hash-table :test 'eq)))
(dolist (desc slotdescs)
(let ((slot (cl--slot-descriptor-name desc)))
(cl-incf i)
(when (gethash slot it)
(error "Duplicate slot name: %S" slot))
(setf (gethash slot it) i)))
it))
(defun oclosure--class-make (name docstring slots parents allparents)
(make-oclosure--class :name name :docstring docstring :parents parents
:slots slots :index-table (oclosure--index-table slots)
:allparents allparents))
;; The `closure' parent class (minimal), then the `oclosure' root.
(setf (cl--find-class 'closure)
(make-oclosure--class :name 'closure :allparents '(closure)))
(setf (cl--find-class 'oclosure)
(oclosure--class-make 'oclosure
"The root parent of all OClosure types"
nil (list (cl--find-class 'closure))
'(oclosure)))
(defun oclosure--p (oclosure)
(not (not (oclosure-type oclosure))))
(cl-deftype oclosure () '(satisfies oclosure--p))
(defun oclosure--slot-mutable-p (slotdesc)
(not (alist-get :read-only (cl--slot-descriptor-props slotdesc))))
(defun oclosure--build-class (name docstring parent-names slots)
(cl-assert (null (cdr parent-names)))
(let* ((parent-class (let ((pname (or (car parent-names) 'oclosure)))
(or (cl--find-class pname)
(error "Unknown class: %S" pname))))
(slotdescs
(append
(oclosure--class-slots parent-class)
(mapcar (lambda (field)
(if (not (consp field))
(cl--make-slot-descriptor field nil nil
'((:read-only . t)))
(let ((sname (pop field))
(type nil)
(read-only t)
(props '()))
(while field
(pcase (pop field)
(:mutable (setq read-only (not (car field))))
(:type (setq type (car field)))
(p (message "Unknown property: %S" p)
(push (cons p (car field)) props)))
(setq field (cdr field)))
(cl--make-slot-descriptor sname nil type
`((:read-only . ,read-only)
,@props)))))
slots))))
(oclosure--class-make name docstring slotdescs
(if (cdr parent-names)
(oclosure--class-parents parent-class)
(list parent-class))
(cons name (oclosure--class-allparents
parent-class)))))
(defun oclosure--defstruct-make-copiers (copiers slotdescs name)
(let* ((mutables '())
(slots (mapcar
(lambda (desc)
(let ((sname (cl--slot-descriptor-name desc)))
(when (oclosure--slot-mutable-p desc)
(push sname mutables))
sname))
slotdescs)))
(mapcar
(lambda (copier)
(pcase-let*
((cname (pop copier))
(args (or (pop copier) `(&key ,@slots)))
(inline (and (eq :inline (car copier)) (pop copier)))
(doc (or (pop copier)
(format "Copier for objects of type `%s'." name)))
(obj (make-symbol "obj"))
(absent (make-symbol "absent"))
(anames (cl--arglist-args args))
(mnames
(let ((res '()) (tmp args))
(while (and tmp (not (memq (car tmp) cl--lambda-list-keywords)))
(push (pop tmp) res))
res))
(has-kw (let ((k nil))
(dolist (a args)
(when (memq a cl--lambda-list-keywords) (setq k t)))
k))
(index -1)
(mutlist '())
(argvals
(mapcar
(lambda (slot)
(setq index (1+ index))
(let* ((mutable (memq slot mutables))
(get `(oclosure--get ,obj ,index ,(not (not mutable)))))
(push mutable mutlist)
(cond
((not (memq slot anames)) get)
((memq slot mnames) slot)
(t `(if (eq ',absent ,slot) ,get ,slot)))))
slots)))
`(,(if inline 'cl-defsubst 'cl-defun) ,cname
,(if has-kw `(&cl-defs (',absent) ,obj ,@args) `(,obj ,@args))
,doc
(oclosure--copy ,obj ',(if (remq nil mutlist) (nreverse mutlist))
,@argvals))))
copiers)))
(defun oclosure--install-functions (name copiers)
(let* ((class (cl--find-class name))
(slotdescs (oclosure--class-slots class))
(i -1))
(dolist (desc slotdescs)
(setq i (1+ i))
(let* ((slot (cl--slot-descriptor-name desc))
(mutable (oclosure--slot-mutable-p desc))
(aname (intern (format "%S--%S" name slot))))
(if (not mutable)
(defalias aname
(oclosure--copy oclosure--accessor-prototype nil name slot i))
(defalias aname
(oclosure--accessor-copy oclosure--mut-getter-prototype name slot i))
(defalias (gv-setter aname)
(oclosure--accessor-copy oclosure--mut-setter-prototype name slot i)))))
(dolist (form (oclosure--defstruct-make-copiers copiers slotdescs name))
(eval form t))))
(defun oclosure--define (name docstring parent-names slots &rest props)
(let* ((class (oclosure--build-class name docstring parent-names slots))
(pred (lambda (oclosure)
(let ((type (oclosure-type oclosure)))
(when type
(memq name (oclosure--class-allparents
(cl--find-class type)))))))
(predname (or (plist-get props :predicate)
(intern (format "%s--internal-p" name)))))
(setf (cl--find-class name) class)
(dolist (slot (oclosure--class-slots class))
(put (cl--slot-descriptor-name slot) 'slot-name t))
(defalias predname pred)
(put name 'cl-deftype-satisfies predname)
(oclosure--install-functions name (plist-get props :copiers))
name))
(defmacro oclosure-define (name &optional docstring &rest slots)
"Define a new OClosure type."
(declare (doc-string 2) (indent 1))
(unless (or (stringp docstring) (null docstring))
(push docstring slots)
(setq docstring nil))
(let* ((options (when (consp name)
(prog1 (copy-sequence (cdr name))
(setq name (car name)))))
(get-opt (lambda (opt &optional all)
(let ((val (assq opt options))
tmp)
(when val (setq options (delq val options)))
(if (not all)
(cdr val)
(when val
(setq val (list (cdr val)))
(while (setq tmp (assq opt options))
(push (cdr tmp) val)
(setq options (delq tmp options)))
(nreverse val))))))
(predicate (car (funcall get-opt :predicate)))
(parent-names (or (funcall get-opt :parent)
(funcall get-opt :include)))
(copiers (funcall get-opt :copier 'all)))
`(oclosure--define ',name ,docstring ',parent-names ',slots
,@(when predicate `(:predicate ',predicate))
:copiers ',copiers)))
(defmacro oclosure--lambda (type bindings mutables args &rest body)
"Low level construction of an OClosure object."
(declare (indent 3) (debug (sexp (&rest (sexp form)) sexp def-body)))
(let* ((parsed (macroexp-parse-body body))
(prebody (car parsed))
(realbody (cdr parsed))
(slotnames (mapcar #'car bindings)))
`(let ,(mapcar (lambda (bind)
(if (cdr bind) bind
`(,(car bind) (progn nil))))
(reverse bindings))
(oclosure--fix-type ,type ',slotnames ',mutables
(lambda ,args
,@prebody
(if t nil ,@slotnames
,@(mapcar (lambda (m) `(setq ,m ,m)) mutables))
,@realbody)))))
(defmacro oclosure-lambda (type-and-slots args &rest body)
"Define anonymous OClosure function."
(declare (indent 2))
(let* ((type (car type-and-slots))
(fields (cdr type-and-slots))
(class (or (cl--find-class type)
(error "Unknown class: %S" type)))
(slots (oclosure--class-slots class))
(mutables '())
(slotbinds (mapcar (lambda (slot)
(let ((sname (cl--slot-descriptor-name slot)))
(when (oclosure--slot-mutable-p slot)
(push sname mutables))
(list sname)))
slots))
(tempbinds (mapcar
(lambda (field)
(let* ((fname (car field))
(bind (assq fname slotbinds)))
(cond
((not bind) (error "Unknown slot: %S" fname))
((cdr bind) (error "Duplicate slot: %S" fname))
(t (let ((temp (gensym "temp")))
(setcdr bind (list temp))
(cons temp (cdr field)))))))
fields)))
`(let ,tempbinds
(oclosure--lambda ',type ,slotbinds ,mutables ,args ,@body))))
(defun oclosure--slot-index (oclosure slotname)
(gethash slotname
(oclosure--class-index-table
(cl--find-class (oclosure-type oclosure)))))
(defun oclosure--slot-value (oclosure slotname)
(let ((class (cl--find-class (oclosure-type oclosure)))
(index (oclosure--slot-index oclosure slotname)))
(oclosure--get oclosure index
(oclosure--slot-mutable-p
(nth index (oclosure--class-slots class))))))
(defun oclosure--set-slot-value (oclosure slotname value)
(let ((class (cl--find-class (oclosure-type oclosure)))
(index (oclosure--slot-index oclosure slotname)))
(unless (oclosure--slot-mutable-p
(nth index (oclosure--class-slots class)))
(signal 'setting-constant (list oclosure slotname)))
(oclosure--set value oclosure index)))
;; Accessor prototype + the `accessor'/`oclosure-accessor' types (bootstrapped
;; exactly like oclosure.el).
(defconst oclosure--accessor-prototype
(oclosure--lambda 'oclosure-accessor ((type) (slot) (index)) nil
(oclosure) (oclosure--get oclosure index nil)))
(oclosure-define accessor
"OClosure function to access a specific slot of an object."
type slot)
(oclosure-define (oclosure-accessor
(:parent accessor)
(:copier oclosure--accessor-copy (type slot index)))
"OClosure function to access a specific slot of an OClosure function."
index)
(defconst oclosure--mut-getter-prototype
(oclosure-lambda (oclosure-accessor (type) (slot) (index)) (oclosure)
(oclosure--get oclosure index t)))
(defconst oclosure--mut-setter-prototype
(oclosure-lambda (oclosure-accessor (type) (slot) (index)) (val oclosure)
(oclosure--set val oclosure index)))
(oclosure-define (save-some-buffers-function
(:predicate save-some-buffers-function--p)))
(oclosure-define (cconv--interactive-helper) fun if)
(defun cconv--interactive-helper (fun if)
"Add interactive \"form\" IF to FUN."
(oclosure-lambda (cconv--interactive-helper (fun fun) (if if))
(&rest args)
(apply (if (called-interactively-p 'any)
#'funcall-interactively #'funcall)
fun args)))
(provide 'oclosure)
;;; ---- coding systems (predicate/registry subset) ----
;; Faithful to GNU Emacs 30.2's built-in coding-system registry. Only the
;; registration/predicate surface is ported: `coding-system-p', `coding-system-base',
;; `coding-system-list', `check-coding-system'. The actual encode/decode machinery
;; (define-coding-system-internal and the charset codecs) is not implemented here.
;; Registry data captured value-for-value from `emacs -Q --batch' via
;; (coding-system-list) and (coding-system-list t).
(define-error 'coding-system-error "Invalid coding system")
(defconst coding-system--all
'(
binary no-conversion undecided prefer-utf-8 raw-text no-conversion-multibyte latin-1 iso-8859-1
iso-latin-1 emacs-mule cp65001 mule-utf-8 utf-8 utf-8-with-signature utf-8-auto utf-8-emacs
utf-16le utf-16be utf-16-le utf-16le-with-signature utf-16-be utf-16be-with-signature utf-16 iso-2022-7bit
iso-2022-7bit-ss2 iso-2022-int-1 iso-2022-7bit-lock iso-2022-cjk iso-2022-7bit-lock-ss2 iso-2022-8bit-ss2 ctext x-ctext
compound-text ctext-no-compositions ctext-with-extensions x-ctext-with-extensions compound-text-with-extensions ascii iso-safe us-ascii
utf-7 utf-7-imap chinese-iso-7bit iso-2022-cn iso-2022-cn-ext gb2312 cn-gb euc-cn
euc-china cn-gb-2312 chinese-iso-8bit hz hz-gb-2312 chinese-hz cp950 cn-big5
big5 chinese-big5 cn-big5-hkscs big5-hkscs chinese-big5-hkscs euc-taiwan euc-tw windows-936
cp936 gbk chinese-gbk gb18030 chinese-gb18030 iso-8859-5 cyrillic-iso-8bit cp878
koi8 koi8-r cyrillic-koi8 koi8-u alternativnyj cyrillic-alternativnyj cp866 koi8-t
cp1251 windows-1251 cp866u ruscii cp1125 ibm855 cp855 mik
pt154 devanagari in-is13194-devanagari ebcdic-us ebcdic-uk cp1047 ibm1047 cp038
ebcdic-int ibm038 latin-2 iso-8859-2 iso-latin-2 latin-3 iso-8859-3 iso-latin-3
latin-4 iso-8859-4 iso-latin-4 latin-5 iso-8859-9 iso-latin-5 latin-6 iso-8859-10
iso-latin-6 latin-7 iso-8859-13 iso-latin-7 latin-8 iso-8859-14 iso-latin-8 latin-0
latin-9 iso-8859-15 iso-latin-9 cp1250 windows-1250 cp1252 windows-1252 cp1254
windows-1254 cp1257 windows-1257 cp256 ebcdic-int1 ibm256 cp273 ibm273
cp274 ebcdic-be ibm274 cp275 ebcdic-br ibm275 cp277 ebcdic-cp-no
ebcdic-cp-dk ibm277 cp278 ebcdic-cp-se ebcdic-cp-fi ibm278 cp280 ebcdic-cp-it
ibm280 cp284 ebcdic-cp-es ibm284 cp285 ebcdic-cp-gb ibm285 cp297
ebcdic-cp-fr ibm297 ibm775 cp775 ibm850 cp850 ibm852 cp852
ibm857 cp857 cp858 ibm860 cp860 ibm861 cp861 ibm863
cp863 ibm865 cp865 ibm437 cp437 macintosh mac-roman next
roman8 hp-roman8 adobe-standard-encoding latin-10 iso-8859-16 iso-latin-10 iso-8859-7 greek-iso-8bit
cp1253 windows-1253 cp737 ibm851 cp851 ibm869 cp869 iso-8859-8-i
iso-8859-8-e iso-8859-8 hebrew-iso-8bit cp1255 windows-1255 ibm862 cp862 junet
iso-2022-jp iso-2022-jp-2 sjis shift_jis japanese-shift-jis cp932 japanese-cp932 old-jis
iso-2022-jp-1978-irv japanese-iso-7bit-1978-irv euc-jp euc-japan euc-japan-1990 japanese-iso-8bit eucjp-ms iso-2022-jp-3
iso-2022-jp-2004 euc-jisx0213 euc-jis-2004 shift_jis-2004 japanese-shift-jis-2004 cp281 ebcdic-jp-e ibm281
cp290 ebcdic-jp-kana ibm290 ks_c_5601-1987 euc-korea euc-kr korean-iso-8bit korean-iso-7bit-lock
iso-2022-kr cp949 korean-cp949 lao tis-620 tis620 th-tis620 thai-tis620
ibm874 cp874 iso-8859-11 tibetan tibetan-iso-8bit viscii vietnamese-viscii tcvn-5712
tcvn vietnamese-tcvn vscii vietnamese-vscii viqr vietnamese-viqr cp1258 windows-1258
iso-8859-6 cp1256 windows-1256 georgian-ps georgian-academy
)
"All built-in coding-system names (base systems and aliases), GNU Emacs 30.2.")
(defconst coding-system--alias-alist
'(
(binary . no-conversion) (latin-1 . iso-latin-1) (iso-8859-1 . iso-latin-1) (cp65001 . utf-8)
(mule-utf-8 . utf-8) (utf-16-le . utf-16le-with-signature) (utf-16-be . utf-16be-with-signature) (iso-2022-int-1 . iso-2022-7bit-lock)
(iso-2022-cjk . iso-2022-7bit-lock-ss2) (ctext . compound-text) (x-ctext . compound-text) (ctext-with-extensions . compound-text-with-extensions)
(x-ctext-with-extensions . compound-text-with-extensions) (ascii . us-ascii) (iso-safe . us-ascii) (chinese-iso-7bit . iso-2022-cn)
(gb2312 . chinese-iso-8bit) (cn-gb . chinese-iso-8bit) (euc-cn . chinese-iso-8bit) (euc-china . chinese-iso-8bit)
(cn-gb-2312 . chinese-iso-8bit) (hz . chinese-hz) (hz-gb-2312 . chinese-hz) (cp950 . chinese-big5)
(cn-big5 . chinese-big5) (big5 . chinese-big5) (cn-big5-hkscs . chinese-big5-hkscs) (big5-hkscs . chinese-big5-hkscs)
(euc-taiwan . euc-tw) (windows-936 . chinese-gbk) (cp936 . chinese-gbk) (gbk . chinese-gbk)
(gb18030 . chinese-gb18030) (iso-8859-5 . cyrillic-iso-8bit) (cp878 . cyrillic-koi8) (koi8 . cyrillic-koi8)
(koi8-r . cyrillic-koi8) (alternativnyj . cyrillic-alternativnyj) (cp1251 . windows-1251) (cp866u . cp1125)
(ruscii . cp1125) (ibm855 . cp855) (devanagari . in-is13194-devanagari) (cp1047 . ibm1047)
(cp038 . ibm038) (ebcdic-int . ibm038) (latin-2 . iso-latin-2) (iso-8859-2 . iso-latin-2)
(latin-3 . iso-latin-3) (iso-8859-3 . iso-latin-3) (latin-4 . iso-latin-4) (iso-8859-4 . iso-latin-4)
(latin-5 . iso-latin-5) (iso-8859-9 . iso-latin-5) (latin-6 . iso-latin-6) (iso-8859-10 . iso-latin-6)
(latin-7 . iso-latin-7) (iso-8859-13 . iso-latin-7) (latin-8 . iso-latin-8) (iso-8859-14 . iso-latin-8)
(latin-0 . iso-latin-9) (latin-9 . iso-latin-9) (iso-8859-15 . iso-latin-9) (cp1250 . windows-1250)
(cp1252 . windows-1252) (cp1254 . windows-1254) (cp1257 . windows-1257) (cp256 . ibm256)
(ebcdic-int1 . ibm256) (cp273 . ibm273) (cp274 . ibm274) (ebcdic-be . ibm274)
(cp275 . ibm275) (ebcdic-br . ibm275) (cp277 . ibm277) (ebcdic-cp-no . ibm277)
(ebcdic-cp-dk . ibm277) (cp278 . ibm278) (ebcdic-cp-se . ibm278) (ebcdic-cp-fi . ibm278)
(cp280 . ibm280) (ebcdic-cp-it . ibm280) (cp284 . ibm284) (ebcdic-cp-es . ibm284)
(cp285 . ibm285) (ebcdic-cp-gb . ibm285) (cp297 . ibm297) (ebcdic-cp-fr . ibm297)
(ibm775 . cp775) (ibm850 . cp850) (ibm852 . cp852) (ibm857 . cp857)
(ibm860 . cp860) (ibm861 . cp861) (ibm863 . cp863) (ibm865 . cp865)
(ibm437 . cp437) (macintosh . mac-roman) (roman8 . hp-roman8) (latin-10 . iso-latin-10)
(iso-8859-16 . iso-latin-10) (iso-8859-7 . greek-iso-8bit) (cp1253 . windows-1253) (ibm851 . cp851)
(ibm869 . cp869) (iso-8859-8-i . hebrew-iso-8bit) (iso-8859-8-e . hebrew-iso-8bit) (iso-8859-8 . hebrew-iso-8bit)
(cp1255 . windows-1255) (ibm862 . cp862) (junet . iso-2022-jp) (sjis . japanese-shift-jis)
(shift_jis . japanese-shift-jis) (cp932 . japanese-cp932) (old-jis . japanese-iso-7bit-1978-irv) (iso-2022-jp-1978-irv . japanese-iso-7bit-1978-irv)
(euc-jp . japanese-iso-8bit) (euc-japan . japanese-iso-8bit) (euc-japan-1990 . japanese-iso-8bit) (iso-2022-jp-3 . iso-2022-jp-2004)
(euc-jisx0213 . euc-jis-2004) (shift_jis-2004 . japanese-shift-jis-2004) (cp281 . ibm281) (ebcdic-jp-e . ibm281)
(cp290 . ibm290) (ebcdic-jp-kana . ibm290) (ks_c_5601-1987 . korean-iso-8bit) (euc-korea . korean-iso-8bit)
(euc-kr . korean-iso-8bit) (korean-iso-7bit-lock . iso-2022-kr) (cp949 . korean-cp949) (tis-620 . thai-tis620)
(tis620 . thai-tis620) (th-tis620 . thai-tis620) (ibm874 . cp874) (tibetan . tibetan-iso-8bit)
(viscii . vietnamese-viscii) (tcvn-5712 . vietnamese-vscii) (tcvn . vietnamese-vscii) (vietnamese-tcvn . vietnamese-vscii)
(vscii . vietnamese-vscii) (viqr . vietnamese-viqr) (cp1258 . windows-1258) (cp1256 . windows-1256)
)
"Alist mapping each alias coding-system to its base coding-system, GNU Emacs 30.2.")
(defun coding-system--strip-eol (name)
"Strip one trailing -unix/-dos/-mac EOL suffix from string NAME."
(cond ((string-suffix-p "-unix" name) (substring name 0 -5))
((string-suffix-p "-dos" name) (substring name 0 -4))
((string-suffix-p "-mac" name) (substring name 0 -4))
(t name)))
(defun coding-system-p (object)
"Return t if OBJECT is nil or a coding system.
See the documentation of `define-coding-system' for information
about coding-system objects."
(or (null object)
(and (symbolp object)
(and (memq (intern (coding-system--strip-eol (symbol-name object)))
coding-system--all)
t))))
(defun coding-system-base (coding-system)
"Return the base of CODING-SYSTEM.
Any alias or end-of-line variant resolves to its base coding system.
If CODING-SYSTEM is invalid, signal a `coding-system-error'."
(if (null coding-system)
'no-conversion
(progn
(check-coding-system coding-system)
(let* ((base (intern (coding-system--strip-eol (symbol-name coding-system))))
(resolved (assq base coding-system--alias-alist)))
(if resolved (cdr resolved) base)))))
(defun coding-system-list (&optional base-only)
"Return a list of all existing non-subsidiary coding systems.
If optional arg BASE-ONLY is non-nil, only base coding systems are listed."
(if base-only
(let ((result nil))
(dolist (cs coding-system--all)
(unless (assq cs coding-system--alias-alist)
(push cs result)))
(nreverse result))
(copy-sequence coding-system--all)))
(defun check-coding-system (coding-system)
"Check validity of CODING-SYSTEM.
If valid, return CODING-SYSTEM, else signal a `coding-system-error'."
(if (coding-system-p coding-system)
coding-system
(signal 'coding-system-error (list coding-system))))
(defconst coding-system--eol-fixed
'(no-conversion no-conversion-multibyte binary)
"Registered coding systems whose EOL type is fixed to `unix' (0), GNU Emacs 30.2.
These have no -dos/-mac subsidiary variants, so `coding-system-eol-type'
returns the integer 0 for them rather than a vector, and no subsidiary
NAME-dos/NAME-mac coding system exists.")
(defun coding-system-eol-type (coding-system)
"Return the EOL (end-of-line) conversion type of CODING-SYSTEM.
The value is an integer 0, 1, or 2 when CODING-SYSTEM has a fixed EOL
type (`unix', `dos', or `mac' respectively), or a vector
[BASE-unix BASE-dos BASE-mac] of the three subsidiary coding systems
when the EOL type is undecided. BASE is the base of CODING-SYSTEM.
CODING-SYSTEM nil is treated as `no-conversion'.
Return nil if CODING-SYSTEM is not a valid coding system."
(when (null coding-system)
(setq coding-system 'no-conversion))
(and (symbolp coding-system)
(let ((name (symbol-name coding-system)))
(cond
;; A directly registered base or alias (no EOL suffix to strip).
((memq coding-system coding-system--all)
(if (memq coding-system coding-system--eol-fixed)
0
(let ((base (symbol-name (coding-system-base coding-system))))
(vector (intern (concat base "-unix"))
(intern (concat base "-dos"))
(intern (concat base "-mac"))))))
;; A subsidiary NAME-unix/-dos/-mac of an EOL-undecided system.
(t
(let ((stem (coding-system--strip-eol name)))
(and (not (string= stem name))
(let ((base (intern stem)))
(and (memq base coding-system--all)
(not (memq base coding-system--eol-fixed))
(cond ((string-suffix-p "-unix" name) 0)
((string-suffix-p "-dos" name) 1)
(t 2)))))))))))
(defun coding-system-change-eol-conversion (coding-system eol-type)
"Return a coding system which differs from CODING-SYSTEM in EOL conversion.
The returned coding system converts end-of-line by EOL-TYPE
but text as the same way as CODING-SYSTEM.
EOL-TYPE should be `unix', `dos', `mac', or nil.
If EOL-TYPE is nil, the returned coding system detects
how end-of-line is formatted automatically while decoding.
EOL-TYPE can be specified by an integer 0, 1, or 2.
They means `unix', `dos', and `mac' respectively."
(if (symbolp eol-type)
(setq eol-type (cond ((eq eol-type 'unix) 0)
((eq eol-type 'dos) 1)
((eq eol-type 'mac) 2)
(t eol-type))))
;; We call `coding-system-base' before `coding-system-eol-type',
;; because the coding-system may not be initialized until then.
(let* ((base (coding-system-base coding-system))
(orig-eol-type (coding-system-eol-type coding-system)))
(cond ((vectorp orig-eol-type)
(if (not eol-type)
coding-system
(aref orig-eol-type eol-type)))
((not eol-type)
base)
((= eol-type orig-eol-type)
coding-system)
((progn (setq orig-eol-type (coding-system-eol-type base))
(vectorp orig-eol-type))
(aref orig-eol-type eol-type)))))
;;; ---- language environments (mule-cmds.el data surface) ----
;; Faithful port of GNU Emacs 30.2's `language-info-alist' machinery: the
;; registry that `set-language-info-alist' populates when a language/*.el file
;; declares a language environment. `bindings--define-key' (bindings.el) and
;; `define-key-after' (subr.el) are the two supporting keymap helpers these
;; functions need for their menu-map bookkeeping; both are copied verbatim.
;; The heavy `set-language-environment*' switch functions are NOT ported here —
;; they only fire when a definition targets the CURRENT environment; declaring a
;; new environment (the load-time case) never touches them. Bodies are verbatim
;; from mule-cmds.el / subr.el / bindings.el.
(defun bindings--define-key (map key item)
"Define KEY in keymap MAP according to ITEM from a menu.
This is like `define-key', but it takes the definition from the
specified menu item, and makes pure copies of as much as possible
of the menu's data."
(declare (indent 2))
(define-key map key
(cond
((not (consp item)) item)
((keymapp item) item)
((stringp (car item))
(if (keymapp (cdr item))
(cons (purecopy (car item)) (cdr item))
(purecopy item)))
((eq 'menu-item (car item))
(if (keymapp (nth 2 item))
`(menu-item ,(purecopy (nth 1 item)) ,(nth 2 item)
,@(purecopy (nthcdr 3 item)))
(purecopy item)))
(t (message "non-menu-item: %S" item) item))))
(defun define-key-after (keymap key definition &optional after)
"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
of the map. Note that AFTER must be an event type (like KEY), NOT a command
\(like DEFINITION).
If AFTER is t or omitted, the new binding goes at the end of the keymap.
AFTER should be a single event type--a symbol or a character, not a sequence.
Bindings are always added before any inherited map.
The order of bindings in a keymap matters only when it is used as
a menu, so this function is not useful for non-menu keymaps."
(declare (indent defun))
(unless after (setq after t))
(or (keymapp keymap)
(signal 'wrong-type-argument (list 'keymapp keymap)))
(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)
(while (and (not done) tail)
;; Delete any earlier bindings for the same key.
(if (eq (car-safe (car (cdr tail))) key)
(setcdr tail (cdr (cdr tail))))
;; If we hit an included map, go down that one.
(if (keymapp (car tail)) (setq tail (car tail)))
;; When we reach AFTER's binding, insert the new binding after.
;; If we reach an inherited keymap, insert just before that.
;; If we reach the end of this keymap, insert at the end.
(if (or (and (eq (car-safe (car tail)) after)
(not (eq after t)))
(eq (car (cdr tail)) 'keymap)
(null (cdr tail)))
(progn
;; 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
(setcdr tail (cons (cons key definition) (cdr tail))))
(setq inserted t)))
(setq tail (cdr tail)))))
(defvar language-info-alist nil
"Alist of language environment definitions.
Each element looks like:
(LANGUAGE-NAME . ((KEY . INFO) ...))
where LANGUAGE-NAME is a string, the name of the language environment,
KEY is a symbol denoting the kind of information, and
INFO is the data associated with KEY.")
(defvar current-language-environment "English"
"The last language environment specified with `set-language-environment'.")
(defvar describe-language-environment-map
(let ((map (make-sparse-keymap "Describe Language Environment")))
(bindings--define-key map
[Default] '(menu-item "Default" describe-specified-language-support))
map))
(defvar setup-language-environment-map
(let ((map (make-sparse-keymap "Set Language Environment")))
(bindings--define-key map
[Default] '(menu-item "Default" setup-specified-language-environment))
map))
(defun get-language-info (lang-env key)
"Return information listed under KEY for language environment LANG-ENV.
KEY is a symbol denoting the kind of information.
For a list of useful values for KEY and their meanings,
see `language-info-alist'."
(if (symbolp lang-env)
(setq lang-env (symbol-name lang-env)))
(let ((lang-slot (assoc-string lang-env language-info-alist t)))
(if lang-slot
(cdr (assq key (cdr lang-slot))))))
(defun set-language-info (lang-env key info)
"Modify part of the definition of language environment LANG-ENV.
Specifically, this stores the information INFO under KEY
in the definition of this language environment.
KEY is a symbol denoting the kind of information.
INFO is the value for that information.
For a list of useful values for KEY and their meanings,
see `language-info-alist'."
(if (symbolp lang-env)
(setq lang-env (symbol-name lang-env)))
(set-language-info-internal lang-env key info)
(if (equal lang-env current-language-environment)
(cond ((eq key 'coding-priority)
(set-language-environment-coding-systems lang-env)
(set-language-environment-charset lang-env))
((eq key 'input-method)
(set-language-environment-input-method lang-env))
((eq key 'nonascii-translation)
(set-language-environment-nonascii-translation lang-env))
((eq key 'charset)
(set-language-environment-charset lang-env)))))
(defun set-language-info-internal (lang-env key info)
"Internal use only.
Arguments are the same as `set-language-info'."
(let (lang-slot key-slot)
(setq lang-slot (assoc lang-env language-info-alist))
(if (null lang-slot) ; If no slot for the language, add it.
(setq lang-slot (list lang-env)
language-info-alist (cons lang-slot language-info-alist)))
(setq key-slot (assq key lang-slot))
(if (null key-slot) ; If no slot for the key, add it.
(progn
(setq key-slot (list key))
(setcdr lang-slot (cons key-slot (cdr lang-slot)))))
(setcdr key-slot (purecopy info))
;; Update the custom-type of `current-language-environment'.
(put 'current-language-environment 'custom-type
(cons 'choice (mapcar
(lambda (lang)
(list 'const lang))
(sort (mapcar 'car language-info-alist) 'string<))))))
(defun set-language-info-setup-keymap (lang-env alist describe-map setup-map)
"Setup menu items for LANG-ENV.
See `set-language-info-alist' for details of other arguments."
(let ((doc (assq 'documentation alist)))
(when doc
(define-key-after describe-map (vector (intern lang-env))
(cons lang-env 'describe-specified-language-support))))
(define-key-after setup-map (vector (intern lang-env))
(cons lang-env 'setup-specified-language-environment)))
(defun set-language-info-alist (lang-env alist &optional parents)
"Store ALIST as the definition of language environment LANG-ENV.
ALIST is an alist of KEY and INFO values. See the documentation of
`language-info-alist' for the meanings of KEY and INFO.
Optional arg PARENTS is a list of parent menu names; it specifies
where to put this language environment in the
Describe Language Environment and Set Language Environment menus.
For example, (\"European\") means to put this language environment
in the European submenu in each of those two menus."
(cond ((symbolp lang-env)
(setq lang-env (symbol-name lang-env)))
((stringp lang-env)
(setq lang-env (purecopy lang-env))))
(if parents
(while parents
(let (describe-map setup-map parent-symbol parent prompt)
(if (symbolp (setq parent-symbol (car parents)))
(setq parent (symbol-name parent))
(setq parent parent-symbol parent-symbol (intern parent)))
(setq describe-map (lookup-key describe-language-environment-map
(vector parent-symbol)))
;; This prompt string is for define-prefix-command, so
;; that the map it creates will be suitable for a menu.
(or describe-map (setq prompt (format "%s Environment" parent)))
(unless describe-map
(setq describe-map (intern (format "describe-%s-environment-map"
(downcase parent))))
(define-prefix-command describe-map nil prompt)
(define-key-after
describe-language-environment-map
(vector parent-symbol) (cons parent describe-map)))
(setq setup-map (lookup-key setup-language-environment-map
(vector parent-symbol)))
(unless setup-map
(setq setup-map (intern (format "setup-%s-environment-map"
(downcase parent))))
(define-prefix-command setup-map nil prompt)
(define-key-after
setup-language-environment-map
(vector parent-symbol) (cons parent setup-map)))
(setq parents (cdr parents))
(set-language-info-setup-keymap
lang-env alist
(symbol-value describe-map) (symbol-value setup-map))))
(set-language-info-setup-keymap
lang-env alist
describe-language-environment-map setup-language-environment-map))
(dolist (elt alist)
(set-language-info-internal lang-env (car elt) (cdr elt)))
(if (equal lang-env current-language-environment)
(set-language-environment lang-env)))
;;; ring.el --- handle rings of items -*- lexical-binding: t -*-
;; Faithful port of emacs-lisp/ring.el (Emacs 30.2). A ring is a fixed-size
;; circular buffer represented as the cons (HD LN . VEC): HD is the index of
;; the oldest element in VEC, LN the current element count, VEC the storage.
(defun ring-p (x)
"Return t if X is a ring; nil otherwise."
(and (consp x) (integerp (car x))
(consp (cdr x)) (integerp (cadr x))
(vectorp (cddr x))))
(defun make-ring (size)
"Make a ring that can contain SIZE elements."
(cons 0 (cons 0 (make-vector size nil))))
(defun ring-insert-at-beginning (ring item)
"Add to RING the item ITEM, at the front, as the oldest item."
(let* ((vec (cddr ring))
(veclen (length vec))
(hd (car ring))
(ln (cadr ring)))
(setq ln (min veclen (1+ ln))
hd (ring-minus1 hd veclen))
(aset vec hd item)
(setcar ring hd)
(setcar (cdr ring) ln)))
(defun ring-plus1 (index veclen)
"Return INDEX+1, with wraparound."
(let ((new-index (1+ index)))
(if (= new-index veclen) 0 new-index)))
(defun ring-minus1 (index veclen)
"Return INDEX-1, with wraparound."
(- (if (zerop index) veclen index) 1))
(defun ring-length (ring)
"Return the number of elements in the RING."
(cadr ring))
(defun ring-index (index head ringlen veclen)
"Convert nominal ring index INDEX to an internal index.
The internal index refers to the items ordered from newest to oldest.
HEAD is the index of the oldest element in the ring.
RINGLEN is the number of elements currently in the ring.
VECLEN is the size of the vector in the ring."
(setq index (mod index ringlen))
(mod (1- (+ head (- ringlen index))) veclen))
(defun ring-empty-p (ring)
"Return t if RING is empty; nil otherwise."
(zerop (cadr ring)))
(defun ring-size (ring)
"Return the size of RING, the maximum number of elements it can contain."
(length (cddr ring)))
(defun ring-copy (ring)
"Return a copy of RING."
(let ((vec (cddr ring))
(hd (car ring))
(ln (cadr ring)))
(cons hd (cons ln (copy-sequence vec)))))
(defun ring-insert (ring item)
"Insert onto ring RING the item ITEM, as the newest (last) item.
If the ring is full, dump the oldest item to make room."
(let* ((vec (cddr ring))
(veclen (length vec))
(hd (car ring))
(ln (cadr ring)))
(prog1
(aset vec (mod (+ hd ln) veclen) item)
(if (= ln veclen)
(setcar ring (ring-plus1 hd veclen))
(setcar (cdr ring) (1+ ln))))))
(defun ring-remove (ring &optional index)
"Remove an item from the RING. Return the removed item.
If optional INDEX is nil, remove the oldest item. If it's
numeric, remove the element indexed."
(if (ring-empty-p ring)
(error "Ring empty")
(let* ((hd (car ring))
(ln (cadr ring))
(vec (cddr ring))
(veclen (length vec))
(tl (mod (1- (+ hd ln)) veclen))
oldelt)
(when (null index)
(setq index (1- ln)))
(setq index (ring-index index hd ln veclen))
(setq oldelt (aref vec index))
(while (/= index tl)
(aset vec index (aref vec (ring-plus1 index veclen)))
(setq index (ring-plus1 index veclen)))
(aset vec tl nil)
(setcar (cdr ring) (1- ln))
oldelt)))
(defun ring-ref (ring index)
"Return RING's INDEX element.
INDEX = 0 is the most recently inserted; higher indices
correspond to older elements.
INDEX need not be <= the ring length; the appropriate modulo operation
will be performed."
(if (ring-empty-p ring)
(error "Accessing an empty ring")
(let ((hd (car ring))
(ln (cadr ring))
(vec (cddr ring)))
(aref vec (ring-index index hd ln (length vec))))))
(defun ring-elements (ring)
"Return a list of the elements of RING, in order, newest first."
(let ((start (car ring))
(size (ring-size ring))
(vect (cddr ring))
lst)
(dotimes (var (cadr ring))
(push (aref vect (mod (+ start var) size)) lst))
lst))
(defun ring-member (ring item)
"Return index of ITEM if on RING, else nil.
Comparison is done via `equal'. The index is 0-based."
(catch 'found
(dotimes (ind (ring-length ring))
(when (equal item (ring-ref ring ind))
(throw 'found ind)))))
(defun ring-next (ring item)
"Return the next item in the RING, after ITEM.
Raise error if ITEM is not in the RING."
(let ((curr-index (ring-member ring item)))
(unless curr-index (error "Item is not in the ring: `%s'" item))
(ring-ref ring (ring-plus1 curr-index (ring-length ring)))))
(defun ring-previous (ring item)
"Return the previous item in the RING, before ITEM.
Raise error if ITEM is not in the RING."
(let ((curr-index (ring-member ring item)))
(unless curr-index (error "Item is not in the ring: `%s'" item))
(ring-ref ring (ring-minus1 curr-index (ring-length ring)))))
(defun ring-extend (ring x)
"Increase the size of RING by X."
(when (and (integerp x) (> x 0))
(ring-resize ring (+ x (ring-size ring)))))
(defun ring-resize (ring size)
"Set the size of RING to SIZE.
If the new size is smaller, then the oldest items in the ring are
discarded."
(when (integerp size)
(let ((length (ring-length ring))
(new-vec (make-vector size nil)))
(if (= length 0)
(setcdr ring (cons 0 new-vec))
(let* ((hd (car ring))
(old-size (ring-size ring))
(old-vec (cddr ring))
(copy-length (min size length))
(copy-hd (mod (+ hd (- length copy-length)) length)))
(setcdr ring (cons copy-length new-vec))
(dotimes (j copy-length)
(aset new-vec j (aref old-vec (mod (+ copy-hd j) old-size))))
(setcar ring 0))))))
(defun ring-insert+extend (ring item &optional grow-p)
"Like `ring-insert', but if GROW-P is non-nil, then enlarge ring.
Insert onto ring RING the item ITEM, as the newest (last) item.
If the ring is full, behavior depends on GROW-P:
If GROW-P is non-nil, enlarge the ring to accommodate the new item.
If GROW-P is nil, dump the oldest item to make room for the new."
(and grow-p
(= (ring-length ring) (ring-size ring))
(ring-extend ring 1))
(ring-insert ring item))
(defun ring-remove+insert+extend (ring item &optional grow-p)
"`ring-remove' ITEM from RING, then `ring-insert+extend' it.
This ensures that there is only one ITEM on RING.
If the RING is full, behavior depends on GROW-P:
If GROW-P is non-nil, enlarge the ring to accommodate the new ITEM.
If GROW-P is nil, dump the oldest item to make room for the new."
(let (ind)
(while (setq ind (ring-member ring item))
(ring-remove ring ind)))
(ring-insert+extend ring item grow-p))
(defun ring-convert-sequence-to-ring (seq)
"Convert sequence SEQ to a ring. Return the ring.
If SEQ is already a ring, return it."
(if (ring-p seq)
seq
(let* ((size (length seq))
(ring (make-ring size)))
(dotimes (count size)
(when (or (ring-empty-p ring)
(not (equal (ring-ref ring 0) (elt seq count))))
(ring-insert-at-beginning ring (elt seq count))))
ring)))
;;; text-property-search.el --- search for text properties -*- lexical-binding: t -*-
;; Faithful port of emacs-lisp/text-property-search.el (Emacs 30.2).
(cl-defstruct (prop-match)
beginning end value)
(defun text-property-search-forward (property &optional value predicate
not-current)
"Search for next region of text where PREDICATE returns non-nil for PROPERTY.
PREDICATE is used to decide whether the value of PROPERTY at a given
buffer position should be considered as a match for VALUE.
VALUE defaults to nil if omitted.
If PREDICATE is a function, it will be called with two arguments:
VALUE and the value of PROPERTY at some buffer position. The function
should return non-nil if these two values are to be considered a match.
Two special values of PREDICATE can also be used:
If PREDICATE is t, that means the value of PROPERTY must `equal' VALUE
to be considered a match.
If PREDICATE is nil (which is the default), the value of PROPERTY will
match if it is not `equal' to VALUE. Furthermore, a nil PREDICATE
means that the match region ends where the value changes. For
instance, this means that if you loop with
(while (setq prop (text-property-search-forward \\='face))
...)
you will get all the distinct regions with non-nil `face' values in
the buffer, and the `prop' object will have the details about the
match. See the manual for more details and examples about how
VALUE and PREDICATE interact.
If NOT-CURRENT is non-nil, current buffer position is not examined for
matches: the function will search for the first region that doesn't
include point and has a value of PROPERTY that matches VALUE.
If no matches can be found, return nil and don't move point.
If found, move point to the end of the region and return a
`prop-match' object describing the match. To access the details
of the match, use `prop-match-beginning' and `prop-match-end' for
the buffer positions that limit the region, and `prop-match-value'
for the value of PROPERTY in the region."
(interactive
(list
(let ((string (completing-read "Search for property: " obarray)))
(when (> (length string) 0)
(intern string obarray)))))
(cond
((eobp)
nil)
((and (text-property--match-p value (get-text-property (point) property)
predicate)
(not not-current))
(text-property--find-end-forward (point) property value predicate))
(t
(let ((origin (point))
(ended nil)
pos)
(while (not ended)
(setq pos (next-single-property-change (point) property))
(if (not pos)
(progn
(goto-char origin)
(setq ended t))
(goto-char pos)
(if (text-property--match-p value (get-text-property (point) property)
predicate)
(setq ended
(text-property--find-end-forward
(point) property value predicate))
(setq pos (next-single-property-change (point) property))
(unless pos
(goto-char origin)
(setq ended t)))))
(and (not (eq ended t))
ended)))))
(defun text-property--find-end-forward (start property value predicate)
(let (end)
(if (and value
(null predicate))
(let ((ended nil))
(while (not ended)
(setq end (next-single-property-change (point) property))
(if (not end)
(progn
(goto-char (point-max))
(setq end (point)
ended t))
(goto-char end)
(unless (text-property--match-p
value (get-text-property (point) property) predicate)
(setq ended t)))))
(setq end (next-single-property-change (point) property nil (point-max)))
(goto-char end))
(make-prop-match :beginning start
:end end
:value (get-text-property start property))))
(defun text-property-search-backward (property &optional value predicate
not-current)
"Search for previous region of text where PREDICATE returns non-nil for PROPERTY.
Like `text-property-search-forward', which see, but searches backward,
and if a matching region is found, place point at the start of the region."
(interactive
(list
(let ((string (completing-read "Search for property: " obarray)))
(when (> (length string) 0)
(intern string obarray)))))
(cond
((bobp)
nil)
((text-property--match-p
value (get-text-property (1- (point)) property)
predicate)
(let ((origin (point))
(match (text-property--find-end-backward
(1- (point)) property value predicate)))
(if (and not-current
(equal (get-text-property (point) property)
(get-text-property origin property)))
(text-property-search-backward property value predicate)
match)))
(t
(let ((origin (point))
(ended nil)
pos)
(while (not ended)
(setq pos (previous-single-property-change (point) property))
(if (not pos)
(progn
(goto-char origin)
(setq ended t))
(goto-char (1- pos))
(if (text-property--match-p value (get-text-property (point) property)
predicate)
(setq ended
(text-property--find-end-backward
(point) property value predicate))
(setq pos (previous-single-property-change (point) property))
(unless pos
(goto-char origin)
(setq ended t)))))
(and (not (eq ended t))
ended)))))
(defun text-property--find-end-backward (start property value predicate)
(let (end)
(if (and value
(null predicate))
(let ((ended nil))
(while (not ended)
(setq end (previous-single-property-change (point) property))
(if (not end)
(progn
(goto-char (point-min))
(setq end (point)
ended t))
(goto-char (1- end))
(unless (text-property--match-p
value (get-text-property (point) property) predicate)
(goto-char end)
(setq ended t)))))
(setq end
(if (and (> (point) (point-min))
(text-property--match-p
value (get-text-property (1- (point)) property)
predicate))
(previous-single-property-change (point)
property nil (point-min))
(point)))
(goto-char end))
(make-prop-match :beginning end
:end (1+ start)
:value (get-text-property end property))))
(defun text-property--match-p (value prop-value predicate)
(cond
((eq predicate t)
(setq predicate #'equal))
((eq predicate nil)
(setq predicate (lambda (val p-val)
(not (equal val p-val))))))
(funcall predicate value prop-value))
;; ---- cl-case / cl-typecase / cl-parse-integer / cl-list-length ----
;; cl-macs.el and cl-extra.el (emacs-31.1), verbatim.
(defmacro cl-case (expr &rest clauses)
"Eval EXPR and choose among clauses on that value.
Each clause looks like (KEYLIST BODY...). EXPR is evaluated and
compared against each key in each KEYLIST; the corresponding BODY
is evaluated. If no clause succeeds, this macro returns nil. A
single non-nil atom may be used in place of a KEYLIST of one
atom. A KEYLIST of t or `otherwise' is allowed only in the final
clause, and matches if no other keys match. Key values are
compared by `eql'.
\(fn EXPR (KEYLIST BODY...)...)"
(declare (indent 1) (debug (form &rest (sexp body))))
(macroexp-let2 macroexp-copyable-p temp expr
(let* ((head-list nil)
(has-otherwise nil))
`(cond
,@(mapcar
(lambda (c)
(cons (cond (has-otherwise
(error "Misplaced t or `otherwise' clause"))
((memq (car c) '(t otherwise))
(setq has-otherwise t)
t)
((eq (car c) 'cl--ecase-error-flag)
`(error "cl-ecase failed: %s, %s"
,temp ',(reverse head-list)))
((null (car c))
(macroexp-warn-and-return
"Case nil will never match"
nil 'suspicious))
((and (consp (car c)) (cdar c) (not (cddar c))
(memq (caar c) '(quote function)))
(macroexp-warn-and-return
(format-message
(concat "Case %s will match `%s'. If "
"that's intended, write %s "
"instead. Otherwise, don't "
"quote `%s'.")
(car c) (caar c) (list (cadar c) (caar c))
(cadar c))
`(cl-member ,temp ',(car c)) 'suspicious))
((listp (car c))
(setq head-list (append (car c) head-list))
`(cl-member ,temp ',(car c)))
(t
(if (memq (car c) head-list)
(error "Duplicate key in case: %s"
(car c)))
(push (car c) head-list)
`(eql ,temp ',(car c))))
(or (cdr c) '(nil))))
clauses)))))
(defmacro cl-ecase (expr &rest clauses)
"Like `cl-case', but error if no case fits.
`otherwise'-clauses are not allowed.
\n(fn EXPR (KEYLIST BODY...)...)"
(declare (indent 1) (debug cl-case))
`(cl-case ,expr ,@clauses (cl--ecase-error-flag)))
(defmacro cl-typecase (expr &rest clauses)
"Eval EXPR and choose among clauses on that value.
Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
this macro returns nil. A TYPE of t or `otherwise' is allowed only in the
final clause, and matches if no other keys match.
\n(fn EXPR (TYPE BODY...)...)"
(declare (indent 1)
(debug (form &rest ([&or cl-type-spec "otherwise"] body))))
(macroexp-let2 macroexp-copyable-p temp expr
(let* ((type-list nil))
(cons
'cond
(mapcar
(lambda (c)
(cons (cond ((eq (car c) 'otherwise) t)
((eq (car c) 'cl--ecase-error-flag)
`(error "cl-etypecase failed: %s, %s"
,temp ',(reverse type-list)))
(t
(push (car c) type-list)
`(cl-typep ,temp ',(car c))))
(or (cdr c) '(nil))))
clauses)))))
(defmacro cl-etypecase (expr &rest clauses)
"Like `cl-typecase', but error if no case fits.
`otherwise'-clauses are not allowed.
\n(fn EXPR (TYPE BODY...)...)"
(declare (indent 1) (debug cl-typecase))
`(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))
(defun cl-list-length (x)
"Return the length of list X. Return nil if list is circular."
(declare (side-effect-free t))
(cl-check-type x list)
(condition-case nil
(length x)
(circular-list)))
(cl-defun cl-parse-integer (string &key start end radix junk-allowed)
"Parse integer from the substring of STRING from START to END.
STRING may be surrounded by whitespace chars (chars with syntax ` ').
Other non-digit chars are considered junk.
RADIX is an integer between 2 and 36, the default is 10. Signal
an error if the substring between START and END cannot be parsed
as an integer unless JUNK-ALLOWED is non-nil."
(declare (side-effect-free t))
(cl-check-type string string)
(let* ((start (or start 0))
(len (length string))
(end (or end len))
(radix (or radix 10)))
(or (<= start end len)
(error "Bad interval: [%d, %d)" start end))
(cl-flet ((skip-whitespace ()
(while (and (< start end)
(= 32 (char-syntax (aref string start))))
(setq start (1+ start)))))
(skip-whitespace)
(let ((sign (cl-case (and (< start end) (aref string start))
(?+ (incf start) +1)
(?- (incf start) -1)
(t +1)))
digit sum)
(while (and (< start end)
(setq digit (cl-digit-char-p (aref string start) radix)))
(setq sum (+ (* (or sum 0) radix) digit)
start (1+ start)))
(skip-whitespace)
(cond ((and junk-allowed (null sum)) sum)
(junk-allowed (* sign sum))
((or (/= start end) (null sum))
(error "Not an integer string: `%s'" string))
(t (* sign sum)))))))
;; ---- cl-seq ----
;; cl-seq.el (emacs-31.1), verbatim, with the two compiler macros its
;; `declare' forms name (cl-macs.el).
;; Keyword parsing.
;; This is special-cased here so that we can compile
;; this file independent from cl-macs.
(defmacro cl--parsing-keywords (keywords other-keys &rest body)
(declare (indent 2) (debug (sexp sexp &rest form)))
`(let* ,(mapcar
(lambda (x)
(let* ((var (if (consp x) (car x) x))
(mem `(car (cdr (memq ',var cl-keys)))))
(if (eq var :test-not)
(setq mem `(and ,mem (setq cl-test ,mem) t)))
(if (eq var :if-not)
(setq mem `(and ,mem (setq cl-if ,mem) t)))
(list (intern
(format "cl-%s" (substring (symbol-name var) 1)))
(if (consp x) `(or ,mem ,(cadr x)) mem))))
keywords)
,@(append
(and (not (eq other-keys t))
`((let ((cl-keys-temp cl-keys))
(while cl-keys-temp
(or (memq (car cl-keys-temp)
(quote ,(mapcar
(lambda (x)
(if (consp x)
(car x) x))
(append keywords other-keys))))
(cadr (memq :allow-other-keys cl-keys))
(error "Bad keyword argument %s"
(car cl-keys-temp)))
(setq cl-keys-temp (cddr cl-keys-temp))))))
body)))
(defmacro cl--check-key (x) ;Expects `cl-key' in context of generated code.
(declare (debug edebug-forms))
`(if cl-key (funcall cl-key ,x) ,x))
(defmacro cl--check-test-nokey (item x) ;cl-test cl-if cl-test-not cl-if-not.
(declare (debug edebug-forms))
`(cond
(cl-test (eq (not (funcall cl-test ,item ,x))
cl-test-not))
(cl-if (eq (not (funcall cl-if ,x)) cl-if-not))
(t (eql ,item ,x))))
(defmacro cl--check-test (item x) ;all of the above.
(declare (debug edebug-forms))
`(cl--check-test-nokey ,item (cl--check-key ,x)))
(defmacro cl--check-match (x y) ;cl-key cl-test cl-test-not
(declare (debug edebug-forms))
(setq x `(cl--check-key ,x) y `(cl--check-key ,y))
`(if cl-test
(eq (not (funcall cl-test ,x ,y)) cl-test-not)
(eql ,x ,y)))
;; Yuck! These vars are set/bound by cl--parsing-keywords to match :if :test
;; and :key keyword args, and they are also accessed (sometimes) via dynamic
;; scoping (and some of those accesses are from macro-expanded code).
(defvar cl-test) (defvar cl-test-not)
(defvar cl-if) (defvar cl-if-not)
(defvar cl-key)
;;;###autoload
(defun cl-endp (x)
"Return true if X is the empty list; false if it is a cons.
Signal an error if X is not a list."
(declare (side-effect-free t))
(cl-check-type x list)
(null x))
;;;###autoload
(defun cl-reduce (func seq &rest cl-keys)
"Reduce two-argument FUNCTION across SEQ.
\nKeywords supported: :start :end :from-end :initial-value :key
Return the result of calling FUNCTION with the first and the
second element of SEQ, then calling FUNCTION with that result and
the third element of SEQ, then with that result and the fourth
element of SEQ, etc.
If :INITIAL-VALUE is specified, it is logically added to the
front of SEQ (or the back if :FROM-END is non-nil). If SEQ is
empty, return :INITIAL-VALUE and FUNCTION is not called.
If SEQ is empty and no :INITIAL-VALUE is specified, then return
the result of calling FUNCTION with zero arguments. This is the
only case where FUNCTION is called with fewer than two arguments.
If SEQ contains exactly one element and no :INITIAL-VALUE is
specified, then just return that element without calling FUNCTION.
If :FROM-END is non-nil, the reduction occurs from the back of
the SEQ moving forward, and the order of arguments to the
FUNCTION is also reversed.
\n(fn FUNCTION SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords (:from-end (:start 0) :end :initial-value :key) ()
(or (listp seq) (setq seq (append seq nil)))
(setq seq (cl-subseq seq cl-start cl-end))
(if cl-from-end (setq seq (nreverse seq)))
(let ((accum (cond ((memq :initial-value cl-keys) cl-initial-value)
(seq (cl--check-key (pop seq)))
(t (funcall func)))))
(if cl-from-end
(while seq
(setq accum (funcall func (cl--check-key (pop seq))
accum)))
(while seq
(setq accum (funcall func accum
(cl--check-key (pop seq))))))
accum)))
;;;###autoload
(defun cl-fill (seq item &rest cl-keys)
"Fill the elements of SEQ with ITEM.
\nKeywords supported: :start :end
\n(fn SEQ ITEM [KEYWORD VALUE]...)"
(cl--parsing-keywords ((:start 0) :end) ()
(if (listp seq)
(let ((p (nthcdr cl-start seq))
(n (and cl-end (- cl-end cl-start))))
(while (and p (or (null n) (>= (decf n) 0)))
(setcar p item)
(setq p (cdr p))))
(or cl-end (setq cl-end (length seq)))
(if (and (= cl-start 0) (= cl-end (length seq)))
(fillarray seq item)
(while (< cl-start cl-end)
(aset seq cl-start item)
(setq cl-start (1+ cl-start)))))
seq))
;;;###autoload
(defun cl-replace (seq1 seq2 &rest cl-keys)
"Replace the elements of SEQ1 with the elements of SEQ2.
SEQ1 is destructively modified, then returned.
\nKeywords supported: :start1 :end1 :start2 :end2
\n(fn SEQ1 SEQ2 [KEYWORD VALUE]...)"
(cl--parsing-keywords ((:start1 0) :end1 (:start2 0) :end2) ()
(if (and (eq seq1 seq2) (<= cl-start2 cl-start1))
(or (= cl-start1 cl-start2)
(let* ((len (length seq1))
(n (min (- (or cl-end1 len) cl-start1)
(- (or cl-end2 len) cl-start2))))
(while (>= (setq n (1- n)) 0)
(setf (elt seq1 (+ cl-start1 n))
(elt seq2 (+ cl-start2 n))))))
(if (listp seq1)
(let ((p1 (nthcdr cl-start1 seq1))
(n1 (and cl-end1 (- cl-end1 cl-start1))))
(if (listp seq2)
(let ((p2 (nthcdr cl-start2 seq2))
(n (cond ((and n1 cl-end2)
(min n1 (- cl-end2 cl-start2)))
((and n1 (null cl-end2)) n1)
((and (null n1) cl-end2) (- cl-end2 cl-start2)))))
(while (and p1 p2 (or (null n) (>= (decf n) 0)))
(setcar p1 (car p2))
(setq p1 (cdr p1) p2 (cdr p2))))
(setq cl-end2 (if (null n1)
(or cl-end2 (length seq2))
(min (or cl-end2 (length seq2))
(+ cl-start2 n1))))
(while (and p1 (< cl-start2 cl-end2))
(setcar p1 (aref seq2 cl-start2))
(setq p1 (cdr p1) cl-start2 (1+ cl-start2)))))
(setq cl-end1 (min (or cl-end1 (length seq1))
(+ cl-start1 (- (or cl-end2 (length seq2))
cl-start2))))
(if (listp seq2)
(let ((p2 (nthcdr cl-start2 seq2)))
(while (< cl-start1 cl-end1)
(aset seq1 cl-start1 (car p2))
(setq p2 (cdr p2) cl-start1 (1+ cl-start1))))
(while (< cl-start1 cl-end1)
(aset seq1 cl-start1 (aref seq2 cl-start2))
(setq cl-start2 (1+ cl-start2) cl-start1 (1+ cl-start1))))))
seq1))
;;;###autoload
(defun cl-remove (item seq &rest cl-keys)
"Remove all occurrences of ITEM in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported: :test :test-not :key :count :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :if :if-not :count :from-end
(:start 0) :end) ()
(let ((len (length seq)))
(if (<= (or cl-count (setq cl-count len)) 0)
seq
(if (or (nlistp seq) (and cl-from-end (< cl-count (/ len 2))))
(let ((i (cl--position item seq cl-start cl-end
cl-from-end)))
(if i
(let ((res (apply #'cl-delete item (append seq nil)
(append (if cl-from-end
(list :end (1+ i))
(list :start i))
cl-keys))))
(if (listp seq) res
(if (stringp seq) (concat res) (vconcat res))))
seq))
(setq cl-end (- (or cl-end len) cl-start))
(if (= cl-start 0)
(while (and seq (> cl-end 0)
(cl--check-test item (car seq))
(setq cl-end (1- cl-end) seq (cdr seq))
(> (setq cl-count (1- cl-count)) 0))))
(if (and (> cl-count 0) (> cl-end 0))
(let ((p (if (> cl-start 0) (nthcdr cl-start seq)
(setq cl-end (1- cl-end)) (cdr seq))))
(while (and p (> cl-end 0)
(not (cl--check-test item (car p))))
(setq p (cdr p) cl-end (1- cl-end)))
(if (and p (> cl-end 0))
(nconc (cl-ldiff seq p)
(if (= cl-count 1) (cdr p)
(and (cdr p)
(apply #'cl-delete item
(copy-sequence (cdr p))
:start 0 :end (1- cl-end)
:count (1- cl-count) cl-keys))))
seq))
seq))))))
;;;###autoload
(defun cl-remove-if (pred list &rest cl-keys)
"Remove all items satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported: :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-remove pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-remove-if-not (pred list &rest cl-keys)
"Remove all items not satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported: :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-remove pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-delete (item seq &rest cl-keys)
"Remove all occurrences of ITEM in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported: :test :test-not :key :count :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :if :if-not :count :from-end
(:start 0) :end) ()
(let ((len (length seq)))
(if (<= (or cl-count (setq cl-count len)) 0)
seq
(if (listp seq)
(if (and cl-from-end (< cl-count (/ len 2)))
(let (i)
(while (and (>= (setq cl-count (1- cl-count)) 0)
(setq i (cl--position item seq cl-start
cl-end cl-from-end)))
(if (= i 0) (setq seq (cdr seq))
(let ((tail (nthcdr (1- i) seq)))
(setcdr tail (cdr (cdr tail)))))
(setq cl-end i))
seq)
(setq cl-end (- (or cl-end len) cl-start))
(if (= cl-start 0)
(progn
(while (and seq
(> cl-end 0)
(cl--check-test item (car seq))
(setq cl-end (1- cl-end) seq (cdr seq))
(> (setq cl-count (1- cl-count)) 0)))
(setq cl-end (1- cl-end)))
(setq cl-start (1- cl-start)))
(if (and (> cl-count 0) (> cl-end 0))
(let ((p (nthcdr cl-start seq)))
(while (and (cdr p) (> cl-end 0))
(if (cl--check-test item (car (cdr p)))
(progn
(setcdr p (cdr (cdr p)))
(if (= (setq cl-count (1- cl-count)) 0)
(setq cl-end 1)))
(setq p (cdr p)))
(setq cl-end (1- cl-end)))))
seq)
(apply #'cl-remove item seq cl-keys))))))
;;;###autoload
(defun cl-delete-if (pred list &rest cl-keys)
"Remove all items satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported: :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-delete pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-delete-if-not (pred list &rest cl-keys)
"Remove all items not satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported: :key :count :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-delete pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-remove-duplicates (seq &rest cl-keys)
"Return a copy of SEQ with all duplicate elements removed.
\nKeywords supported: :test :test-not :key :start :end :from-end
\n(fn SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--delete-duplicates seq cl-keys t))
;;;###autoload
(defun cl-delete-duplicates (seq &rest cl-keys)
"Remove all duplicate elements from SEQ (destructively).
\nKeywords supported: :test :test-not :key :start :end :from-end
\n(fn SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--delete-duplicates seq cl-keys nil))
(defun cl--delete-duplicates (seq cl-keys copy)
(if (listp seq)
(cl--parsing-keywords
;; We need to parse :if, otherwise `cl-if' is unbound.
(:test :test-not :key (:start 0) :end :from-end :if)
()
(if cl-from-end
(let ((p (nthcdr cl-start seq)) i)
(setq cl-end (- (or cl-end (length seq)) cl-start))
(while (> cl-end 1)
(setq i 0)
(while (setq i (cl--position (cl--check-key (car p))
(cdr p) i (1- cl-end)))
(if copy (setq seq (copy-sequence seq)
p (nthcdr cl-start seq) copy nil))
(let ((tail (nthcdr i p)))
(setcdr tail (cdr (cdr tail))))
(setq cl-end (1- cl-end)))
(setq p (cdr p) cl-end (1- cl-end)
cl-start (1+ cl-start)))
seq)
(setq cl-end (- (or cl-end (length seq)) cl-start))
(while (and (cdr seq) (= cl-start 0) (> cl-end 1)
(cl--position (cl--check-key (car seq))
(cdr seq) 0 (1- cl-end)))
(setq seq (cdr seq) cl-end (1- cl-end)))
(let ((p (if (> cl-start 0) (nthcdr (1- cl-start) seq)
(setq cl-end (1- cl-end) cl-start 1) seq)))
(while (and (cdr (cdr p)) (> cl-end 1))
(if (cl--position (cl--check-key (car (cdr p)))
(cdr (cdr p)) 0 (1- cl-end))
(progn
(if copy (setq seq (copy-sequence seq)
p (nthcdr (1- cl-start) seq)
copy nil))
(setcdr p (cdr (cdr p))))
(setq p (cdr p)))
(setq cl-end (1- cl-end) cl-start (1+ cl-start)))
seq)))
(let ((res (cl--delete-duplicates (append seq nil) cl-keys nil)))
(if (stringp seq) (concat res) (vconcat res)))))
;;;###autoload
(defun cl-substitute (new old seq &rest cl-keys)
"Substitute NEW for OLD in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported: :test :test-not :key :count :start :end :from-end
\n(fn NEW OLD SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :if :if-not :count
(:start 0) :end :from-end) ()
(if (or (eq old new)
(<= (or cl-count (setq cl-from-end nil
cl-count (length seq))) 0))
seq
(let ((i (cl--position old seq cl-start cl-end)))
(if (not i)
seq
(setq seq (copy-sequence seq))
(unless cl-from-end
(setf (elt seq i) new)
(incf i)
(decf cl-count))
(apply #'cl-nsubstitute new old seq :count cl-count
:start i cl-keys))))))
;;;###autoload
(defun cl-substitute-if (new pred seq &rest cl-keys)
"Substitute NEW for all items satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported: :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-substitute new pred seq :test #'funcall cl-keys))
;;;###autoload
(defun cl-substitute-if-not (new pred seq &rest cl-keys)
"Substitute NEW for all items not satisfying PREDICATE in SEQ.
This is a non-destructive function; it makes a copy of SEQ if necessary
to avoid corrupting the original SEQ.
\nKeywords supported: :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-substitute new pred seq :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-nsubstitute (new old seq &rest cl-keys)
"Substitute NEW for OLD in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported: :test :test-not :key :count :start :end :from-end
\n(fn NEW OLD SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :if :if-not :count
(:start 0) :end :from-end) ()
(let* ((stringp (stringp seq))
(seq (if (stringp seq) (string-to-vector seq) seq))
(len (length seq)))
(or (eq old new) (<= (or cl-count (setq cl-count len)) 0)
(if (and (listp seq) (or (not cl-from-end) (> cl-count (/ len 2))))
(let ((p (nthcdr cl-start seq)))
(setq cl-end (- (or cl-end len) cl-start))
(while (and p (> cl-end 0) (> cl-count 0))
(if (cl--check-test old (car p))
(progn
(setcar p new)
(setq cl-count (1- cl-count))))
(setq p (cdr p) cl-end (1- cl-end))))
(or cl-end (setq cl-end len))
(if cl-from-end
(while (and (< cl-start cl-end) (> cl-count 0))
(setq cl-end (1- cl-end))
(if (cl--check-test old (elt seq cl-end))
(progn
(setf (elt seq cl-end) new)
(setq cl-count (1- cl-count)))))
(while (and (< cl-start cl-end) (> cl-count 0))
(if (cl--check-test old (aref seq cl-start))
(progn
(aset seq cl-start new)
(setq cl-count (1- cl-count))))
(setq cl-start (1+ cl-start))))))
(if stringp (concat seq) seq))))
;;;###autoload
(defun cl-nsubstitute-if (new pred list &rest cl-keys)
"Substitute NEW for all items satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported: :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-nsubstitute new pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-nsubstitute-if-not (new pred list &rest cl-keys)
"Substitute NEW for all items not satisfying PREDICATE in SEQ.
This is a destructive function; it reuses the storage of SEQ whenever possible.
\nKeywords supported: :key :count :start :end :from-end
\n(fn NEW PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-nsubstitute new pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-find (item seq &rest cl-keys)
"Find the first occurrence of ITEM in SEQ.
Return the matching ITEM, or nil if not found.
\nKeywords supported: :test :test-not :key :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(let ((pos (apply #'cl-position item seq cl-keys)))
(and pos (elt seq pos))))
;;;###autoload
(defun cl-find-if (pred list &rest cl-keys)
"Find the first item satisfying PREDICATE in SEQ.
Return the matching item, or nil if not found.
\nKeywords supported: :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-find pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-find-if-not (pred list &rest cl-keys)
"Find the first item not satisfying PREDICATE in SEQ.
Return the matching item, or nil if not found.
\nKeywords supported: :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-find pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-position (item seq &rest cl-keys)
"Find the first occurrence of ITEM in SEQ.
Return the index of the matching item, or nil if not found.
\nKeywords supported: :test :test-not :key :start :end :from-end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :if :if-not
(:start 0) :end :from-end) ()
(cl--position item seq cl-start cl-end cl-from-end)))
(defun cl--position (item seq start &optional end from-end)
(if (listp seq)
(let ((p (nthcdr start seq))
res)
(while (and p (or (null end) (< start end)) (or (null res) from-end))
(if (cl--check-test item (car p))
(setq res start))
(setq p (cdr p) start (1+ start)))
res)
(or end (setq end (length seq)))
(if from-end
(progn
(while (and (>= (setq end (1- end)) start)
(not (cl--check-test item (aref seq end)))))
(and (>= end start) end))
(while (and (< start end)
(not (cl--check-test item (aref seq start))))
(setq start (1+ start)))
(and (< start end) start))))
;;;###autoload
(defun cl-position-if (pred list &rest cl-keys)
"Find the first item satisfying PREDICATE in SEQ.
Return the index of the matching item, or nil if not found.
\nKeywords supported: :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-position pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-position-if-not (pred list &rest cl-keys)
"Find the first item not satisfying PREDICATE in SEQ.
Return the index of the matching item, or nil if not found.
\nKeywords supported: :key :start :end :from-end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-position pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-count (item seq &rest cl-keys)
"Count the number of occurrences of ITEM in SEQ.
\nKeywords supported: :test :test-not :key :start :end
\n(fn ITEM SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords (:test :test-not :key :if :if-not (:start 0) :end) ()
(let ((count 0) x)
(or cl-end (setq cl-end (length seq)))
(if (consp seq) (setq seq (nthcdr cl-start seq)))
(while (< cl-start cl-end)
(setq x (if (consp seq) (pop seq) (aref seq cl-start)))
(if (cl--check-test item x) (incf count))
(setq cl-start (1+ cl-start)))
count)))
;;;###autoload
(defun cl-count-if (pred list &rest cl-keys)
"Count the number of items satisfying PREDICATE in SEQ.
\nKeywords supported: :key :start :end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-count pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-count-if-not (pred list &rest cl-keys)
"Count the number of items not satisfying PREDICATE in SEQ.
\nKeywords supported: :key :start :end
\n(fn PREDICATE SEQ [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-count pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-mismatch (seq1 seq2 &rest cl-keys)
"Compare SEQ1 with SEQ2, return index of first mismatching element.
Return nil if the sequences match. If one sequence is a prefix of the
other, the return value indicates the end of the shorter sequence.
\nKeywords supported: :test :test-not :key :start1 :end1 :start2 :end2 :from-end
\n(fn SEQ1 SEQ2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :from-end
(:start1 0) :end1 (:start2 0) :end2) ()
(or cl-end1 (setq cl-end1 (length seq1)))
(or cl-end2 (setq cl-end2 (length seq2)))
(if cl-from-end
(progn
(while (and (< cl-start1 cl-end1) (< cl-start2 cl-end2)
(cl--check-match (elt seq1 (1- cl-end1))
(elt seq2 (1- cl-end2))))
(setq cl-end1 (1- cl-end1) cl-end2 (1- cl-end2)))
(and (or (< cl-start1 cl-end1) (< cl-start2 cl-end2))
(1- cl-end1)))
(let ((p1 (and (listp seq1) (nthcdr cl-start1 seq1)))
(p2 (and (listp seq2) (nthcdr cl-start2 seq2))))
(while (and (< cl-start1 cl-end1) (< cl-start2 cl-end2)
(cl--check-match (if p1 (car p1)
(aref seq1 cl-start1))
(if p2 (car p2)
(aref seq2 cl-start2))))
(setq p1 (cdr p1) p2 (cdr p2)
cl-start1 (1+ cl-start1) cl-start2 (1+ cl-start2)))
(and (or (< cl-start1 cl-end1) (< cl-start2 cl-end2))
cl-start1)))))
;;;###autoload
(defun cl-search (seq1 seq2 &rest cl-keys)
"Search for SEQ1 as a subsequence of SEQ2.
Return the index of the leftmost element of the first match found;
return nil if there are no matches.
\nKeywords supported: :test :test-not :key :start1 :end1 :start2 :end2 :from-end
\n(fn SEQ1 SEQ2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords ( :test :test-not :key :from-end
(:start1 0) :end1 (:start2 0) :end2) ()
(or cl-end1 (setq cl-end1 (length seq1)))
(or cl-end2 (setq cl-end2 (length seq2)))
(if (>= cl-start1 cl-end1)
(if cl-from-end cl-end2 cl-start2)
(let* ((len (- cl-end1 cl-start1))
(first (cl--check-key (elt seq1 cl-start1)))
(cl-if nil) pos)
(setq cl-end2 (- cl-end2 (1- len)))
(while (and (< cl-start2 cl-end2)
(setq pos (cl--position first seq2
cl-start2 cl-end2 cl-from-end))
(apply #'cl-mismatch seq1 seq2
:start1 (1+ cl-start1) :end1 cl-end1
:start2 (1+ pos) :end2 (+ pos len)
:from-end nil cl-keys))
(if cl-from-end (setq cl-end2 pos) (setq cl-start2 (1+ pos))))
(and (< cl-start2 cl-end2) pos)))))
;;;###autoload
(defun cl-sort (seq pred &rest cl-keys)
"Sort the argument SEQ according to PREDICATE.
This is a destructive function; it reuses the storage of SEQ if possible.
\nKeywords supported: :key
\n(fn SEQ PREDICATE [KEYWORD VALUE]...)"
;; It's safe to ignore the return value when used on arrays,
;; but most calls pass lists.
(declare (important-return-value t))
(if (nlistp seq)
(if (stringp seq)
(concat (apply #'cl-sort (vconcat seq) pred cl-keys))
(cl-replace seq
(apply #'cl-sort (append seq nil) pred cl-keys)))
(cl--parsing-keywords (:key) ()
(if (memq cl-key '(nil identity))
(sort seq pred)
(sort seq (lambda (x y)
(funcall pred (funcall cl-key x)
(funcall cl-key y))))))))
;;;###autoload
(defun cl-stable-sort (seq pred &rest cl-keys)
"Sort the argument SEQ stably according to PREDICATE.
This is a destructive function; it reuses the storage of SEQ if possible.
\nKeywords supported: :key
\n(fn SEQ PREDICATE [KEYWORD VALUE]...)"
;; It's safe to ignore the return value when used on arrays,
;; but most calls pass lists.
(declare (important-return-value t))
(apply #'cl-sort seq pred cl-keys))
;;;###autoload
(defun cl-merge (type seq1 seq2 pred &rest cl-keys)
"Destructively merge the two sequences to produce a new sequence.
TYPE is the sequence type to return, SEQ1 and SEQ2 are the two argument
sequences, and PREDICATE is a `less-than' predicate on the elements.
\nKeywords supported: :key
\n(fn TYPE SEQ1 SEQ2 PREDICATE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(or (listp seq1) (setq seq1 (append seq1 nil)))
(or (listp seq2) (setq seq2 (append seq2 nil)))
(cl--parsing-keywords (:key) ()
(let ((res nil))
(while (and seq1 seq2)
(if (funcall pred (cl--check-key (car seq2))
(cl--check-key (car seq1)))
(push (pop seq2) res)
(push (pop seq1) res)))
(cl-coerce (nconc (nreverse res) seq1 seq2) type))))
;;;###autoload
(defun cl-member (item list &rest cl-keys)
"Find the first occurrence of ITEM in LIST.
Return the sublist of LIST whose car is ITEM.
\nKeywords supported: :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
(declare (important-return-value t)
(compiler-macro cl--compiler-macro-member))
(if cl-keys
(cl--parsing-keywords (:test :test-not :key :if :if-not) ()
(while (and list (not (cl--check-test item (car list))))
(setq list (cdr list)))
list)
(memql item list)))
;;;###autoload
(defun cl-member-if (pred list &rest cl-keys)
"Find the first item satisfying PREDICATE in LIST.
Return the sublist of LIST whose car matches.
This function is obsolete: use `member-if'. The new function does not
support the old `:key KEY-FN' argument, but it is better to compose any
KEY-FN into PRED. For example, you can replace
(cl-member-if #\\='foo items :key #\\='bar)
with
(member-if (lambda (x) (foo (bar x))) items)
(fn PREDICATE LIST [:KEY KEY-FN])"
(declare (important-return-value t))
(apply #'cl-member pred list :test #'funcall cl-keys))
(make-obsolete 'cl-member-if 'member-if "31.1")
;;;###autoload
(defun cl-member-if-not (pred list &rest cl-keys)
"Find the first item not satisfying PREDICATE in LIST.
Return the sublist of LIST whose car matches.
This function is deprecated in the Common Lisp standard.
Prefer `member-if' with a negated predicate, and composing any `:key'
function into the predicate.
\nKeywords supported: :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-member pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl--adjoin (item list &rest cl-keys)
(if (cl--parsing-keywords (:key) t
(apply #'cl-member (cl--check-key item) list cl-keys))
list
(cons item list)))
;;;###autoload
(defun cl-assoc (item alist &rest cl-keys)
"Find the first item whose car matches ITEM in LIST.
\nKeywords supported: :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
(declare (important-return-value t)
(compiler-macro cl--compiler-macro-assoc))
(if cl-keys
(cl--parsing-keywords (:test :test-not :key :if :if-not) ()
(while (and alist
(or (not (consp (car alist)))
(not (cl--check-test item (car (car alist))))))
(setq alist (cdr alist)))
(and alist (car alist)))
(if (and (numberp item) (not (fixnump item)))
(assoc item alist)
(assq item alist))))
;;;###autoload
(defun cl-assoc-if (pred list &rest cl-keys)
"Find the first item whose car satisfies PREDICATE in LIST.
\nKeywords supported: :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-assoc pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-assoc-if-not (pred list &rest cl-keys)
"Find the first item whose car does not satisfy PREDICATE in LIST.
\nKeywords supported: :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-assoc pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-rassoc (item alist &rest cl-keys)
"Find the first item whose cdr matches ITEM in LIST.
\nKeywords supported: :test :test-not :key
\n(fn ITEM LIST [KEYWORD VALUE]...)"
(declare (important-return-value t))
(if (or cl-keys (numberp item))
(cl--parsing-keywords (:test :test-not :key :if :if-not) ()
(while (and alist
(or (not (consp (car alist)))
(not (cl--check-test item (cdr (car alist))))))
(setq alist (cdr alist)))
(and alist (car alist)))
(rassq item alist)))
;;;###autoload
(defun cl-rassoc-if (pred list &rest cl-keys)
"Find the first item whose cdr satisfies PREDICATE in LIST.
\nKeywords supported: :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-rassoc pred list :test #'funcall cl-keys))
;;;###autoload
(defun cl-rassoc-if-not (pred list &rest cl-keys)
"Find the first item whose cdr does not satisfy PREDICATE in LIST.
\nKeywords supported: :key
\n(fn PREDICATE LIST [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-rassoc pred list :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-union (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-union operation.
The resulting list contains all items that appear in either LIST1 or LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cond ((null list1) list2) ((null list2) list1)
((and (not cl-keys) (equal list1 list2)) list1)
(t
(or (>= (length list1) (length list2))
(setq list1 (prog1 list2 (setq list2 list1))))
(while list2
(if (or cl-keys (numberp (car list2)))
(setq list1
(apply #'cl-adjoin (car list2) list1 cl-keys))
(or (memq (car list2) list1)
(push (car list2) list1)))
(pop list2))
list1)))
;;;###autoload
(defun cl-nunion (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-union operation.
The resulting list contains all items that appear in either LIST1 or LIST2.
This is a destructive function; it reuses the storage of LIST1 and LIST2
whenever possible.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cond ((null list1) list2) ((null list2) list1)
(t (apply #'cl-union list1 list2 cl-keys))))
;;;###autoload
(defun cl-intersection (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-intersection operation.
The resulting list contains all items that appear in both LIST1 and LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(and list1 list2
(if (equal list1 list2) list1
(cl--parsing-keywords (:key) (:test :test-not)
(let ((res nil))
(or (>= (length list1) (length list2))
(setq list1 (prog1 list2 (setq list2 list1))))
(while list2
(if (if (or cl-keys (numberp (car list2)))
(apply #'cl-member (cl--check-key (car list2))
list1 cl-keys)
(memq (car list2) list1))
(push (car list2) res))
(pop list2))
res)))))
;;;###autoload
(defun cl-nintersection (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-intersection operation.
The resulting list contains all items that appear in both LIST1 and LIST2.
This is a destructive function; it reuses the storage of LIST1 (but not
LIST2) whenever possible.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(and list1 list2 (apply #'cl-intersection list1 list2 cl-keys)))
;;;###autoload
(defun cl-set-difference (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-difference operation.
The resulting list contains all items that appear in LIST1 but not LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(if (or (null list1) (null list2)) list1
(cl--parsing-keywords (:key) (:test :test-not)
(let ((res nil))
(while list1
(or (if (or cl-keys (numberp (car list1)))
(apply #'cl-member (cl--check-key (car list1))
list2 cl-keys)
(memq (car list1) list2))
(push (car list1) res))
(pop list1))
(nreverse res)))))
;;;###autoload
(defun cl-nset-difference (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-difference operation.
The resulting list contains all items that appear in LIST1 but not LIST2.
This is a destructive function; it reuses the storage of LIST1 (but not
LIST2) whenever possible.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(if (or (null list1) (null list2)) list1
(apply #'cl-set-difference list1 list2 cl-keys)))
;;;###autoload
(defun cl-set-exclusive-or (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-exclusive-or operation.
The resulting list contains all items appearing in exactly one of LIST1, LIST2.
This is a non-destructive function; it makes a copy of the data if necessary
to avoid corrupting the original LIST1 and LIST2.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cond ((null list1) list2) ((null list2) list1)
((equal list1 list2) nil)
(t (append (apply #'cl-set-difference list1 list2 cl-keys)
(apply #'cl-set-difference list2 list1 cl-keys)))))
;;;###autoload
(defun cl-nset-exclusive-or (list1 list2 &rest cl-keys)
"Combine LIST1 and LIST2 using a set-exclusive-or operation.
The resulting list contains all items appearing in exactly one of LIST1, LIST2.
This is a destructive function; it reuses the storage of LIST1 and LIST2
whenever possible.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cond ((null list1) list2) ((null list2) list1)
((equal list1 list2) nil)
(t (nconc (apply #'cl-nset-difference list1 list2 cl-keys)
(apply #'cl-nset-difference list2 list1 cl-keys)))))
;;;###autoload
(defun cl-subsetp (list1 list2 &rest cl-keys)
"Return true if LIST1 is a subset of LIST2.
I.e., if every element of LIST1 also appears in LIST2.
\nKeywords supported: :test :test-not :key
\n(fn LIST1 LIST2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cond ((null list1) t) ((null list2) nil)
((equal list1 list2) t)
(t (cl--parsing-keywords (:key) (:test :test-not)
(while (and list1
(apply #'cl-member (cl--check-key (car list1))
list2 cl-keys))
(pop list1))
(null list1)))))
;;;###autoload
(defun cl-subst-if (new pred tree &rest cl-keys)
"Substitute NEW for elements matching PREDICATE in TREE (non-destructively).
Return a copy of TREE with all matching elements replaced by NEW.
\nKeywords supported: :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-sublis (list (cons pred new)) tree :test #'funcall cl-keys))
;;;###autoload
(defun cl-subst-if-not (new pred tree &rest cl-keys)
"Substitute NEW for elts not matching PREDICATE in TREE (non-destructively).
Return a copy of TREE with all non-matching elements replaced by NEW.
\nKeywords supported: :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-sublis (list (cons pred new)) tree :test-not #'funcall cl-keys))
;;;###autoload
(defun cl-nsubst (new old tree &rest cl-keys)
"Substitute NEW for OLD everywhere in TREE (destructively).
Any element of TREE which is `eql' to OLD is changed to NEW (via a call
to `setcar').
\nKeywords supported: :test :test-not :key
\n(fn NEW OLD TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-nsublis (list (cons old new)) tree cl-keys))
;;;###autoload
(defun cl-nsubst-if (new pred tree &rest cl-keys)
"Substitute NEW for elements matching PREDICATE in TREE (destructively).
Any element of TREE which matches is changed to NEW (via a call to `setcar').
\nKeywords supported: :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-nsublis (list (cons pred new)) tree :test #'funcall cl-keys))
;;;###autoload
(defun cl-nsubst-if-not (new pred tree &rest cl-keys)
"Substitute NEW for elements not matching PREDICATE in TREE (destructively).
Any element of TREE which matches is changed to NEW (via a call to `setcar').
\nKeywords supported: :key
\n(fn NEW PREDICATE TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(apply #'cl-nsublis (list (cons pred new)) tree :test-not #'funcall cl-keys))
(defvar cl--alist)
;;;###autoload
(defun cl-sublis (alist tree &rest cl-keys)
"Perform substitutions indicated by ALIST in TREE (non-destructively).
Return a copy of TREE with all matching elements replaced.
\nKeywords supported: :test :test-not :key
\n(fn ALIST TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords (:test :test-not :key :if :if-not) ()
(let ((cl--alist alist))
(cl--sublis-rec tree))))
(defun cl--sublis-rec (tree) ;Uses cl--alist cl-key/test*/if*.
(let ((temp (cl--check-key tree))
(p cl--alist))
(while (and p (not (cl--check-test-nokey (car (car p)) temp)))
(setq p (cdr p)))
(if p (cdr (car p))
(if (consp tree)
(let ((a (cl--sublis-rec (car tree)))
(d (cl--sublis-rec (cdr tree))))
(if (and (eq a (car tree)) (eq d (cdr tree)))
tree
(cons a d)))
tree))))
;;;###autoload
(defun cl-nsublis (alist tree &rest cl-keys)
"Perform substitutions indicated by ALIST in TREE (destructively).
Any matching element of TREE is changed via a call to `setcar'.
\nKeywords supported: :test :test-not :key
\n(fn ALIST TREE [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords (:test :test-not :key :if :if-not) ()
(let ((hold (list tree))
(cl--alist alist))
(cl--nsublis-rec hold)
(car hold))))
(defun cl--nsublis-rec (tree) ;Uses cl--alist cl-key/test*/if*.
(while (consp tree)
(let ((temp (cl--check-key (car tree)))
(p cl--alist))
(while (and p (not (cl--check-test-nokey (car (car p)) temp)))
(setq p (cdr p)))
(if p (setcar tree (cdr (car p)))
(if (consp (car tree)) (cl--nsublis-rec (car tree))))
(setq temp (cl--check-key (cdr tree)) p cl--alist)
(while (and p (not (cl--check-test-nokey (car (car p)) temp)))
(setq p (cdr p)))
(if p
(progn (setcdr tree (cdr (car p))) (setq tree nil))
(setq tree (cdr tree))))))
;;;###autoload
(defun cl-tree-equal (x y &rest cl-keys)
"Return t if trees TREE1 and TREE2 have `eql' leaves.
Atoms are compared by `eql'; cons cells are compared recursively.
\nKeywords supported: :test :test-not :key
\n(fn TREE1 TREE2 [KEYWORD VALUE]...)"
(declare (important-return-value t))
(cl--parsing-keywords (:test :test-not :key) ()
(cl--tree-equal-rec x y)))
(defun cl--tree-equal-rec (x y) ;Uses cl-key/test*.
(while (and (consp x) (consp y)
(cl--tree-equal-rec (car x) (car y)))
(setq x (cdr x) y (cdr y)))
(and (not (consp x)) (not (consp y)) (cl--check-match x y)))
(make-obsolete-variable 'cl-seq-load-hook
"use `with-eval-after-load' instead." "28.1")
(run-hooks 'cl-seq-load-hook)
;; Local variables:
;; generated-autoload-file: "cl-loaddefs.el"
;; End:
(defun cl--compiler-macro-member (form a list &rest keys)
(let ((test (and (= (length keys) 2) (eq (car keys) :test)
(cl--const-expr-val (nth 1 keys)))))
(cond ((eq test 'eq) `(memq ,a ,list))
((eq test 'equal) `(member ,a ,list))
((or (null keys) (eq test 'eql)) `(memql ,a ,list))
(t form))))
(defun cl--compiler-macro-assoc (form a list &rest keys)
(let ((test (and (= (length keys) 2) (eq (car keys) :test)
(cl--const-expr-val (nth 1 keys)))))
(cond ((eq test 'eq) `(assq ,a ,list))
((eq test 'equal) `(assoc ,a ,list))
((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
(if (floatp (cl--const-expr-val a))
`(assoc ,a ,list) `(assq ,a ,list)))
(t form))))
;; ---- cl-loop ----
;; cl-macs.el's loop machinery (emacs-31.1), verbatim: the clause parser, the
;; binding builder and the `and'-chain builder, so every clause the Emacs macro
;; accepts expands the way Emacs expands it. `cl--map-intervals' and
;; `cl--map-overlays' are cl-extra.el's, used by `being the intervals/overlays'.
(defun cl--expr-contains (x y)
"Count number of times X refers to Y. Return nil for 0 times."
;; FIXME: This is naive, and it will cl-count Y as referred twice in
;; (let ((Y 1)) Y) even though it should be 0. Also it is often called on
;; non-macroexpanded code, so it may also miss some occurrences that would
;; only appear in the expanded code.
(cond ((equal y x) 1)
((and (consp x) (not (memq (car x) '(quote function cl-function))))
(let ((sum 0))
(while (consp x)
(setq sum (+ sum (or (cl--expr-contains (pop x) y) 0))))
(setq sum (+ sum (or (cl--expr-contains x y) 0)))
(and (> sum 0) sum)))
(t nil)))
(defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
(defvar cl--loop-bindings) (defvar cl--loop-body) (defvar cl--loop-conditions)
(defvar cl--loop-finally)
(defvar cl--loop-finish-flag) ;Symbol set to nil to exit the loop?
(defvar cl--loop-first-flag)
(defvar cl--loop-initially) (defvar cl--loop-iterator-function)
(defvar cl--loop-name)
(defvar cl--loop-result) (defvar cl--loop-result-explicit)
(defvar cl--loop-result-var) (defvar cl--loop-steps)
(defvar cl--loop-symbol-macs)
(defun cl--loop-set-iterator-function (kind iterator)
(if cl--loop-iterator-function
;; FIXME: Of course, we could make it work, but why bother.
(error "Iteration on %S does not support this combination" kind)
(setq cl--loop-iterator-function iterator)))
;;;###autoload
(defmacro cl-loop (&rest loop-args)
"The Common Lisp `loop' macro.
Valid clauses include:
For clauses:
for VAR from/upfrom/downfrom EXPR1 to/upto/downto/above/below EXPR2
[by EXPR3]
for VAR = EXPR1 then EXPR2
for VAR in/on/in-ref LIST [by FUNC]
for VAR across/across-ref ARRAY
for VAR being:
the elements of/of-ref SEQUENCE [using (index VAR2)]
the symbols [of OBARRAY]
the hash-keys/hash-values of HASH-TABLE [using (hash-values/hash-keys V2)]
the key-codes/key-bindings/key-seqs of KEYMAP [using (key-bindings VAR2)]
the overlays/intervals [of BUFFER] [from POS1] [to POS2]
the frames/buffers
the windows [of FRAME]
Iteration clauses:
repeat INTEGER
while/until/always/never/thereis CONDITION
Accumulation clauses:
collect/append/nconc/concat/vconcat/count/sum/maximize/minimize FORM
[into VAR]
Miscellaneous clauses:
with VAR = INIT
if/when/unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...]
named NAME
initially/finally [do] EXPRS...
do EXPRS...
[finally] return EXPR
For more details, see Info node `(cl)Loop Facility'.
\(fn CLAUSE...)"
(declare (debug (&rest &or
;; These are usually followed by a symbol, but it can
;; actually be any destructuring-bind pattern, which
;; would erroneously match `form'.
[[&or "for" "as" "with" "and"] sexp]
;; These are followed by expressions which could
;; erroneously match `symbolp'.
[[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
"above" "below" "by" "in" "on" "=" "across"
"repeat" "while" "until" "always" "never"
"thereis" "collect" "append" "nconc" "sum"
"count" "maximize" "minimize"
"if" "when" "unless"
"return"]
form]
["using" (symbolp symbolp)]
;; Simple default, which covers 99% of the cases.
symbolp form)))
(if (not (memq t (mapcar #'symbolp
(delq nil (delq t (cl-copy-list loop-args))))))
`(cl-block nil (while t ,@loop-args))
(let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
(cl--loop-body nil) (cl--loop-steps nil)
(cl--loop-result nil) (cl--loop-result-explicit nil)
(cl--loop-result-var nil) (cl--loop-finish-flag nil)
(cl--loop-accum-var nil) (cl--loop-accum-vars nil)
(cl--loop-initially nil) (cl--loop-finally nil)
(cl--loop-iterator-function nil) (cl--loop-first-flag nil)
(cl--loop-symbol-macs nil)
(cl--loop-conditions nil))
;; Here is more or less how those dynbind vars are used after looping
;; over cl--parse-loop-clause:
;;
;; (cl-block ,cl--loop-name
;; (cl-symbol-macrolet ,cl--loop-symbol-macs
;; (foldl #'cl--loop-let
;; `((,cl--loop-result-var)
;; ((,cl--loop-first-flag t))
;; ((,cl--loop-finish-flag t))
;; ,@cl--loop-bindings)
;; ,@(nreverse cl--loop-initially)
;; (while ;(well: cl--loop-iterator-function)
;; ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
;; ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
;; ,@(nreverse cl--loop-steps)
;; (setq ,cl--loop-first-flag nil))
;; (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
;; ,cl--loop-result-var
;; ,@(nreverse cl--loop-finally)
;; ,(or cl--loop-result-explicit
;; cl--loop-result)))))
;;
(setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
(while (not (eq (car cl--loop-args) 'cl-end-loop))
(cl--parse-loop-clause))
(if cl--loop-finish-flag
(push `((,cl--loop-finish-flag t)) cl--loop-bindings))
(if cl--loop-first-flag
(progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
(push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
(let* ((epilogue (nconc (nreverse cl--loop-finally)
(list (or cl--loop-result-explicit
cl--loop-result))))
(ands (cl--loop-build-ands (nreverse cl--loop-body)))
(while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
(body (append
(nreverse cl--loop-initially)
(list (if cl--loop-iterator-function
`(cl-block --cl-finish--
,(funcall cl--loop-iterator-function
(if (eq (car ands) t) while-body
(cons `(or ,(car ands)
(cl-return-from
--cl-finish--
nil))
while-body))))
`(while ,(car ands) ,@while-body)))
(if cl--loop-finish-flag
(if (equal epilogue '(nil)) (list cl--loop-result-var)
`((if ,cl--loop-finish-flag
(progn ,@epilogue) ,cl--loop-result-var)))
epilogue))))
(if cl--loop-result-var
(push (list cl--loop-result-var) cl--loop-bindings))
(while cl--loop-bindings
(if (cdar cl--loop-bindings)
(setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
(let ((lets nil))
(while (and cl--loop-bindings
(not (cdar cl--loop-bindings)))
(push (car (pop cl--loop-bindings)) lets))
(setq body (list (cl--loop-let lets body nil))))))
(if cl--loop-symbol-macs
(setq body
(list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
`(cl-block ,cl--loop-name ,@body)))))
(defmacro cl--push-clause-loop-body (clause)
"Apply CLAUSE to both `cl--loop-conditions' and `cl--loop-body'."
(macroexp-let2 nil sym clause
`(progn
(push ,sym cl--loop-conditions)
(push ,sym cl--loop-body))))
;; Below is a complete spec for cl-loop, in several parts that correspond
;; to the syntax given in CLtL2. The specs do more than specify where
;; the forms are; it also specifies, as much as Edebug allows, all the
;; syntactically valid cl-loop clauses. The disadvantage of this
;; completeness is rigidity, but the "for ... being" clause allows
;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
;; (def-edebug-spec cl-loop
;; ([&optional ["named" symbolp]]
;; [&rest
;; &or
;; ["repeat" form]
;; loop-for-as
;; loop-with
;; loop-initial-final]
;; [&rest loop-clause]
;; ))
;; (def-edebug-elem-spec 'loop-with
;; '("with" loop-var
;; loop-type-spec
;; [&optional ["=" form]]
;; &rest ["and" loop-var
;; loop-type-spec
;; [&optional ["=" form]]]))
;; (def-edebug-elem-spec 'loop-for-as
;; '([&or "for" "as"] loop-for-as-subclause
;; &rest ["and" loop-for-as-subclause]))
;; (def-edebug-elem-spec 'loop-for-as-subclause
;; '(loop-var
;; loop-type-spec
;; &or
;; [[&or "in" "on" "in-ref" "across-ref"]
;; form &optional ["by" function-form]]
;; ["=" form &optional ["then" form]]
;; ["across" form]
;; ["being"
;; [&or "the" "each"]
;; &or
;; [[&or "element" "elements"]
;; [&or "of" "in" "of-ref"] form
;; &optional "using" ["index" symbolp]];; is this right?
;; [[&or "hash-key" "hash-keys"
;; "hash-value" "hash-values"]
;; [&or "of" "in"]
;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
;; "hash-key" "hash-keys"] sexp)]]
;; [[&or "symbol" "present-symbol" "external-symbol"
;; "symbols" "present-symbols" "external-symbols"]
;; [&or "in" "of"] package-p]
;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
;; [[&or "frame" "frames"
;; "screen" "screens"
;; "buffer" "buffers"]]
;; [[&or "window" "windows"]
;; [&or "of" "in"] form]
;; [[&or "overlay" "overlays"
;; "extent" "extents"]
;; [&or "of" "in"] form
;; &optional [[&or "from" "to"] form]]
;; [[&or "interval" "intervals"]
;; [&or "in" "of"] form
;; &optional [[&or "from" "to"] form]
;; ["property" form]]
;; [[&or "key-code" "key-codes"
;; "key-seq" "key-seqs"
;; "key-binding" "key-bindings"]
;; [&or "in" "of"] form
;; &optional ["using" ([&or "key-code" "key-codes"
;; "key-seq" "key-seqs"
;; "key-binding" "key-bindings"]
;; sexp)]]
;; ;; For arbitrary extensions, recognize anything else.
;; [symbolp &rest &or symbolp form]
;; ]
;; ;; arithmetic - must be last since all parts are optional.
;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
;; [&optional ["by" form]]
;; ]))
;; (def-edebug-elem-spec 'loop-initial-final
;; '(&or ["initially"
;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
;; &rest loop-non-atomic-expr]
;; ["finally" &or
;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
;; ["return" form]]))
;; (def-edebug-elem-spec 'loop-and-clause
;; '(loop-clause &rest ["and" loop-clause]))
;; (def-edebug-elem-spec 'loop-clause
;; '(&or
;; [[&or "while" "until" "always" "never" "thereis"] form]
;; [[&or "collect" "collecting"
;; "append" "appending"
;; "nconc" "nconcing"
;; "concat" "vconcat"] form
;; [&optional ["into" loop-var]]]
;; [[&or "count" "counting"
;; "sum" "summing"
;; "maximize" "maximizing"
;; "minimize" "minimizing"] form
;; [&optional ["into" loop-var]]
;; loop-type-spec]
;; [[&or "if" "when" "unless"]
;; form loop-and-clause
;; [&optional ["else" loop-and-clause]]
;; [&optional "end"]]
;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
;; ["return" form]
;; loop-initial-final
;; ))
;; (def-edebug-elem-spec 'loop-non-atomic-expr
;; '([¬ atom] form))
;; (def-edebug-elem-spec 'loop-var
;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
;; ;; loop-var =>
;; ;; (loop-var . [&or nil loop-var])
;; ;; (symbolp . [&or nil loop-var])
;; ;; (symbolp . loop-var)
;; ;; (symbolp . (symbolp . [&or nil loop-var]))
;; ;; (symbolp . (symbolp . loop-var))
;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
;; '(&or (loop-var . [&or nil loop-var]) [gate symbolp]))
;; (def-edebug-elem-spec 'loop-type-spec
;; '(&optional ["of-type" loop-d-type-spec]))
;; (def-edebug-elem-spec 'loop-d-type-spec
;; '(&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
(defun cl--parse-loop-clause () ; uses loop-*
(let ((word (pop cl--loop-args))
(hash-types '(hash-key hash-keys hash-value hash-values))
(key-types '(key-code key-codes key-seq key-seqs
key-binding key-bindings)))
(cond
((null cl--loop-args)
(error "Malformed `cl-loop' macro"))
((eq word 'named)
(setq cl--loop-name (pop cl--loop-args)))
((eq word 'initially)
(if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
(or (consp (car cl--loop-args))
(error "Syntax error on `initially' clause"))
(while (consp (car cl--loop-args))
(push (pop cl--loop-args) cl--loop-initially)))
((eq word 'finally)
(if (eq (car cl--loop-args) 'return)
(setq cl--loop-result-explicit
(or (cl--pop2 cl--loop-args) '(quote nil)))
(if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
(or (consp (car cl--loop-args))
(error "Syntax error on `finally' clause"))
(if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
(setq cl--loop-result-explicit
(or (nth 1 (pop cl--loop-args)) '(quote nil)))
(while (consp (car cl--loop-args))
(push (pop cl--loop-args) cl--loop-finally)))))
((memq word '(for as))
(let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
(ands nil))
(while
;; Use `gensym' rather than `make-symbol'. It's important that
;; (not (eq (symbol-name var1) (symbol-name var2))) because
;; these vars get added to the macro-environment.
(let ((var (or (pop cl--loop-args) (gensym "--cl-var--"))))
(setq word (pop cl--loop-args))
(if (eq word 'being) (setq word (pop cl--loop-args)))
(if (memq word '(the each)) (setq word (pop cl--loop-args)))
(if (memq word '(buffer buffers))
(setq word 'in
cl--loop-args (cons '(buffer-list) cl--loop-args)))
(cond
((memq word '(from downfrom upfrom to downto upto
above below by))
(push word cl--loop-args)
(if (memq (car cl--loop-args) '(downto above))
(error "Must specify `from' value for downward cl-loop"))
(let* ((down (or (eq (car cl--loop-args) 'downfrom)
(memq (nth 2 cl--loop-args)
'(downto above))))
(excl (or (memq (car cl--loop-args) '(above below))
(memq (nth 2 cl--loop-args)
'(above below))))
(start (and (memq (car cl--loop-args)
'(from upfrom downfrom))
(cl--pop2 cl--loop-args)))
(end (and (memq (car cl--loop-args)
'(to upto downto above below))
(cl--pop2 cl--loop-args)))
(step (and (eq (car cl--loop-args) 'by)
(cl--pop2 cl--loop-args)))
(end-var (and (not (macroexp-const-p end))
(make-symbol "--cl-var--")))
(step-var (and (not (macroexp-const-p step))
(make-symbol "--cl-var--"))))
(and step (numberp step) (<= step 0)
(error "Loop `by' value is not positive: %s" step))
(push (list var (or start 0)) loop-for-bindings)
(if end-var (push (list end-var end) loop-for-bindings))
(if step-var (push (list step-var step)
loop-for-bindings))
(when end
(cl--push-clause-loop-body
(list
(if down (if excl '> '>=) (if excl '< '<=))
var (or end-var end))))
(push (list var (list (if down '- '+) var
(or step-var step 1)))
loop-for-steps)))
((memq word '(in in-ref on))
(let* ((on (eq word 'on))
(temp (if (and on (symbolp var))
var (make-symbol "--cl-var--"))))
(push (list temp (pop cl--loop-args)) loop-for-bindings)
(cl--push-clause-loop-body `(consp ,temp))
(if (eq word 'in-ref)
(push (list var `(car ,temp)) cl--loop-symbol-macs)
(or (eq temp var)
(progn
(push (list var nil) loop-for-bindings)
(push (list var (if on temp `(car ,temp)))
loop-for-sets))))
(push (list temp
(if (eq (car cl--loop-args) 'by)
(let ((step (cl--pop2 cl--loop-args)))
(if (and (memq (car-safe step)
'(quote function
cl-function))
(symbolp (nth 1 step)))
(list (nth 1 step) temp)
`(funcall ,step ,temp)))
`(cdr ,temp)))
loop-for-steps)))
((eq word '=)
(let* ((start (pop cl--loop-args))
(then (if (eq (car cl--loop-args) 'then)
(cl--pop2 cl--loop-args) start))
(first-assign (or cl--loop-first-flag
(setq cl--loop-first-flag
(make-symbol "--cl-var--")))))
(push (list var nil) loop-for-bindings)
(if (or ands (eq (car cl--loop-args) 'and))
(progn
(push `(,var (if ,first-assign ,start ,var)) loop-for-sets)
(push `(,var (if ,(car (cl--loop-build-ands
(nreverse cl--loop-conditions)))
,then ,var))
loop-for-steps))
(push (if (eq start then)
`(,var ,then)
`(,var (if ,first-assign ,start ,then)))
loop-for-sets))))
((memq word '(across across-ref))
(let ((temp-vec (make-symbol "--cl-vec--"))
(temp-idx (make-symbol "--cl-idx--")))
(push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
(push (list temp-idx -1) loop-for-bindings)
(push `(setq ,temp-idx (1+ ,temp-idx)) cl--loop-body)
(cl--push-clause-loop-body
`(< ,temp-idx (length ,temp-vec)))
(if (eq word 'across-ref)
(push (list var `(aref ,temp-vec ,temp-idx))
cl--loop-symbol-macs)
(push (list var nil) loop-for-bindings)
(push (list var `(aref ,temp-vec ,temp-idx))
loop-for-sets))))
((memq word '(element elements))
(let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
(and (not (memq (car cl--loop-args) '(in of)))
(error "Expected `of'"))))
(seq (cl--pop2 cl--loop-args))
(temp-seq (make-symbol "--cl-seq--"))
(temp-idx
(if (eq (car cl--loop-args) 'using)
(if (and (= (length (cadr cl--loop-args)) 2)
(eq (caadr cl--loop-args) 'index))
(cadr (cl--pop2 cl--loop-args))
(error "Bad `using' clause"))
(make-symbol "--cl-idx--"))))
(push (list temp-seq seq) loop-for-bindings)
(push (list temp-idx 0) loop-for-bindings)
(if ref
(let ((temp-len (make-symbol "--cl-len--")))
(push (list temp-len `(length ,temp-seq))
loop-for-bindings)
(push (list var `(elt ,temp-seq ,temp-idx))
cl--loop-symbol-macs)
(cl--push-clause-loop-body `(< ,temp-idx ,temp-len)))
(push (list var nil) loop-for-bindings)
(cl--push-clause-loop-body `(and ,temp-seq
(or (consp ,temp-seq)
(< ,temp-idx (length ,temp-seq)))))
(push (list var `(if (consp ,temp-seq)
(pop ,temp-seq)
(aref ,temp-seq ,temp-idx)))
loop-for-sets))
(push (list temp-idx `(1+ ,temp-idx))
loop-for-steps)))
((memq word hash-types)
(or (memq (car cl--loop-args) '(in of))
(error "Expected `of'"))
(let* ((table (cl--pop2 cl--loop-args))
(other
(if (eq (car cl--loop-args) 'using)
(if (and (= (length (cadr cl--loop-args)) 2)
(memq (caadr cl--loop-args) hash-types)
(not (eq (caadr cl--loop-args) word)))
(cadr (cl--pop2 cl--loop-args))
(error "Bad `using' clause"))
(make-symbol "--cl-var--"))))
(if (memq word '(hash-value hash-values))
(setq var (prog1 other (setq other var))))
(cl--loop-set-iterator-function
'hash-tables (lambda (body)
`(maphash (lambda (,var ,other) . ,body)
,table)))))
((memq word '(symbol present-symbol external-symbol
symbols present-symbols external-symbols))
(let ((ob (and (memq (car cl--loop-args) '(in of))
(cl--pop2 cl--loop-args))))
(cl--loop-set-iterator-function
'symbols (lambda (body)
`(mapatoms (lambda (,var) . ,body) ,ob)))))
((memq word '(overlay overlays extent extents))
(let ((buf nil) (from nil) (to nil))
(while (memq (car cl--loop-args) '(in of from to))
(cond ((eq (car cl--loop-args) 'from)
(setq from (cl--pop2 cl--loop-args)))
((eq (car cl--loop-args) 'to)
(setq to (cl--pop2 cl--loop-args)))
(t (setq buf (cl--pop2 cl--loop-args)))))
(cl--loop-set-iterator-function
'overlays (lambda (body)
`(cl--map-overlays
(lambda (,var ,(make-symbol "--cl-var--"))
(progn . ,body) nil)
,buf ,from ,to)))))
((memq word '(interval intervals))
(let ((buf nil) (prop nil) (from nil) (to nil)
(var1 (make-symbol "--cl-var1--"))
(var2 (make-symbol "--cl-var2--")))
(while (memq (car cl--loop-args) '(in of property from to))
(cond ((eq (car cl--loop-args) 'from)
(setq from (cl--pop2 cl--loop-args)))
((eq (car cl--loop-args) 'to)
(setq to (cl--pop2 cl--loop-args)))
((eq (car cl--loop-args) 'property)
(setq prop (cl--pop2 cl--loop-args)))
(t (setq buf (cl--pop2 cl--loop-args)))))
(if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
(setq var1 (car var) var2 (cdr var))
(push (list var nil) loop-for-bindings)
(push (list var `(cons ,var1 ,var2)) loop-for-sets))
(cl--loop-set-iterator-function
'intervals (lambda (body)
`(cl--map-intervals
(lambda (,var1 ,var2) . ,body)
,buf ,prop ,from ,to)))))
((memq word key-types)
(or (memq (car cl--loop-args) '(in of))
(error "Expected `of'"))
(let ((map (cl--pop2 cl--loop-args))
(other
(if (eq (car cl--loop-args) 'using)
(if (and (= (length (cadr cl--loop-args)) 2)
(memq (caadr cl--loop-args) key-types)
(not (eq (caadr cl--loop-args) word)))
(cadr (cl--pop2 cl--loop-args))
(error "Bad `using' clause"))
(make-symbol "--cl-var--"))))
(if (memq word '(key-binding key-bindings))
(setq var (prog1 other (setq other var))))
(cl--loop-set-iterator-function
'keys (lambda (body)
`(,(if (memq word '(key-seq key-seqs))
'cl--map-keymap-recursively 'map-keymap)
(lambda (,var ,other) . ,body) ,map)))))
((memq word '(frame frames screen screens))
(let ((temp (make-symbol "--cl-var--")))
(push (list var '(selected-frame))
loop-for-bindings)
(push (list temp nil) loop-for-bindings)
(cl--push-clause-loop-body `(prog1 (not (eq ,var ,temp))
(or ,temp (setq ,temp ,var))))
(push (list var `(next-frame ,var))
loop-for-steps)))
((memq word '(window windows))
(let ((scr (and (memq (car cl--loop-args) '(in of))
(cl--pop2 cl--loop-args)))
(temp (make-symbol "--cl-var--"))
(minip (make-symbol "--cl-minip--")))
(push (list var (if scr
`(frame-selected-window ,scr)
'(selected-window)))
loop-for-bindings)
;; If we started in the minibuffer, we need to
;; ensure that next-window will bring us back there
;; at some point. (Bug#7492).
;; (Consider using walk-windows instead of cl-loop if
;; you care about such things.)
(push (list minip `(minibufferp (window-buffer ,var)))
loop-for-bindings)
(push (list temp nil) loop-for-bindings)
(cl--push-clause-loop-body `(prog1 (not (eq ,var ,temp))
(or ,temp (setq ,temp ,var))))
(push (list var `(next-window ,var ,minip))
loop-for-steps)))
(t
;; This is an advertised interface: (info "(cl)Other Clauses").
(let ((handler (and (symbolp word)
(get word 'cl-loop-for-handler))))
(if handler
(funcall handler var)
(error "Expected a `for' preposition, found %s" word)))))
(eq (car cl--loop-args) 'and))
(setq ands t)
(pop cl--loop-args))
(if (and ands loop-for-bindings)
(push (nreverse loop-for-bindings) cl--loop-bindings)
(setq cl--loop-bindings (nconc (mapcar #'list loop-for-bindings)
cl--loop-bindings)))
(if loop-for-sets
(push `(progn
,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
t)
cl--loop-body))
(when loop-for-steps
(push (cons (if ands 'cl-psetq 'setq)
(apply #'append (nreverse loop-for-steps)))
cl--loop-steps))))
((eq word 'repeat)
(let ((temp (make-symbol "--cl-var--")))
(push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
(push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))
((memq word '(collect collecting))
(let ((what (pop cl--loop-args))
(var (cl--loop-handle-accum nil 'nreverse)))
(if (eq var cl--loop-accum-var)
(push `(progn (push ,what ,var) t) cl--loop-body)
(push `(progn
(setq ,var (nconc ,var (list ,what)))
t)
cl--loop-body))))
((memq word '(nconc nconcing append appending))
(let ((what (pop cl--loop-args))
(var (cl--loop-handle-accum nil 'nreverse)))
(push `(progn
(setq ,var
,(if (eq var cl--loop-accum-var)
`(nconc
(,(if (memq word '(nconc nconcing))
#'nreverse #'reverse)
,what)
,var)
`(,(if (memq word '(nconc nconcing))
#'nconc #'append)
,var ,what)))
t)
cl--loop-body)))
((memq word '(concat concating))
(let ((what (pop cl--loop-args))
(var (cl--loop-handle-accum "")))
(push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))
((memq word '(vconcat vconcating))
(let ((what (pop cl--loop-args))
(var (cl--loop-handle-accum [])))
(push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))
((memq word '(sum summing))
(let ((what (pop cl--loop-args))
(var (cl--loop-handle-accum 0)))
(push `(progn (incf ,var ,what) t) cl--loop-body)))
((memq word '(count counting))
(let ((what (pop cl--loop-args))
(var (cl--loop-handle-accum 0)))
(push `(progn (if ,what (incf ,var)) t) cl--loop-body)))
((memq word '(minimize minimizing maximize maximizing))
(push `(progn ,(macroexp-let2 macroexp-copyable-p temp
(pop cl--loop-args)
(let* ((var (cl--loop-handle-accum nil))
(func (intern (substring (symbol-name word)
0 3))))
`(setq ,var (if ,var (,func ,var ,temp) ,temp))))
t)
cl--loop-body))
((eq word 'with)
(let ((bindings nil))
(while (progn (push (list (pop cl--loop-args)
(and (eq (car cl--loop-args) '=)
(cl--pop2 cl--loop-args)))
bindings)
(eq (car cl--loop-args) 'and))
(pop cl--loop-args))
(push (nreverse bindings) cl--loop-bindings)))
((eq word 'while)
(push (pop cl--loop-args) cl--loop-body))
((eq word 'until)
(push `(not ,(pop cl--loop-args)) cl--loop-body))
((eq word 'always)
(or cl--loop-finish-flag
(setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
(push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
(setq cl--loop-result t))
((eq word 'never)
(or cl--loop-finish-flag
(setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
(push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
cl--loop-body)
(setq cl--loop-result t))
((eq word 'thereis)
(or cl--loop-finish-flag
(setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
(or cl--loop-result-var
(setq cl--loop-result-var (make-symbol "--cl-var--")))
(push `(setq ,cl--loop-finish-flag
(not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
cl--loop-body))
((memq word '(if when unless))
(let* ((cond (pop cl--loop-args))
(then (let ((cl--loop-body nil))
(cl--parse-loop-clause)
(cl--loop-build-ands (nreverse cl--loop-body))))
(else (let ((cl--loop-body nil))
(if (eq (car cl--loop-args) 'else)
(progn (pop cl--loop-args) (cl--parse-loop-clause)))
(cl--loop-build-ands (nreverse cl--loop-body))))
(simple (and (eq (car then) t) (eq (car else) t))))
(if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
(if (eq word 'unless) (setq then (prog1 else (setq else then))))
(let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
(if simple (nth 1 else) (list (nth 2 else))))))
(setq form (if (cl--expr-contains form 'it)
`(let ((it ,cond)) (if it ,@form))
`(if ,cond ,@form)))
(push (if simple `(progn ,form t) form) cl--loop-body))))
((memq word '(do doing))
(let ((body nil))
(or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
(while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
(push (cons 'progn (nreverse (cons t body))) cl--loop-body)))
((eq word 'return)
(or cl--loop-finish-flag
(setq cl--loop-finish-flag (make-symbol "--cl-var--")))
(or cl--loop-result-var
(setq cl--loop-result-var (make-symbol "--cl-var--")))
(push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
,cl--loop-finish-flag nil)
cl--loop-body))
(t
;; This is an advertised interface: (info "(cl)Other Clauses").
(let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
(or handler (error "Expected a cl-loop keyword, found %s" word))
(funcall handler))))
(if (eq (car cl--loop-args) 'and)
(progn (pop cl--loop-args) (cl--parse-loop-clause)))))
(defun cl--unused-var-p (sym)
(or (null sym) (eq ?_ (aref (symbol-name sym) 0))))
(defun cl--loop-let (specs body par) ; modifies cl--loop-bindings
"Build an expression equivalent to (let SPECS BODY).
SPECS can include bindings using `cl-loop's destructuring (not to be
confused with the patterns of `cl-destructuring-bind').
If PAR is nil, do the bindings step by step, like `let*'.
If BODY is `setq', then use SPECS for assignments rather than for bindings."
(let ((temps nil) (new nil))
(when par
(let ((p specs))
(while (and p (or (symbolp (car-safe (car p))) (null (cadar p))))
(setq p (cdr p)))
(when p
(setq par nil)
(dolist (spec specs)
(or (macroexp-const-p (cadr spec))
(let ((temp (make-symbol "--cl-var--")))
(push (list temp (cadr spec)) temps)
(setcar (cdr spec) temp)))))))
(while specs
(let* ((binding (pop specs))
(spec (car-safe binding)))
(if (and (consp binding) (or (consp spec) (cl--unused-var-p spec)))
(let* ((nspecs nil)
(expr (car (cdr-safe binding)))
(temp (last spec 0)))
(if (and (cl--unused-var-p temp) (null expr))
nil ;; Don't bother declaring/setting `temp' since it won't
;; be used when `expr' is nil, anyway.
(when (or (null temp)
(and (eq body 'setq) (cl--unused-var-p temp)))
;; Prefer a fresh uninterned symbol over "_to", to avoid
;; warnings that we set an unused variable.
(setq temp (make-symbol "--cl-var--"))
;; Make sure this temp variable is locally declared.
(when (eq body 'setq)
(push (list (list temp)) cl--loop-bindings)))
(push (list temp expr) new))
(while (consp spec)
(push (list (pop spec)
(and expr (list (if spec 'pop 'car) temp)))
nspecs))
(setq specs (nconc (nreverse nspecs) specs)))
(push binding new))))
(if (eq body 'setq)
(let ((set (cons (if par 'cl-psetq 'setq)
(apply #'nconc (nreverse new)))))
(if temps `(let* ,(nreverse temps) ,set) set))
`(,(if par 'let 'let*)
,(nconc (nreverse temps) (nreverse new)) ,@body))))
(defun cl--loop-handle-accum (def &optional func) ; uses loop-*
(if (eq (car cl--loop-args) 'into)
(let ((var (cl--pop2 cl--loop-args)))
(or (memq var cl--loop-accum-vars)
(progn (push (list (list var def)) cl--loop-bindings)
(push var cl--loop-accum-vars)))
var)
(or cl--loop-accum-var
(progn
(push (list (list
(setq cl--loop-accum-var (make-symbol "--cl-var--"))
def))
cl--loop-bindings)
(setq cl--loop-result (if func (list func cl--loop-accum-var)
cl--loop-accum-var))
cl--loop-accum-var))))
(defun cl--loop-build-ands (clauses)
"Return various representations of (and . CLAUSES).
CLAUSES is a list of Elisp expressions, where clauses of the form
\(progn E1 E2 E3 .. t) are the focus of particular optimizations.
The return value has shape (COND BODY COMBO)
such that COMBO is equivalent to (and . CLAUSES)."
(let ((ands nil)
(body nil))
;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
;; into (progn ,@A ,@B) ,@C.
(while clauses
(if (and (eq (car-safe (car clauses)) 'progn)
(eq (car (last (car clauses))) t))
(if (cdr clauses)
(setq clauses (cons (nconc (butlast (car clauses))
(if (eq (car-safe (cadr clauses))
'progn)
(cdadr clauses)
(list (cadr clauses))))
(cddr clauses)))
;; A final (progn ,@A t) is moved outside of the `and'.
(setq body (cdr (butlast (pop clauses)))))
(push (pop clauses) ands)))
(setq ands (or (nreverse ands) (list t)))
(list (if (cdr ands) (cons 'and ands) (car ands))
body
(let ((full (if body
(append ands (list (cons 'progn (append body '(t)))))
ands)))
(if (cdr full) (cons 'and full) (car full))))))
(defun cl--map-intervals (func &optional what prop start end)
(or what (setq what (current-buffer)))
(if (bufferp what)
(let (mark mark2 (next t) next2)
(with-current-buffer what
(setq mark (copy-marker (or start (point-min))))
(setq mark2 (and end (copy-marker end))))
(while (and next (or (not mark2) (< mark mark2)))
(setq next (if prop (next-single-property-change
mark prop what)
(next-property-change mark what))
next2 (or next (with-current-buffer what
(point-max))))
(funcall func (prog1 (marker-position mark)
(set-marker mark next2))
(if mark2 (min next2 mark2) next2)))
(set-marker mark nil) (if mark2 (set-marker mark2 nil)))
(or start (setq start 0))
(or end (setq end (length what)))
(while (< start end)
(let ((next (or (if prop (next-single-property-change
start prop what)
(next-property-change start what))
end)))
(funcall func start (min next end))
(setq start next)))))
;;;###autoload
(defun cl--map-overlays (func &optional buffer start end arg)
(or buffer (setq buffer (current-buffer)))
(let (ovl)
(with-current-buffer buffer
(setq ovl (overlay-lists))
(if start (setq start (copy-marker start)))
(if end (setq end (copy-marker end))))
(setq ovl (nconc (car ovl) (cdr ovl)))
(while (and ovl
(or (not (overlay-start (car ovl)))
(and end (>= (overlay-start (car ovl)) end))
(and start (<= (overlay-end (car ovl)) start))
(not (funcall func (car ovl) arg))))
(setq ovl (cdr ovl)))
(if start (set-marker start nil))
(if end (set-marker end nil))))
;;; ---- cl-macs.el / cl-extra.el: the remaining macro and number surface ----
;; Ported from GNU Emacs 31.1's cl-macs.el, cl-extra.el and cl-lib.el.
(defmacro cl-with-gensyms (names &rest body)
"Bind each of NAMES to an uninterned symbol and evaluate BODY."
(declare (debug (sexp body)) (indent 1))
`(let ,(cl-loop for name in names collect
`(,name (gensym (symbol-name ',name))))
,@body))
(defmacro cl-once-only (names &rest body)
"Generate code to evaluate each of NAMES just once in BODY."
(declare (debug (sexp body)) (indent 1))
(setq names (mapcar #'ensure-list names))
(let ((our-gensyms (cl-loop for _ in names collect (gensym))))
`(let ,(cl-loop for sym in our-gensyms collect `(,sym (gensym)))
`(let ,(list
,@(cl-loop for name in names for gensym in our-gensyms
for to-eval = (or (cadr name) (car name))
collect ``(,,gensym ,,to-eval)))
,(let ,(cl-loop for name in names for gensym in our-gensyms
collect `(,(car name) ,gensym))
,@body)))))
(defmacro cl-with-accessors (bindings instance &rest body)
"Use BINDINGS as function calls on INSTANCE inside BODY."
(declare (debug [(&rest (symbolp symbolp)) form body])
(indent 2))
(cond ((null body)
(macroexp-warn-and-return "`cl-with-accessors' used with empty body"
nil 'empty-body))
((null bindings)
(macroexp-warn-and-return "`cl-with-accessors' used without accessors"
(macroexp-progn body)
'suspicious))
(t
(cl-once-only (instance)
(let ((symbol-macros))
(dolist (b bindings)
(pcase b
(`(,(and (pred symbolp) var)
,(and (pred symbolp) accessor))
(push `(,var (,accessor ,instance))
symbol-macros))
(_
(error "Malformed `cl-with-accessors' binding: %S" b))))
`(cl-symbol-macrolet
,symbol-macros
,@body))))))
;; `cl-tagbody': each label starts a block of a `cl-case' dispatched from a
;; `while' loop; `go' is a local macro, supplied through `macroexpand-all''s
;; ENVIRONMENT, that throws the next label to the loop's catch.
(defvar cl--tagbody-alist nil)
(defmacro cl-tagbody (&rest labels-or-stmts)
"Execute statements while providing for control transfers to labels."
(let ((blocks '())
(first-label (if (consp (car labels-or-stmts))
'cl--preamble (pop labels-or-stmts))))
(let ((block (list first-label)))
(dolist (label-or-stmt labels-or-stmts)
(if (consp label-or-stmt) (push label-or-stmt block)
(unless (eq 'go (car-safe (car-safe block)))
(push `(go ,label-or-stmt) block))
(push (nreverse block) blocks)
(setq block (list label-or-stmt))))
(unless (eq 'go (car-safe (car-safe block)))
(push '(go cl--exit) block))
(push (nreverse block) blocks))
(let ((catch-tag (make-symbol "cl--tagbody-tag"))
(cl--tagbody-alist cl--tagbody-alist))
(push (cons 'cl--exit catch-tag) cl--tagbody-alist)
(dolist (block blocks)
(push (cons (car block) catch-tag) cl--tagbody-alist))
(macroexpand-all
`(let ((next-label ',first-label))
(while
(not (eq (setq next-label
(catch ',catch-tag
(cl-case next-label
,@blocks)))
'cl--exit))))
`((go . ,(lambda (label)
(let ((catch-tag (cdr (assq label cl--tagbody-alist))))
(unless catch-tag
(error "Unknown cl-tagbody go label `%S'" label))
`(throw ',catch-tag ',label))))
,@macroexpand-all-environment)))))
(defun cl--prog (binder bindings body)
(let (decls)
(while (eq 'declare (car-safe (car body)))
(push (pop body) decls))
`(cl-block nil
(,binder ,bindings
,@(nreverse decls)
(cl-tagbody . ,body)))))
(defmacro cl-prog (bindings &rest body)
"Run BODY like a `cl-tagbody' after setting up the BINDINGS."
(cl--prog 'let bindings body))
(defmacro cl-prog* (bindings &rest body)
"Run BODY like a `cl-tagbody' after setting up the BINDINGS."
(cl--prog 'let* bindings body))
(defmacro cl-do-symbols (spec &rest body)
"Loop over all symbols, or all symbols of OBARRAY."
(declare (indent 1))
`(cl-block nil
(let (,(car spec))
(mapatoms #'(lambda (,(car spec)) ,@body)
,@(and (cadr spec) (list (cadr spec))))
,(nth 2 spec))))
(defmacro cl-do-all-symbols (spec &rest body)
"Like `cl-do-symbols', but use the default obarray."
(declare (indent 1))
`(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
;; Outside the byte-compiler FORM is evaluated at expansion time and quoted.
(defmacro cl-load-time-value (form &optional _read-only)
"Like `progn', but evaluates the body at load time."
`',(eval form lexical-binding))
;; Declarations only matter to the byte-compiler; interpreted, this is nil.
(defmacro cl-declare (&rest _specs)
"Declare SPECS about the current function while compiling."
nil)
(defmacro cl-define-compiler-macro (func args &rest body)
"Define a compiler-only macro."
(declare (indent 2))
(let ((p args) (res nil))
(while (consp p) (push (pop p) res))
(setq args (nconc (nreverse res) (and p (list '&rest p)))))
(let ((fname (intern (concat (symbol-name func) "--cmacro"))))
`(eval-and-compile
(cl-defun ,fname ,(if (memq '&whole args) (delq '&whole args)
(cons '_cl-whole-arg args))
,@body)
(define-symbol-prop ',func 'compiler-macro #',fname))))
(defun cl-compiler-macroexpand (form)
"Like `macroexpand', but for compiler macros."
(while
(let ((func (car-safe form)) (handler nil))
(while (and (symbolp func)
(not (setq handler (get func 'compiler-macro)))
(fboundp func)
(or (not (autoloadp (symbol-function func)))
(autoload-do-load (symbol-function func) func)))
(setq func (symbol-function func)))
(and handler
(not (eq form (setq form (apply handler form (cdr form))))))))
form)
;; cl-macs.el (31.1): optimize away unused block-wrappers. `cl--block-throw'
;; marks its block as used while the wrapper's body is expanded; a block nothing
;; throws to expands to its body alone.
(defvar cl--active-block-names nil)
(cl-define-compiler-macro cl--block-wrapper (form)
(pcase form
(`(let ((,var . ,val)) (catch ,var . ,body))
(let* ((cl-entry (cons var nil))
(cl--active-block-names (cons cl-entry cl--active-block-names))
(cl-body (macroexpand-all ;Performs compiler-macro expansions.
(macroexp-progn body)
macroexpand-all-environment)))
;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
;; to indicate that this return value is already fully expanded.
(if (cdr cl-entry)
`(let ((,var . ,val)) (catch ,var ,@(macroexp-unprogn cl-body)))
cl-body)))
;; `form' was somehow mangled, god knows what happened, let's not touch it.
(_ form)))
(cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
(let ((cl-found (and (symbolp cl-tag) (assq cl-tag cl--active-block-names))))
(if cl-found (setcdr cl-found t)))
`(throw ,cl-tag ,cl-value))
;; Emacs also gives the function an inlining compiler macro built on
;; `cl--defsubst-expand'; that rewrite only changes how a call is compiled,
;; not what it returns, and is not ported.
(defmacro cl-defsubst (name args &rest body)
"Define NAME as a function, like `cl-defun'."
(declare (indent 2))
`(progn nil (cl-defun ,name ,args ,@body)))
;; cl-extra.el's random-number generator: "ran3" from Numerical Recipes, an
;; additive congruential method over a 55-entry state vector.
(defun cl--random-time ()
(car (time-convert nil t)))
(cl-defstruct (cl--random-state
(:copier nil)
(:predicate cl-random-state-p)
(:constructor nil)
(:constructor cl--make-random-state (vec)))
(i -1) (j 30) vec)
(defvar cl--random-state (cl--make-random-state (cl--random-time)))
(defun cl-random (lim &optional state)
"Return a pseudo-random nonnegative number less than LIM, an integer or float."
(or state (setq state cl--random-state))
(let ((vec (cl--random-state-vec state)))
(if (integerp vec)
(let ((i 0) (j (- 1357335 (abs (% vec 1357333)))) (k 1))
(setf (cl--random-state-vec state)
(setq vec (make-vector 55 nil)))
(aset vec 0 j)
(while (> (setq i (% (+ i 21) 55)) 0)
(aset vec i (setq j (prog1 k (setq k (- j k))))))
(while (< (setq i (1+ i)) 200) (cl-random 2 state))))
(let* ((i (cl-callf (lambda (x) (% (1+ x) 55)) (cl--random-state-i state)))
(j (cl-callf (lambda (x) (% (1+ x) 55)) (cl--random-state-j state)))
(n (aset vec i (logand 8388607 (- (aref vec i) (aref vec j))))))
(cond
((natnump lim)
(if (<= lim 512) (% n lim)
(if (> lim 8388607) (setq n (+ (ash n 9) (cl-random 512 state))))
(let ((mask 1023))
(while (< mask (1- lim)) (setq mask (1+ (+ mask mask))))
(if (< (setq n (logand n mask)) lim) n (cl-random lim state)))))
((< 0 lim 1.0e+INF)
(* (/ n '8388608e0) lim))
(t
(error "Limit %S not supported by cl-random" lim))))))
(defun cl-make-random-state (&optional state)
"Return a copy of random-state STATE, or of the internal state if omitted."
(unless state (setq state cl--random-state))
(if (cl-random-state-p state)
(copy-sequence state)
(cl--make-random-state (if (integerp state) state (cl--random-time)))))
;; cl-lib.el's float parameters are nil until `cl-float-limits' measures them.
(defconst cl-most-positive-float nil)
(defconst cl-most-negative-float nil)
(defconst cl-least-positive-float nil)
(defconst cl-least-negative-float nil)
(defconst cl-least-positive-normalized-float nil)
(defconst cl-least-negative-normalized-float nil)
(defconst cl-float-epsilon nil)
(defconst cl-float-negative-epsilon nil)
(defun cl--finite-do (func a b)
(condition-case _
(let ((res (funcall func a b)))
(and (numberp res) (/= res (/ res 2)) res))
(arith-error nil)))
(defun cl-float-limits ()
"Initialize the Common Lisp floating-point parameters."
(or cl-most-positive-float (not (numberp '2e1))
(let ((x '2e0) y z)
(while (cl--finite-do '* x x) (setq x (* x x)))
(while (cl--finite-do '* x (/ x 2)) (setq x (* x (/ x 2))))
(while (cl--finite-do '+ x x) (setq x (+ x x)))
(setq z x y (/ x 2))
(while (and (cl--finite-do '+ x y) (/= (+ x y) x))
(setq x (+ x y) y (/ y 2)))
(setq cl-most-positive-float x
cl-most-negative-float (- x))
(setq x (/ x z) y (/ 16 z) x (* x y))
(while (condition-case _ (and (= x (* (/ x 2) 2)) (> (/ y 2) 0))
(arith-error nil))
(setq x (/ x 2) y (/ y 2)))
(setq cl-least-positive-normalized-float y
cl-least-negative-normalized-float (- y))
(setq x (/ z) y x)
(while (condition-case _ (> (/ x 2) 0) (arith-error nil))
(setq x (/ x 2)))
(setq cl-least-positive-float x
cl-least-negative-float (- x))
(setq x '1e0)
(while (/= (+ '1e0 x) '1e0) (setq x (/ x 2)))
(setq cl-float-epsilon (* x 2))
(setq x '1e0)
(while (/= (- '1e0 x) '1e0) (setq x (/ x 2)))
(setq cl-float-negative-epsilon (* x 2))))
nil)
(define-obsolete-function-alias 'cl-floatp-safe 'floatp "24.4")
;; subr.el: KEY is present even when its value is nil.
(let ((missing (make-symbol "missing")))
(defun hash-table-contains-p (key table)
"Return non-nil if TABLE has an element with KEY."
(not (eq (gethash key table missing) missing))))
;; cl-extra.el; `terpri''s ENSURE does the bolp test.
(defun cl-fresh-line (&optional stream)
"Output a newline unless already at the beginning of a line."
(terpri stream 'ensure))
;; doc.c `documentation' / `documentation-property' and simple.el's
;; `function-documentation' (Emacs 31.1). There is no etc/DOC file, so a
;; primitive's docstring is nil.
(defun documentation-property (symbol prop &optional raw)
(let ((tem (get symbol prop)))
(if (and (null tem) (eq prop 'variable-documentation)
(not (eq symbol (indirect-variable symbol))))
(documentation-property (indirect-variable symbol) prop raw)
(when (eql tem 0) (setq tem nil))
(unless (stringp tem) (setq tem (eval tem nil)))
(if (and (null raw) (stringp tem)) (substitute-command-keys tem) tem))))
(defun function-documentation (function)
(cond
((closurep function)
(when (> (length function) 4)
(let ((doc (aref function 4)))
(when (or (stringp doc) (fixnump doc) (fixnump (cdr-safe doc))) doc))))
((or (stringp function) (vectorp function)) "Keyboard macro.")
((eq (car-safe function) 'keymap)
"Prefix command (definition is a keymap associating keystrokes with commands).")
((memq (car-safe function) '(lambda autoload))
(let ((doc (car (cdr (cdr function)))))
(when (or (stringp doc) (fixnump doc) (fixnump (cdr-safe doc))) doc)))
((symbolp function)
(let ((f (indirect-function function)))
(if f (function-documentation f)
(signal 'void-function (list function)))))
((eq (car-safe function) 'macro) (function-documentation (cdr function)))
;; elisprs holds a defmacro's `(macro . FN)' as FN's closure flagged as a
;; macro: `car-safe' does not open it and `closurep' rejects it, but its
;; docstring slot is FN's.
((and (not (symbolp function)) (macrop function))
(when (> (length function) 4)
(let ((doc (aref function 4)))
(when (or (stringp doc) (fixnump doc) (fixnump (cdr-safe doc))) doc))))
((subrp function) nil)
(t (signal 'invalid-function (list function)))))
(defun documentation (function &optional raw)
(if (and (symbolp function) (get function 'function-documentation))
(documentation-property function 'function-documentation raw)
(let ((fun (indirect-function function)))
(unless fun (signal 'void-function (list function)))
(when (eq (car-safe fun) 'macro) (setq fun (cdr fun)))
(let ((doc (function-documentation fun)))
(if (eql doc 0) (setq doc nil))
(if raw doc (substitute-command-keys doc))))))
;; The per-buffer variables of buffer.c (`DEFVAR_PER_BUFFER') and the C
;; variables Emacs makes automatically buffer-local at startup, as GNU Emacs
;; 31.1 `emacs -Q --batch' has them: every one is bound, and setting one in a
;; buffer gives that buffer its own value instead of changing every buffer's.
;; Defaults are the measured `default-value's; `mode-line-format' holds
;; bindings.el's construct (whose parts are not defined: nothing displays it).
;; Left out: `lexical-binding' (rebound by `load'); `enable-multibyte-characters'
;; is one of the always-local slots below, and only `set-buffer-multibyte' sets it.
(dolist (var '(case-fold-search case-symbols-as-words deactivate-mark
multibyte-syntax-as-symbol parse-sexp-ignore-comments
parse-sexp-lookup-properties show-trailing-whitespace tab-width))
(make-variable-buffer-local var))
(defvar-local abbrev-mode nil)
(defvar-local auto-composition-function 'auto-compose-chars)
(defvar-local auto-composition-mode t)
(defvar-local auto-fill-function nil)
(defvar-local bidi-display-reordering t)
(defvar-local bidi-paragraph-separate-re nil)
(defvar-local bidi-paragraph-start-re nil)
(defvar-local buffer-auto-save-file-format t)
(defvar-local buffer-auto-save-file-name nil)
(defvar-local buffer-backed-up nil)
(defvar-local buffer-display-count 0)
(defvar-local buffer-display-table nil)
(defvar-local buffer-display-time nil)
(defvar-local buffer-file-coding-system 'utf-8-unix)
(defvar-local buffer-file-format nil)
(defvar-local buffer-file-name nil)
(defvar-local buffer-file-truename nil)
(defvar-local buffer-invisibility-spec t)
(defvar-local buffer-saved-size 0)
(defvar-local cache-long-scans t)
(defvar-local ctl-arrow t)
(defvar-local cursor-in-non-selected-windows t)
(defvar-local cursor-type t)
(defvar-local display-fill-column-indicator nil)
(defvar-local display-fill-column-indicator-character nil)
(defvar-local display-fill-column-indicator-column t)
(defvar-local display-line-numbers nil)
(defvar-local display-line-numbers-offset 0)
(defvar-local display-line-numbers-widen nil)
(defvar-local display-line-numbers-width nil)
(defvar-local expose-hidden-buffer nil)
(defvar-local fill-column 70)
(defvar-local fontification-functions nil)
(defvar-local fringe-cursor-alist nil)
(defvar-local fringe-indicator-alist nil)
(defvar-local fringes-outside-margins nil)
(defvar-local header-line-format nil)
(defvar-local horizontal-scroll-bar t)
(defvar-local indicate-buffer-boundaries nil)
(defvar-local indicate-empty-lines nil)
(defvar-local left-fringe-width nil)
(defvar-local left-margin 0)
(defvar-local left-margin-width 0)
(defvar-local line-prefix nil)
(defvar-local line-spacing nil)
(defvar-local make-window-start-visible nil)
(defvar-local mode-line-format
'("%e" mode-line-front-space mode-line-mule-info mode-line-client
mode-line-modified mode-line-remote mode-line-window-dedicated
mode-line-frame-identification mode-line-buffer-identification " "
mode-line-position (project-mode-line project-mode-line-format)
(vc-mode vc-mode) " " mode-line-modes mode-line-misc-info
mode-line-end-spaces))
(defvar-local mark-active nil)
(defvar-local minor-mode-overriding-map-alist nil)
(defvar-local overwrite-mode nil)
(defvar-local point-before-scroll nil)
(defvar-local post-command-hook nil)
(defvar-local pre-command-hook nil)
(defvar-local right-fringe-width nil)
(defvar-local right-margin-width 0)
(defvar-local scroll-bar-height nil)
(defvar-local scroll-bar-width nil)
(defvar-local scroll-down-aggressively nil)
(defvar-local scroll-up-aggressively nil)
(defvar-local selective-display nil)
(defvar-local selective-display-ellipses t)
(defvar-local tab-line-format nil)
(defvar-local text-conversion-style nil)
(defvar-local text-property-default-nonsticky '((composition . t) (syntax-table . t) (display . t)))
(defvar-local treesit-language-remap-alist nil)
(defvar-local vertical-scroll-bar t)
(defvar-local word-wrap nil)
(defvar-local wrap-prefix nil)
;; The always-local slots: `buffer_local_flags' is -1 for these in buffer.c
;; `init_buffer_once', so every buffer has its own value from birth
;; (`local-variable-p' is t in a fresh buffer) and `kill-local-variable' keeps
;; it. The second element is what a new buffer starts with: `reset_buffer' /
;; `reset_buffer_local_variables' store constants, `default-directory' is the
;; creating buffer's, and `buffer-undo-list' is t only in a buffer whose name
;; starts with a space (`Fget_buffer_create').
(dolist (slot '((buffer-file-name nil) (buffer-file-truename nil)
(default-directory :inherit) (buffer-backed-up nil)
(buffer-saved-size 0) (buffer-auto-save-file-name nil)
(buffer-read-only nil) (major-mode fundamental-mode)
(local-minor-modes nil) (mode-name "Fundamental")
(buffer-undo-list :undo-list) (mark-active nil)
(point-before-scroll nil) (buffer-invisibility-spec t)
(buffer-file-format nil) (buffer-auto-save-file-format t)
(buffer-display-count 0) (buffer-display-time nil)
(enable-multibyte-characters t)))
(--make-always-local-- (car slot) (cadr slot)))
;; The startup buffers now hold the working directory; the default, which only
;; `default-value' sees, is nil as in Emacs.
(setq-default default-directory nil)
;; lisp-mode.el (preloaded): the docstring positions and indentation of the
;; definers and special forms, which have no `declare' of their own.
(put 'autoload 'doc-string-elt 3)
(put 'defmethod 'doc-string-elt 3)
(put 'defvar 'doc-string-elt 3)
(put 'defconst 'doc-string-elt 3)
(put 'defalias 'doc-string-elt 3)
(put 'defvaralias 'doc-string-elt 3)
(put 'define-category 'doc-string-elt 2)
(put 'defconstant 'doc-string-elt 3)
(put 'define-compiler-macro 'doc-string-elt 3)
(put 'define-setf-expander 'doc-string-elt 3)
(put 'defparameter 'doc-string-elt 3)
(put 'defstruct 'doc-string-elt 2)
(put 'deftype 'doc-string-elt 3)
(put 'autoload 'lisp-indent-function 'defun) ;Elisp
(put 'progn 'lisp-indent-function 0)
(put 'defvar 'lisp-indent-function 'defun)
(put 'defalias 'lisp-indent-function 'defun)
(put 'defvaralias 'lisp-indent-function 'defun)
(put 'defconst 'lisp-indent-function 'defun)
(put 'define-category 'lisp-indent-function 'defun)
(put 'define-charset-internal 'lisp-indent-function 'defun)
(put 'define-fringe-bitmap 'lisp-indent-function 'defun)
(put 'prog1 'lisp-indent-function 1)
(put 'save-excursion 'lisp-indent-function 0) ;Elisp
(put 'save-restriction 'lisp-indent-function 0) ;Elisp
(put 'save-current-buffer 'lisp-indent-function 0) ;Elisp
(put 'let 'lisp-indent-function 1)
(put 'let* 'lisp-indent-function 1)
(put 'while 'lisp-indent-function 1)
(put 'if 'lisp-indent-function 2)
(put 'catch 'lisp-indent-function 1)
(put 'condition-case 'lisp-indent-function 2)
(put 'handler-case 'lisp-indent-function 1) ;CL
(put 'unwind-protect 'lisp-indent-function 1)
"#;
pub const NADVICE: &str = r##"
(oclosure-define (advice
(:predicate advice--p)
(:copier advice--cons (cdr))
(:copier advice--copy (car cdr how props)))
car cdr how props)
;; advice--how-alist maps each HOW keyword to a prototype `advice' oclosure whose
;; body combines the added FUNCTION (`car') with the previous definition (`cdr').
(eval-when-compile
(defmacro advice--make-how-alist (&rest args)
`(list
,@(mapcar
(lambda (arg)
(pcase-let ((`(,how . ,body) arg))
`(list ,how
(oclosure-lambda (advice (how ,how)) (&rest r)
,@body))))
args))))
(defvar advice--how-alist
(advice--make-how-alist
(:around (apply car cdr r))
(:before (apply car r) (apply cdr r))
(:after (prog1 (apply cdr r) (apply car r)))
(:override (apply car r))
(:after-until (or (apply cdr r) (apply car r)))
(:after-while (and (apply cdr r) (apply car r)))
(:before-until (or (apply car r) (apply cdr r)))
(:before-while (and (apply car r) (apply cdr r)))
(:filter-args (apply cdr (funcall car r)))
(:filter-return (funcall car (apply cdr r))))
"List of descriptions of how to add a function.
Each element has the form (HOW OCL) where HOW is a keyword and OCL is a
\"prototype\" function of type `advice'.")
(defun advice--cd*r (f)
(while (advice--p f)
(setq f (advice--cdr f)))
f)
(defun advice--make (how function main props)
"Build a function value that adds FUNCTION to MAIN at HOW.
HOW is a symbol to select an entry in `advice--how-alist'."
(let ((fd (or (cdr (assq 'depth props)) 0))
(md (if (advice--p main)
(or (cdr (assq 'depth (advice--props main))) 0))))
(if (and md (> fd md))
;; `function' should go deeper.
(let ((rest (advice--make how function (advice--cdr main) props)))
(advice--cons main rest))
(let ((proto (assq how advice--how-alist)))
(unless proto (error "Unknown add-function location `%S'" how))
(advice--copy (cadr proto)
function main how props)))))
(defun advice--member-p (function use-name definition)
(let ((found nil))
(while (and (not found) (advice--p definition))
(if (if (eq use-name :use-both)
(or (equal function
(cdr (assq 'name (advice--props definition))))
(equal function (advice--car definition)))
(equal function (if use-name
(cdr (assq 'name (advice--props definition)))
(advice--car definition))))
(setq found definition)
(setq definition (advice--cdr definition))))
found))
(defun advice--tweak (flist tweaker)
(if (not (advice--p flist))
(funcall tweaker nil flist nil)
(let ((first (advice--car flist))
(rest (advice--cdr flist))
(props (advice--props flist)))
(let ((val (funcall tweaker first rest props)))
(if val (car val)
(let ((nrest (advice--tweak rest tweaker)))
(if (eq rest nrest) flist
(advice--cons flist nrest))))))))
(defun advice--remove-function (flist function)
(advice--tweak flist
(lambda (first rest props)
(cond ((not first) rest)
((or (equal function first)
(equal function (cdr (assq 'name props))))
(list (advice--remove-function rest function)))))))
(eval-and-compile
(defun advice--normalize-place (place)
(cond ((eq 'local (car-safe place))
(error "Buffer-local advice places are unsupported"))
((eq 'var (car-safe place)) (nth 1 place))
((symbolp place) `(default-value ',place))
(t place))))
(defmacro add-function (how place function &optional props)
"Add a piece of advice on the function stored at PLACE.
FUNCTION describes the code to add. HOW describes how to add it (see
`advice--how-alist'). PROPS is an alist; `name' and `depth' are special."
(declare
(debug (form [&or symbolp ("local" form) ("var" sexp) gv-place]
form &optional form)))
`(advice--add-function ,how (gv-ref ,(advice--normalize-place place))
,function ,props))
(defun advice--add-function (how ref function props)
(let* ((name (cdr (assq 'name props)))
(a (advice--member-p (or name function) (if name t) (gv-deref ref))))
(when a
;; The advice is already present. Remove the old one, first.
(setf (gv-deref ref)
(advice--remove-function (gv-deref ref)
(or name (advice--car a)))))
(setf (gv-deref ref)
(advice--make how function (gv-deref ref) props))))
(defmacro remove-function (place function)
"Remove the FUNCTION piece of advice from PLACE.
If FUNCTION was not added to PLACE, do nothing. FUNCTION can also be the
`name' of the piece of advice."
(declare (debug ([&or symbolp ("local" form) ("var" sexp) gv-place]
form)))
(gv-letplace (getter setter) (advice--normalize-place place)
(macroexp-let2 nil new `(advice--remove-function ,getter ,function)
`(unless (eq ,new ,getter) ,(funcall setter new)))))
(defun advice-function-mapc (f function-def)
"Apply F to every advice function in FUNCTION-DEF.
F is called with two arguments: the added function and its props alist."
(while (advice--p function-def)
(funcall f (advice--car function-def) (advice--props function-def))
(setq function-def (advice--cdr function-def))))
(defun advice-function-member-p (advice function-def)
"Return non-nil if ADVICE is already in FUNCTION-DEF.
ADVICE can also be the `name' of the piece of advice."
(advice--member-p advice :use-both function-def))
;;;; Specific application of add-function to `symbol-function' for advice.
(defun advice--subst-main (old new)
(advice--tweak old
(lambda (first _rest _props) (if (not first) new))))
(defun advice--normalize (symbol def)
(cond
((special-form-p def)
(error "Advice impossible: %S is a special form" symbol))
((and (symbolp def) (macrop def))
(let ((newval `(macro . ,(lambda (&rest r) (macroexpand `(,def . ,r))))))
(put symbol 'advice--saved-rewrite (cons def (cdr newval)))
newval))
;; `f' might be a pure (hence read-only) cons!
((and (eq 'macro (car-safe def))
(not (ignore-errors (setcdr def (cdr def)) t)))
(cons 'macro (cdr def)))
(t def)))
(defsubst advice--strip-macro (x)
(if (eq 'macro (car-safe x)) (cdr x) x))
(defun advice--symbol-function (symbol)
;; Conceptually the symbol-function is split into the plain definition plus the
;; list of advice; this returns the advice part (or the pending advice stashed
;; on `advice--pending' while the definition is nil/an autoload).
(or (get symbol 'advice--pending)
(advice--strip-macro (symbol-function symbol))))
(defun advice--defalias-fset (fsetfun symbol newdef)
(unless fsetfun (setq fsetfun #'fset))
;; `newdef' shouldn't include advice wrappers, since that's what *we* manage.
(cond
((advice--p newdef) (setq newdef (advice--cd*r newdef)))
((and (eq 'macro (car-safe newdef))
(advice--p (cdr newdef)))
(setq newdef `(macro . ,(advice--cd*r (cdr newdef))))))
(when (get symbol 'advice--saved-rewrite)
(put symbol 'advice--saved-rewrite nil))
(setq newdef (advice--normalize symbol newdef))
(let ((oldadv (advice--symbol-function symbol)))
(if (and newdef (not (autoloadp newdef)))
(let* ((snewdef (advice--strip-macro newdef))
(snewadv (advice--subst-main oldadv snewdef)))
(put symbol 'advice--pending nil)
(funcall fsetfun symbol
(if (eq snewdef newdef) snewadv (cons 'macro snewadv))))
(unless (eq oldadv (get symbol 'advice--pending))
(put symbol 'advice--pending (advice--subst-main oldadv nil)))
(funcall fsetfun symbol newdef))))
(defun advice-add (symbol how function &optional props)
"Like `add-function' but for the function named SYMBOL.
Handles the cases where SYMBOL is defined as a macro, alias, command, ..."
(let* ((f (symbol-function symbol))
(nf (advice--normalize symbol f)))
(unless (eq f nf) (fset symbol nf))
(add-function how (cond
((eq (car-safe nf) 'macro) (cdr nf))
((or (not nf) (autoloadp nf))
(get symbol 'advice--pending))
(t (symbol-function symbol)))
function props)
(add-function :around (get symbol 'defalias-fset-function)
#'advice--defalias-fset))
nil)
(defun advice-remove (symbol function)
"Like `remove-function' but for the function named SYMBOL.
Works when SYMBOL is a macro or an autoload and preserves `fboundp'.
FUNCTION can also be the `name' of the piece of advice."
(let ((f (symbol-function symbol)))
(remove-function (cond ;This is `advice--symbol-function' but as a "place".
((get symbol 'advice--pending)
(get symbol 'advice--pending))
((eq (car-safe f) 'macro) (cdr f))
(t (symbol-function symbol)))
function)
(unless (advice--p (advice--symbol-function symbol))
(remove-function (get symbol 'defalias-fset-function)
#'advice--defalias-fset)
(let ((asr (get symbol 'advice--saved-rewrite)))
(and asr (eq (cdr-safe (symbol-function symbol))
(cdr asr))
(fset symbol (car (get symbol 'advice--saved-rewrite)))))))
nil)
(defmacro define-advice (symbol args &rest body)
"Define an advice and add it to function named SYMBOL.
See `advice-add' and `add-function'. If NAME is non-nil, the advice is
named `SYMBOL@NAME' and installed with the name NAME; else it is anonymous.
\(fn SYMBOL (HOW LAMBDA-LIST &optional NAME DEPTH) &rest BODY)"
(declare (indent 2) (doc-string 3) (debug (sexp sexp def-body)))
(or (listp args) (signal 'wrong-type-argument (list 'listp args)))
(or (<= 2 (length args) 4)
(signal 'wrong-number-of-arguments (list 2 4 (length args))))
(let* ((how (nth 0 args))
(lambda-list (nth 1 args))
(name (nth 2 args))
(depth (nth 3 args))
(props (append
(and depth `((depth . ,depth)))
(and name `((name . ,name)))))
(advice (cond ((null name) `(lambda ,lambda-list ,@body))
((or (stringp name) (symbolp name))
(intern (format "%s@%s" symbol name)))
(t (error "Unrecognized name spec `%S'" name)))))
`(prog1 ,@(and (symbolp advice) `((defun ,advice ,lambda-list ,@body)))
(advice-add ',symbol ,how #',advice ,@(and props `(',props))))))
(defun advice-mapc (fun symbol)
"Apply FUN to every advice function in SYMBOL.
FUN is called with two arguments: the added function and its props alist."
(advice-function-mapc fun (advice--symbol-function symbol)))
(defun advice-member-p (advice symbol)
"Return non-nil if ADVICE has been added to SYMBOL.
ADVICE can also be the `name' of the piece of advice."
(advice-function-member-p advice (advice--symbol-function symbol)))
(provide 'nadvice)
"##;