Attempt to make defclass documentation more legible
[emacs.git] / lisp / emacs-lisp / subr-x.el
blob468d124c0e292823a3d4bffa92ae29110ce4791d
1 ;;; subr-x.el --- extra Lisp functions -*- lexical-binding:t -*-
3 ;; Copyright (C) 2013-2021 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: convenience
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Less commonly used functions that complement basic APIs, often implemented in
27 ;; C code (like hash-tables and strings), and are not eligible for inclusion
28 ;; in subr.el.
30 ;; Do not document these functions in the lispref.
31 ;; https://lists.gnu.org/r/emacs-devel/2014-01/msg01006.html
33 ;; NB If you want to use this library, it's almost always correct to use:
34 ;; (eval-when-compile (require 'subr-x))
36 ;;; Code:
38 (eval-when-compile (require 'cl-lib))
41 (defmacro internal--thread-argument (first? &rest forms)
42 "Internal implementation for `thread-first' and `thread-last'.
43 When Argument FIRST? is non-nil argument is threaded first, else
44 last. FORMS are the expressions to be threaded."
45 (pcase forms
46 (`(,x (,f . ,args) . ,rest)
47 `(internal--thread-argument
48 ,first? ,(if first? `(,f ,x ,@args) `(,f ,@args ,x)) ,@rest))
49 (`(,x ,f . ,rest) `(internal--thread-argument ,first? (,f ,x) ,@rest))
50 (_ (car forms))))
52 (defmacro thread-first (&rest forms)
53 "Thread FORMS elements as the first argument of their successor.
54 Example:
55 (thread-first
57 (+ 20)
58 (/ 25)
60 (+ 40))
61 Is equivalent to:
62 (+ (- (/ (+ 5 20) 25)) 40)
63 Note how the single `-' got converted into a list before
64 threading."
65 (declare (indent 1)
66 (debug (form &rest [&or symbolp (sexp &rest form)])))
67 `(internal--thread-argument t ,@forms))
69 (defmacro thread-last (&rest forms)
70 "Thread FORMS elements as the last argument of their successor.
71 Example:
72 (thread-last
74 (+ 20)
75 (/ 25)
77 (+ 40))
78 Is equivalent to:
79 (+ 40 (- (/ 25 (+ 20 5))))
80 Note how the single `-' got converted into a list before
81 threading."
82 (declare (indent 1) (debug thread-first))
83 `(internal--thread-argument nil ,@forms))
85 (defsubst internal--listify (elt)
86 "Wrap ELT in a list if it is not one.
87 If ELT is of the form ((EXPR)), listify (EXPR) with a dummy symbol."
88 (cond
89 ((symbolp elt) (list elt elt))
90 ((null (cdr elt))
91 (list (make-symbol "s") (car elt)))
92 (t elt)))
94 (defsubst internal--check-binding (binding)
95 "Check BINDING is properly formed."
96 (when (> (length binding) 2)
97 (signal
98 'error
99 (cons "`let' bindings can have only one value-form" binding)))
100 binding)
102 (defsubst internal--build-binding-value-form (binding prev-var)
103 "Build the conditional value form for BINDING using PREV-VAR."
104 (let ((var (car binding)))
105 `(,var (and ,prev-var ,(cadr binding)))))
107 (defun internal--build-binding (binding prev-var)
108 "Check and build a single BINDING with PREV-VAR."
109 (thread-first
110 binding
111 internal--listify
112 internal--check-binding
113 (internal--build-binding-value-form prev-var)))
115 (defun internal--build-bindings (bindings)
116 "Check and build conditional value forms for BINDINGS."
117 (let ((prev-var t))
118 (mapcar (lambda (binding)
119 (let ((binding (internal--build-binding binding prev-var)))
120 (setq prev-var (car binding))
121 binding))
122 bindings)))
124 (defmacro if-let* (varlist then &rest else)
125 "Bind variables according to VARLIST and evaluate THEN or ELSE.
126 This is like `if-let' but doesn't handle a VARLIST of the form
127 \(SYMBOL SOMETHING) specially."
128 (declare (indent 2)
129 (debug ((&rest [&or symbolp (symbolp form) (form)])
130 body)))
131 (if varlist
132 `(let* ,(setq varlist (internal--build-bindings varlist))
133 (if ,(caar (last varlist))
134 ,then
135 ,@else))
136 `(let* () ,then)))
138 (defmacro when-let* (varlist &rest body)
139 "Bind variables according to VARLIST and conditionally evaluate BODY.
140 This is like `when-let' but doesn't handle a VARLIST of the form
141 \(SYMBOL SOMETHING) specially."
142 (declare (indent 1) (debug if-let*))
143 (list 'if-let* varlist (macroexp-progn body)))
145 (defmacro and-let* (varlist &rest body)
146 "Bind variables according to VARLIST and conditionally evaluate BODY.
147 Like `when-let*', except if BODY is empty and all the bindings
148 are non-nil, then the result is non-nil."
149 (declare (indent 1) (debug if-let*))
150 (let (res)
151 (if varlist
152 `(let* ,(setq varlist (internal--build-bindings varlist))
153 (when ,(setq res (caar (last varlist)))
154 ,@(or body `(,res))))
155 `(let* () ,@(or body '(t))))))
157 ;;;###autoload
158 (defmacro if-let (spec then &rest else)
159 "Bind variables according to SPEC and evaluate THEN or ELSE.
160 Evaluate each binding in turn, as in `let*', stopping if a
161 binding value is nil. If all are non-nil return the value of
162 THEN, otherwise the last form in ELSE.
164 Each element of SPEC is a list (SYMBOL VALUEFORM) that binds
165 SYMBOL to the value of VALUEFORM. An element can additionally be
166 of the form (VALUEFORM), which is evaluated and checked for nil;
167 i.e. SYMBOL can be omitted if only the test result is of
168 interest. It can also be of the form SYMBOL, then the binding of
169 SYMBOL is checked for nil.
171 As a special case, interprets a SPEC of the form \(SYMBOL SOMETHING)
172 like \((SYMBOL SOMETHING)). This exists for backward compatibility
173 with an old syntax that accepted only one binding."
174 (declare (indent 2)
175 (debug ([&or (symbolp form) ; must be first, Bug#48489
176 (&rest [&or symbolp (symbolp form) (form)])]
177 body)))
178 (when (and (<= (length spec) 2)
179 (not (listp (car spec))))
180 ;; Adjust the single binding case
181 (setq spec (list spec)))
182 (list 'if-let* spec then (macroexp-progn else)))
184 ;;;###autoload
185 (defmacro when-let (spec &rest body)
186 "Bind variables according to SPEC and conditionally evaluate BODY.
187 Evaluate each binding in turn, stopping if a binding value is nil.
188 If all are non-nil, return the value of the last form in BODY.
190 The variable list SPEC is the same as in `if-let'."
191 (declare (indent 1) (debug if-let))
192 (list 'if-let spec (macroexp-progn body)))
194 (defsubst hash-table-empty-p (hash-table)
195 "Check whether HASH-TABLE is empty (has 0 elements)."
196 (zerop (hash-table-count hash-table)))
198 (defsubst hash-table-keys (hash-table)
199 "Return a list of keys in HASH-TABLE."
200 (cl-loop for k being the hash-keys of hash-table collect k))
202 (defsubst hash-table-values (hash-table)
203 "Return a list of values in HASH-TABLE."
204 (cl-loop for v being the hash-values of hash-table collect v))
206 (defsubst string-empty-p (string)
207 "Check whether STRING is empty."
208 (string= string ""))
210 (defsubst string-join (strings &optional separator)
211 "Join all STRINGS using SEPARATOR."
212 (mapconcat #'identity strings separator))
214 (define-obsolete-function-alias 'string-reverse 'reverse "25.1")
216 ;;;###autoload
217 (defun string-truncate-left (string length)
218 "Truncate STRING to LENGTH, replacing initial surplus with \"...\"."
219 (let ((strlen (length string)))
220 (if (<= strlen length)
221 string
222 (setq length (max 0 (- length 3)))
223 (concat "..." (substring string (max 0 (- strlen 1 length)))))))
225 (defsubst string-blank-p (string)
226 "Check whether STRING is either empty or only whitespace.
227 The following characters count as whitespace here: space, tab, newline and
228 carriage return."
229 (string-match-p "\\`[ \t\n\r]*\\'" string))
231 (defsubst string-remove-prefix (prefix string)
232 "Remove PREFIX from STRING if present."
233 (if (string-prefix-p prefix string)
234 (substring string (length prefix))
235 string))
237 (defsubst string-remove-suffix (suffix string)
238 "Remove SUFFIX from STRING if present."
239 (if (string-suffix-p suffix string)
240 (substring string 0 (- (length string) (length suffix)))
241 string))
243 (defun string-clean-whitespace (string)
244 "Clean up whitespace in STRING.
245 All sequences of whitespaces in STRING are collapsed into a
246 single space character, and leading/trailing whitespace is
247 removed."
248 (let ((blank "[[:blank:]\r\n]+"))
249 (string-trim (replace-regexp-in-string blank " " string t t)
250 blank blank)))
252 (defun string-fill (string length)
253 "Try to word-wrap STRING so that no lines are longer than LENGTH.
254 Wrapping is done where there is whitespace. If there are
255 individual words in STRING that are longer than LENGTH, the
256 result will have lines that are longer than LENGTH."
257 (with-temp-buffer
258 (insert string)
259 (goto-char (point-min))
260 (let ((fill-column length)
261 (adaptive-fill-mode nil))
262 (fill-region (point-min) (point-max)))
263 (buffer-string)))
265 (defun string-limit (string length &optional end coding-system)
266 "Return (up to) a LENGTH substring of STRING.
267 If STRING is shorter than or equal to LENGTH, the entire string
268 is returned unchanged.
270 If STRING is longer than LENGTH, return a substring consisting of
271 the first LENGTH characters of STRING. If END is non-nil, return
272 the last LENGTH characters instead.
274 If CODING-SYSTEM is non-nil, STRING will be encoded before
275 limiting, and LENGTH is interpreted as the number of bytes to
276 limit the string to. The result will be a unibyte string that is
277 shorter than LENGTH, but will not contain \"partial\" characters,
278 even if CODING-SYSTEM encodes characters with several bytes per
279 character.
281 When shortening strings for display purposes,
282 `truncate-string-to-width' is almost always a better alternative
283 than this function."
284 (unless (natnump length)
285 (signal 'wrong-type-argument (list 'natnump length)))
286 (if coding-system
287 (let ((result nil)
288 (result-length 0)
289 (index (if end (1- (length string)) 0)))
290 ;; FIXME: This implementation, which uses encode-coding-char
291 ;; to encode the string one character at a time, is in general
292 ;; incorrect: coding-systems that produce prefix or suffix
293 ;; bytes, such as ISO-2022-based or UTF-8/16 with BOM, will
294 ;; produce those bytes for each character, instead of just
295 ;; once for the entire string. encode-coding-char attempts to
296 ;; remove those extra bytes at least in some situations, but
297 ;; it cannot do that in all cases. And in any case, producing
298 ;; what is supposed to be a UTF-16 or ISO-2022-CN encoded
299 ;; string which lacks the BOM bytes at the beginning and the
300 ;; charset designation sequences at the head and tail of the
301 ;; result will definitely surprise the callers in some cases.
302 (while (let ((encoded (encode-coding-char
303 (aref string index) coding-system)))
304 (and (<= (+ (length encoded) result-length) length)
305 (progn
306 (push encoded result)
307 (cl-incf result-length (length encoded))
308 (setq index (if end (1- index)
309 (1+ index))))
310 (if end (> index -1)
311 (< index (length string)))))
312 ;; No body.
314 (apply #'concat (if end result (nreverse result))))
315 (cond
316 ((<= (length string) length) string)
317 (end (substring string (- (length string) length)))
318 (t (substring string 0 length)))))
320 ;;;###autoload
321 (defun string-lines (string &optional omit-nulls)
322 "Split STRING into a list of lines.
323 If OMIT-NULLS, empty lines will be removed from the results."
324 (split-string string "\n" omit-nulls))
326 (defun string-pad (string length &optional padding start)
327 "Pad STRING to LENGTH using PADDING.
328 If PADDING is nil, the space character is used. If not nil, it
329 should be a character.
331 If STRING is longer than the absolute value of LENGTH, no padding
332 is done.
334 If START is nil (or not present), the padding is done to the end
335 of the string, and if non-nil, padding is done to the start of
336 the string."
337 (unless (natnump length)
338 (signal 'wrong-type-argument (list 'natnump length)))
339 (let ((pad-length (- length (length string))))
340 (if (< pad-length 0)
341 string
342 (concat (and start
343 (make-string pad-length (or padding ?\s)))
344 string
345 (and (not start)
346 (make-string pad-length (or padding ?\s)))))))
348 (defun string-chop-newline (string)
349 "Remove the final newline (if any) from STRING."
350 (string-remove-suffix "\n" string))
352 (defun replace-region-contents (beg end replace-fn
353 &optional max-secs max-costs)
354 "Replace the region between BEG and END using REPLACE-FN.
355 REPLACE-FN runs on the current buffer narrowed to the region. It
356 should return either a string or a buffer replacing the region.
358 The replacement is performed using `replace-buffer-contents'
359 which also describes the MAX-SECS and MAX-COSTS arguments and the
360 return value.
362 Note: If the replacement is a string, it'll be placed in a
363 temporary buffer so that `replace-buffer-contents' can operate on
364 it. Therefore, if you already have the replacement in a buffer,
365 it makes no sense to convert it to a string using
366 `buffer-substring' or similar."
367 (save-excursion
368 (save-restriction
369 (narrow-to-region beg end)
370 (goto-char (point-min))
371 (let ((repl (funcall replace-fn)))
372 (if (bufferp repl)
373 (replace-buffer-contents repl max-secs max-costs)
374 (let ((source-buffer (current-buffer)))
375 (with-temp-buffer
376 (insert repl)
377 (let ((tmp-buffer (current-buffer)))
378 (set-buffer source-buffer)
379 (replace-buffer-contents tmp-buffer max-secs max-costs)))))))))
381 (defmacro named-let (name bindings &rest body)
382 "Looping construct taken from Scheme.
383 Like `let', bind variables in BINDINGS and then evaluate BODY,
384 but with the twist that BODY can evaluate itself recursively by
385 calling NAME, where the arguments passed to NAME are used
386 as the new values of the bound variables in the recursive invocation."
387 (declare (indent 2) (debug (symbolp (&rest (symbolp form)) body)))
388 (require 'cl-lib)
389 (let ((fargs (mapcar (lambda (b) (if (consp b) (car b) b)) bindings))
390 (aargs (mapcar (lambda (b) (if (consp b) (cadr b))) bindings)))
391 ;; According to the Scheme semantics of named let, `name' is not in scope
392 ;; while evaluating the expressions in `bindings', and for this reason, the
393 ;; "initial" function call below needs to be outside of the `cl-labels'.
394 ;; When the "self-tco" eliminates all recursive calls, the `cl-labels'
395 ;; expands to a lambda which the byte-compiler then combines with the
396 ;; funcall to make a `let' so we end up with a plain `while' loop and no
397 ;; remaining `lambda' at all.
398 `(funcall
399 (cl-labels ((,name ,fargs . ,body)) #',name)
400 . ,aargs)))
403 (provide 'subr-x)
405 ;;; subr-x.el ends here