-
Notifications
You must be signed in to change notification settings - Fork 17
/
eldev-util.el
2641 lines (2294 loc) · 120 KB
/
eldev-util.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; eldev-util.el --- Elisp development tool -*- lexical-binding: t -*-
;;; Copyright (C) 2019-2024 Paul Pogonyshev
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see https://www.gnu.org/licenses.
;;; Commentary:
;; Utility and compatibility functions.
(require 'package)
;; Compatibility.
;; To silence byte-compilation warnings on Emacs 24-25.
(defvar inhibit-message)
(defvar byte-compile-log-warning-function)
(defun eldev-define-error (name message &optional parent)
"Same as `define-error', needed for compatibility."
(if (fboundp #'define-error)
(define-error name message parent)
(put name 'error-conditions `(,name ,(or parent 'error)))
(put name 'error-message message)))
(eval-and-compile
(if (fboundp 'xor)
(defalias 'eldev-xor 'xor
"Same as `xor', needed for compatibility.")
(defsubst eldev-xor (a b)
"Same as `xor', needed for compatibility."
(if a (not b) b)))
(if (macrop 'pcase-exhaustive)
(defalias 'eldev-pcase-exhaustive 'pcase-exhaustive
"Same as `pcase-exhaustive', needed for compatibility.")
(defmacro eldev-pcase-exhaustive (value &rest cases)
"Same as `pcase-exhaustive', needed for compatibility."
`(pcase ,value
,@cases
(value (error "No clause matching `%S'" value)))))
(if (fboundp 'macroexp-quote)
(defalias 'eldev-macroexp-quote 'macroexp-quote
"Same as `macroexp-quote', needed for compatibility.")
(defun eldev-macroexp-quote (v)
"Same as `macroexp-quote', needed for compatibility."
(if (and (not (consp v))
(or (keywordp v) (not (symbolp v)) (memq v '(nil t))))
v
(list 'quote v)))))
(defun eldev-macroexp-parse-body (body)
"Same as `macroexp-parse-body', needed for compatibility."
(let ((decls ()))
(while (and (cdr body)
(let ((e (car body)))
(or (stringp e)
(memq (car-safe e)
'(:documentation declare interactive cl-declare)))))
(push (pop body) decls))
(cons (nreverse decls) body)))
;; XDG support: native only in Emacs 26 and up.
(defmacro eldev--xdg-dir-home (environ default-path)
(declare (debug (stringp stringp)))
(let ((env (make-symbol "env")))
`(let ((,env (getenv ,environ)))
(if (or (null ,env) (not (file-name-absolute-p ,env)))
(expand-file-name ,default-path)
,env))))
(if (require 'xdg nil t)
(progn
(defalias 'eldev-xdg-config-home 'xdg-config-home)
(defalias 'eldev-xdg-cache-home 'xdg-cache-home))
(defun eldev-xdg-config-home ()
"Same as `xdg-config-home' in Emacs 26 and up.
Since Eldev 0.11."
(eldev--xdg-dir-home "XDG_CONFIG_HOME" "~/.config"))
(defun eldev-xdg-cache-home ()
"Same as `xdg-cache-home' in Emacs 26 and up.
Since Eldev 0.11."
(eldev--xdg-dir-home "XDG_CACHE_HOME" "~/.cache")))
;; This is rather for compatibility across shells, as Windows PowerShell has weird quote
;; escaping rules. Can be used as `(eldev--list-to-string '(foo bar baz))' and produces
;; "foo bar baz" without using quotes on the command line. Currently package-"private".
(defun eldev--list-to-string (list)
(mapconcat #'prin1-to-string list " "))
;; General.
(defvar eldev--running-from-dir nil)
;; Replacements for a small parts of `dash'.
(defmacro eldev-any-p (form list)
"Same as `--any' in Dash.
Used to avoid depending on the library."
(let ((values (make-symbol "$values"))
(result (make-symbol "$result")))
`(let ((,values ,list)
,result)
(while ,values
(let ((it (car ,values)))
(setf ,values (if ,form (progn (setf ,result t) nil) (cdr ,values)))))
,result)))
(defmacro eldev-all-p (form list)
"Same as `--all' in Dash.
Used to avoid depending on the library."
(let ((values (make-symbol "$values"))
(result (make-symbol "$result")))
`(let ((,values ,list)
(,result t))
(while ,values
(let ((it (car ,values)))
(setf ,values (if ,form (cdr ,values) (setf ,result nil)))))
,result)))
(defmacro eldev-filter (form list)
"Same as `--filter' in Dash.
Used to avoid depending on the library."
(let ((values (make-symbol "$values"))
(result (make-symbol "$result")))
`(let ((,values ,list)
,result)
(while ,values
(let ((it (pop ,values)))
(when ,form
(push it ,result))))
(nreverse ,result))))
(defmacro eldev-advised (spec &rest body)
"Execute BODY with given advice installed, then remove it.
Advice function can be nil, in which case it is simply ignored.
This can be used to execute BODY with an advice installed
conditionally.
\(fn (SYMBOL WHERE FUNCTION [PROPS]) BODY...)"
(declare (indent 1) (debug (sexp body)))
(let ((symbol (nth 0 spec))
(where (nth 1 spec))
(function (nth 2 spec))
(props (nthcdr 3 spec))
(fn (make-symbol "$fn")))
`(let ((,fn ,function))
(when ,fn
;; See test `eldev-advised-3' for an example why this is important.
(if (advice-member-p ,fn ,symbol)
(setf ,fn nil)
(advice-add ,symbol ,where ,fn ,@props)))
(unwind-protect
,(macroexp-progn body)
(when ,fn
(advice-remove ,symbol ,fn))))))
(defmacro eldev-with-kill-handler (function &rest body)
"Execute BODY with given FUNCTION on `kill-emacs-hook'.
The function can be nil, in which case it is simply ignored.
Since 1.2."
(declare (indent 1) (debug (sexp body)))
(let ((fn (make-symbol "$fn")))
`(let ((,fn ,function))
(when ,fn
(add-hook 'kill-emacs-hook ,fn))
(unwind-protect
,(macroexp-progn body)
(when ,fn
(remove-hook 'kill-emacs-hook ,fn))))))
(defsubst eldev-listify (x)
"Make a list out of X.
If X is already a list (including nil), it is returned
unmodified, else it is wrapped as a single-item list."
(if (listp x) x `(,x)))
(defun eldev-literalp (x)
"Return non-nil if X is a literal, possibly quoted.
Since Eldev 1.4."
(declare (pure t) (side-effect-free t))
(if (atom x)
(or (not (symbolp x))
(memq x '(nil t))
(keywordp x))
(and (memq (car x) '(quote function)) (consp (cdr x)) (null (cddr x)))))
(defun eldev-string-list-p (x)
"Determine if X is a list of strings."
(let ((result t))
(while x
(if (and (consp x) (stringp (car x)))
(setf x (cdr x))
(setf result nil
x nil)))
result))
(defun eldev-flatten-tree (tree)
"Like `flatten-tree' in newer Emacs versions.
Needed for compatibility."
(let (elems)
(while (consp tree)
(let ((elem (pop tree)))
(while (consp elem)
(push (cdr elem) tree)
(setq elem (car elem)))
(if elem (push elem elems))))
(if tree (push tree elems))
(nreverse elems)))
(eval-and-compile
(defmacro eldev--assq-set (key value place &optional comparator)
"Add or replace VALUE for given KEY in associated list at PLACE.
For Emacs 25+ this is the same as
(setf (alist-get key place nil nil comparator) value)
Only `eq' (also default) and `equal' are supported for COMPARATOR."
`(let* ((key ,key)
(value ,value)
;; Emacs 24 doesn't support arbitrary comparators.
(existing ,(eldev-pcase-exhaustive (or comparator #'eq)
((or `eq `(function eq)) `(assq key ,place))
((or `equal `(function equal)) `(assoc key ,place)))))
(if existing
(setf (cdr existing) value)
(push (cons key value) ,place)
value))))
(defun eldev-valid-regexp-p (regexp)
"Determine if REGEXP is valid.
Since 0.2."
(ignore-errors
;; `ignore' is only here to silence byte-compilation warning.
(ignore (string-match-p regexp ""))
t))
(defsubst eldev-get (symbol property)
"Similar to built-in `get', used to avoid accidental name clashes."
(plist-get (get symbol 'eldev--properties) property))
(defsubst eldev-put (symbol property value)
"Similar to built-in `put', used to avoid accidental name clashes."
(put symbol 'eldev--properties (plist-put (get symbol 'eldev--properties) property value)))
(defun eldev-getenv (variable &optional if-empty-or-not-set)
"Like `getenv', but with default value.
Note that it is impossible to tell an unset variable from one set
to an empty string with this function. Also lacks `frame'
parameter, but it's not needed in noninteractive use."
(let ((value (getenv variable)))
(if (> (length value) 0) value if-empty-or-not-set)))
(defun eldev-bat-quote (mode &optional string)
"Helper function to quote data in a batch file using Delayed
Expansion. The :init MODE result has to be inserted first in a
batch file to prepare the ground for the other MODEs to work.
Available MODEs:
:init
Returns the prolog required to support the rest of the quoting
modes. Basically this sets the ARGS variable to the batch
command line arguments, enables delayed expansion and creates
the NL variable containing the newline character.
:args
Returns the delayed expansion reference to the ARGS variable
which holds the command line arguments of the batch file.
:string
Returns the quoted STRING using delayed expansion tricks to
support multiline text."
(pcase mode
(`:init
(concat "set ARGS=%*\n"
"setlocal EnableDelayedExpansion\n"
"set NL= ^\n"
"\n\nREM the newline variable above MUST be followed by two empty lines."))
(`:args "!ARGS!")
(`:string
(with-temp-buffer
;; begin by opening a double quote while tricking the batch
;; reader to believe that the opening double quote has been
;; closed by using a delayed expansion to the non-existent
;; variable =" which includes a " in its name.
;;
;; Then open a new line and insert STRING.
(let ((start "\"!=\"!\n"))
(insert start string)
(goto-char (length start)))
;; escape any double quotes by tripling them.
(while (search-forward "\"" nil t)
(insert "\"\""))
;; close the quoted text with a double quote.
(goto-char (point-max))
(insert "\"")
;; escape special characters with ^
(goto-char (point-min))
(while (re-search-forward "&\\|<\\|>" nil t)
(replace-match "^\\&"))
;; escape % with %%
(goto-char (point-min))
(while (search-forward "%" nil t)
(replace-match "%%"))
;; replace any newlines with the delayed expansion of the NL
;; variable followed by the new line escape character ^.
;;
;; The ^ escapes newlines only visually, i.e. the recipient of
;; the quoted string will only see the quoted text as a single
;; line.
;;
;; The delayed expansion of the NL variable though will insert
;; a new line physically, which is the desired behavior when
;; the quoted line is a lisp program with comments in it, since
;; they need to be on dedicated lines.
(goto-char (point-min))
(while (search-forward "\n" nil t)
(replace-match " !NL!^\n"))
(buffer-substring-no-properties (point-min) (point-max))))))
(defun eldev-quote-sh-string (string &optional always-quote)
"Quote given STRING for use in a shell command.
Unlike standard `shell-quote-argument', this function uses single
quotes to improve readability in most cases.
If ALWAYS-QUOTE is not specified and STRING doesn't contain any
special characters, it is returned unmodified."
(if (and (not always-quote) (string-match-p "\\`[-a-zA-Z0-9,._+:@%/]+\\'" string))
;; No quoting necessary.
string
(with-temp-buffer
(insert "'" string)
(goto-char 2)
(while (search-forward "'" nil t)
(insert "\\''"))
(goto-char (point-max))
(insert "'")
(buffer-substring-no-properties (point-min) (point-max)))))
(defun eldev-replace-suffix (string old-suffix new-suffix)
"Replace suffix of given STRING (usually a filename).
If STRING doesn't even end in OLD-SUFFIX, it is returned
unmodified."
(if (string-suffix-p old-suffix string)
(concat (substring string 0 (- (length old-suffix))) new-suffix)
string))
(defsubst eldev-external-filename (filename)
"Determine if FILENAME specifies a path outside current directory.
This function doesn't handle absolute paths specially, so in most
cases you should use `eldev-external-or-absolute-filename'
instead. Remember that `file-relative-name' may return an
absolute path, when networking or Windows is involved."
(or (string= filename "..") (string-prefix-p "../" filename)))
(defsubst eldev-external-or-absolute-filename (filename)
"Determine if FILENAME specifies a path outside current directory.
Absolute paths are also considered to point outside."
(or (eldev-external-filename filename) (file-name-absolute-p filename)))
(defun eldev-environment-value (variable environment)
"Retrieve value of VARIABLE from alist ENVIRONMENT.
If there is no such value, fall back to the corresponding Lisp
variable, if it is bound.
This function is intended mostly for `let'-binding variables that
are not necessarily declared, e.g. because of older Emacs or
library version."
(let ((entry (assq variable environment)))
(if entry
(cdr entry)
(when (boundp variable)
(symbol-value variable)))))
(defmacro eldev-bind-from-environment (environment variables &rest body)
"Execute BODY with certain VARIABLES set from ENVIRONMENT.
ENVIRONMENT should be an alist (see `eldev-environment-value').
If no value for a variable is specified, current value is not
altered."
(declare (indent 2))
`(let (,@(mapcar (lambda (variable) `(,variable (eldev-environment-value ',variable ,environment))) variables))
,@body))
(defmacro eldev-with-errors-as (signal-type &rest body)
"Evaluate BODY, resignalling any errors using SIGNAL-TYPE.
Since 1.1.1."
(declare (indent 1) (debug (symbolp body)))
(let ((error (make-symbol "$error")))
`(condition-case ,error
,(macroexp-progn body)
(error (signal ,signal-type (cdr ,error))))))
(defun eldev--guess-url-from-file-error (error)
;; Another example of marvelous Elisp design. It is sometimes first (installing
;; packages from an HTTPS archive), sometimes last (installing from a local archive)...
(let ((data (cdr error))
url)
(while (and (null url) (consp data))
(let ((element (pop data)))
(when (and (stringp element) (string-match-p (rx (or "/" "\\")) element))
(setf url element))))
(or url (when (stringp (car-safe (cdr error))) (cadr error)))))
(defmacro eldev--lazy-scope (spec &rest body)
"Execute BODY with a named value set up for lazy evaluation.
Evaluation can be performed as `(funcall NAME)' inside the body
as many times as wanted (including zero). If you call it
as `(funcall NAME NEW-VALUE)', evaluated value is replaced.
Actual EXPRESSION is evaluated only the first time, after which
its value is remembered and returned unchanged. If the value has
been evaluated or replaced using a call with an argument, CLEANUP
form is executed at the end.
\(fn (NAME EXPRESSION [CLEANUP [AS-UNWIND-PROTECT]]) BODY...)"
(declare (indent 1))
(let ((name (nth 0 spec))
(expression (nth 1 spec))
(cleanup (nth 2 spec))
(as-unwind-protect (nth 3 spec))
(evaluated (make-symbol "$evaluated"))
(value (make-symbol "$value")))
(setf cleanup (when cleanup `(if ,evaluated ,cleanup)))
`(let* (,evaluated
,value
(,name (lambda (&rest new-value)
(cond (new-value
(when (cdr new-value)
(error "Must be called with zero or one argument only"))
(setf ,value (car new-value)
,evaluated t))
((not ,evaluated)
(setf ,value ,expression
,evaluated t)))
,value)))
,@(if cleanup
(if as-unwind-protect
`((unwind-protect ,(macroexp-progn body) ,cleanup))
`(,@body ,cleanup))
body))))
(defun eldev-parse-number (string &rest options)
"Similar to `string-to-number', but with error checking.
Useful in user interface to give feedback on erroneous input.
Signalled errors are of generic type, use `eldev-with-errors-as'
to rebrand as needed.
Supported OPTIONS:
:floating-point
Also parse floating-point numbers; by default only
integers are accepted.
:min, :max
Throw an error if the number is outside this range.
Since 1.1.1."
(let (floating-point
min
max)
(while options
(eldev-pcase-exhaustive (pop options)
(:floating-point (setf floating-point (pop options)))
(:min (setf min (pop options)))
(:max (setf max (pop options)))))
(unless (string-match-p (if floating-point
(rx bos (? (any "+-")) (| (seq (+ digit) (? (| (seq "." (* digit)) (seq (any "eE") (? (any "+-")) (+ digit))))) (seq "." (* digit)) eos))
(rx bos (? (any "+-")) (+ digit) eos))
string)
(error (eldev-format-message (if floating-point "`%s' it not a valid number" "`%s' it not a valid integer number") string)))
(let ((number (string-to-number string)))
(when (and min (< number min))
(error (eldev-format-message "minimum allowed value is %s" min)))
(when (and max (> number max))
(error (eldev-format-message "maximum allowed value is %s" max)))
number)))
(defmacro eldev-with-file-buffer (file &rest body)
"Execute in a buffer with FILE and write results back.
Since 1.2."
(declare (indent 1) (debug (stringp sexp body)))
(let ((filename (make-symbol "$filename")))
`(let ((,filename ,file))
(with-temp-buffer
(ignore-errors (insert-file-contents ,filename t))
,@body
(let ((backup-inhibited t))
(eldev--silence-file-writing-message ,filename
(save-buffer)))))))
(defun eldev-write-to-file (file &optional from to)
"Write current buffer's contents to FILE.
Since 1.2."
(if (or from to)
(write-region (or from (point-min)) (or to (point-max)) file nil 'no-message)
(write-region nil nil file nil 'no-message)))
;; Output.
(defvar eldev-verbosity-level nil
"How much output Eldev generates.
Can be a symbol `quiet', `verbose' or `trace'. Any other value,
including nil, stands for the default verbosity level.")
(defvar eldev-coloring-mode 'auto
"Whether to use coloring on output.
Special symbol \\='auto means that coloring should be used when
printing to a real terminal, but not when printing to a file.")
(defvar eldev--tty (equal (eldev-getenv "ELDEV_TTY") "t"))
(defvar eldev-colorizing-schemes (eval-when-compile (let (schemes)
(dolist (type '((error ((light-bg "91;1") (dark-bg "91;1") (interactive error)))
(warn ((light-bg 31) (dark-bg 31) (interactive warning)))
(verbose ((light-bg 90) (dark-bg 90) (interactive shadow)))
(trace ((light-bg 90) (dark-bg 90) (interactive shadow)))
(debug ((light-bg 35) (dark-bg 95) (interactive font-lock-comment-face)))
(success ((light-bg 32) (dark-bg 92) (interactive success)))
(section ((light-bg 1) (dark-bg 1) (interactive bold)))
(default ((light-bg 34) (dark-bg 94) (interactive font-lock-c)))
(name ((light-bg 33) (dark-bg 93) (interactive font-lock-function-name-face)))
(url ((light-bg 34) (dark-bg 96) (interactive font-lock-string-face)))
(details ((light-bg 90) (dark-bg 90) (interactive shadow)))
(timestamp ((light-bg 90) (dark-bg 90) (interactive shadow)))))
(dolist (entry (cadr type))
(puthash (car type) (if (eq (car entry) 'interactive) (cadr entry) (format "%s" (cadr entry)))
(or (cdr (assq (car entry) schemes))
(eldev--assq-set (car entry) (make-hash-table :test #'eq) schemes)))))
schemes))
"Alist of colorizing schemes.
Specifies how to convert colorizing types to actual ASCII
terminal colors.")
(defvar eldev-used-colorizing-scheme nil
"Used colorizing scheme.
If not specified, Eldev will try to pick the best-suited one.")
(defvar eldev-output-time-diffs nil
"Whether to prepend all output lines with elapsed time.")
(defvar eldev-output-newline-pending nil
"If the last printed line is not terminated yet.
Only output coming through `eldev-output' counts. Since 1.6.")
(defvar eldev--time-diff-base (float-time))
(defvar eldev-disable-message-rerouting nil
"Temporarily disable message rerouting.
See `eldev-output-reroute-messages'.")
(defvar eldev-message-rerouting-destination :stderr
"Rerouted message destination.
Should be either `:stderr', `:stdout' or (since 1.3) `:debug' to
reroute them to debugging output.")
(defvar eldev-message-rerouting-wrapper nil
"When set, send rerouted message through this function/macro.
Typical values would be `eldev-warn', `eldev-trace' etc. Note
that this overrides `eldev-message-rerouting-destination'.")
(defvar eldev-interactive-stderr-destination 'debugging-output
"Interactively, show output meant for stderr in given way.
Normally, Eldev and its functions are meant for non-interactive
use. However, it is possible to use e.g. `eldev-backtrace' in
a (preferably) temporary way as means of debugging output. The
output that normally comes to stderr (also from `eldev-warn', for
example) can be redirected in interactive use as follows:
`message' or nil -- show it with `message';
`debugging-output' -- send to _Emacs_ stderr, similar to output
of `eldev-debug'; this is the default;
`display-warning' -- show with `display-warning', trying to
pick a suitable level.
Since 1.3.")
(defvar eldev-xdebug-output-enabled nil
"Set if optional debugging output is enabled.
This shouldn't be set directly, instead use `eldev-maybe-xdebug',
`eldev-enabling-xdebug', `eldev-disabling-xdebug' or let-bind
this variable.
Since 1.4.")
(defvar eldev-debugging-output-level 0
"The nesting level of debugging output.
This shouldn't be set directly, instead use macro
`eldev-nest-debugging-output' or let-bind this variable.
Since 1.4.")
(defvar eldev--real-stderr-output nil)
;; Might want to make part of public interface.
(defvar eldev--skip-nothing-to-do-messages nil)
(defalias 'eldev-format-message (if (fboundp 'format-message) 'format-message #'format)
"Like `format-message' if that is defined.
Fall back to `format' on older Emacs versions.")
(defun eldev-message-plural (n singular &optional plural)
"Return SINGULAR or PLURAL as suitable for the value of N.
If PLURAL is not specified, it is built from SINGULAR by adding a
single ‘s’ (suitable for most, but not all words)."
(if (= n 1)
(eldev-format-message "%d %s" n singular)
(if plural
(eldev-format-message "%d %s" n plural)
(eldev-format-message "%d %ss" n singular))))
(defun eldev-message-enumerate (string values &optional converter dont-quote no-and)
"Enumerate VALUES for use in human-readable messages.
STRING is the common term. Can be either a simple string, a
two-item list in form (SINGULAR PLURAL) or nil.
If CONVERTER is specified, it should be a function that converts
a value to a string; otherwise VALUES must be a list of strings.
Values are put in single quotes, unless DONT-QUOTE is specified.
Values are separated by commas, but the last two, for better
readability, are separated with word “and”. However, if NO-AND
is t, a comma is used also between the last two values. If
NO-AND is a string, it is used in place of “and”."
(let (enumerated)
(setf values (eldev-listify values))
(when string
(push (if (cdr values)
(if (consp string) (cadr string) (format "%ss" string))
(if (consp string) (car string) string))
enumerated)
(push " " enumerated))
(while values
(let ((as-string (if converter (funcall converter (pop values)) (pop values))))
(push (eldev-format-message (if dont-quote "%s" "`%s'") as-string) enumerated))
(when values
(push (if (or (cdr values) (eq no-and t)) ", " (if no-and (concat " " no-and " ") " and ")) enumerated)))
(apply #'concat (nreverse enumerated))))
(defun eldev-message-enumerate-files (string files)
"Enumerate FILES for use in human-readable messages.
See function `eldev-message-enumerate' for details."
(eldev-format-message string (if (and files (null (cdr files))) "" "s")
(if files (mapconcat (lambda (file) (eldev-format-message "`%s'" file)) files ", ") "none")
(length files)))
(defun eldev-message-version (version &optional colorized parenthesized)
"Format VERSION for use in human-readable messages.
VERSION can be a string, a list (see `version-to-list') or a
package descriptor."
(let ((string (cond ((stringp version) version)
((and version (not (equal version '(0)))) (package-version-join (if (listp version) version (package-desc-version version))))
(t "any"))))
(when colorized
(setf string (eldev-colorize string 'version)))
(when (or parenthesized (string= string "any"))
(setf string (format "(%s)" string)))
string))
(defun eldev-message-command-line (executable command-line)
"Format given command line for human-readable messages"
(concat executable " " (mapconcat #'eldev-quote-sh-string command-line " ")))
(defun eldev-message-upcase-first (string)
(if (> (length string) 0)
(concat (upcase (substring string 0 1)) (substring string 1))
string))
(defun eldev-y-or-n-p (prompt)
"Similar to `y-or-n-p'.
Currently the only difference is that it supports colorizing in
PROMPT. More can be added later (preserving semantics)."
(eldev-output-prompt prompt)
(y-or-n-p ""))
(defun eldev-yes-or-no-p (prompt)
"Similar to `yes-or-no-p'.
Currently the only difference is that it supports colorizing in
PROMPT. More can be added later (preserving semantics). Since
1.2."
(eldev-output-prompt prompt)
(yes-or-no-p ""))
(defun eldev-read-string (prompt &optional initial-input)
"Similar to `read-string'.
Currently the only difference is that it supports colorizing in
PROMPT. More can be added later (preserving semantics). Since
1.2."
(eldev-output-prompt prompt)
(read-string "" nil nil initial-input))
(defun eldev-output-prompt (prompt)
(eldev-output :nolf "%s" prompt))
(defun eldev-colorize (string &rest types)
"Apply given Eldev colorizing to STRING."
(setf string (copy-sequence (cond ((stringp string) string)
((symbolp string) (symbol-name string))
;; We get here e.g. if `eldev-debug' is mixed up with `eldev-dump'.
(t (error "Expected a string or a symbol, got %S instead" string)))))
(when types
(add-face-text-property 0 (length string) types nil string))
string)
(defsubst eldev-output-colorized-p ()
"Determine if output should be colorized.
Since 0.2."
(if (eq eldev-coloring-mode 'auto) eldev--tty eldev-coloring-mode))
;; Only from Emacs 29.
(declare-function flush-standard-output nil)
;; From Emacs 25.
(declare-function set-binary-mode nil)
(defun eldev-output (format-string &rest arguments)
"Unconditionally format and print given message."
(let (special-destination
nolf
nocolor
colors)
(while (keywordp format-string)
(pcase format-string
(`:stdout (setf special-destination nil))
(`:stderr (setf special-destination
(if noninteractive
'stderr
(pcase eldev-interactive-stderr-destination
(`debugging-output 'debugging-output)
(`display-warning 'display-warning)
(_ 'stderr)))))
((or `:debug `:debugging-output) (setf special-destination 'debugging-output))
(`:nolf (setf nolf t))
(`:nocolor (setf nocolor t))
(`:color (push (pop arguments) colors))
(_ (error "Unknown option `%s'" format-string)))
(setf format-string (pop arguments)))
(let ((message (if format-string (apply #'eldev-format-message format-string arguments) "")))
(when (eq special-destination 'debugging-output)
(let ((prefix (eldev-debugging-output-prefix)))
(when (and prefix (> (length prefix) 0))
(setf message (replace-regexp-in-string (rx bol) prefix message t t)))))
(when colors
(setf message (apply #'eldev-colorize message colors)))
(when eldev-output-time-diffs
(let (part1
part2)
(if eldev-output-newline-pending
(let ((newline-at (string-match-p "\n" message)))
(when newline-at
(setf part1 (substring message 0 (1+ newline-at))
part2 (substring message (1+ newline-at)))))
(setf part1 ""
part2 message))
;; Only insert timestamp when last output ended with newline, or `message' contains one.
(when part1
(let* ((elapsed (- (float-time) eldev--time-diff-base))
(elapsed-min (floor (/ elapsed 60)))
(elapsed-sec-raw (- elapsed (* elapsed-min 60)))
(elapsed-sec (floor elapsed-sec-raw))
(elapsed-millis (floor (* (- elapsed-sec-raw elapsed-sec) 1000))))
(setf message (concat part1
(eldev-colorize (format "[%02d:%02d.%03d]" elapsed-min elapsed-sec elapsed-millis) 'timestamp)
" " (replace-regexp-in-string "\n" "\n " part2 t t)))))))
(setf eldev-output-newline-pending (and nolf (not (string-match-p (rx "\n" eos) message))))
(if (or noninteractive (eq special-destination 'debugging-output))
(when (and (not nocolor) (eldev-output-colorized-p))
(let ((colorizing-scheme (eldev--get-colorizing-scheme))
(from 0)
chunks)
(while (let ((to (next-property-change from message)))
(let ((faces (get-text-property from 'face message)))
(when (or to faces)
(if faces
(dolist (type (eldev-listify faces))
(let ((ascii-mode (gethash type colorizing-scheme)))
(when ascii-mode
(push (format "\033[%sm" ascii-mode) chunks))))
(push "\033[0m" chunks))
(push (substring-no-properties message from to) chunks)
(if to
(setf from to)
(setf from (length message))
nil)))))
(when chunks
(push "\033[0m" chunks))
(push (substring-no-properties message from) chunks)
(setf message (mapconcat #'identity (nreverse chunks) ""))))
;; While Eldev is meant to be used non-interactively, make some effort to support
;; interactive use too, especially for temporary debug output. Otherwise Emacs
;; would complain about unknown faces.
(let ((interactive-faces (cdr (assq 'interactive eldev-colorizing-schemes)))
(replaced-up-to 0))
(while replaced-up-to
(let ((faces (get-text-property replaced-up-to 'face message))
(next-change (next-single-property-change replaced-up-to 'face message))
replaced-faces)
(when faces
(dolist (face (eldev-listify faces))
(let ((replacement (gethash face interactive-faces)))
(when replacement
(push replacement replaced-faces))))
(put-text-property replaced-up-to (or next-change (length message)) 'face (nreverse replaced-faces) message))
(setf replaced-up-to next-change)))))
(pcase special-destination
(`stderr
(eldev--do-stderr-output message (not nolf)))
(`display-warning
(let ((scan 0)
probably-error)
(while (and scan (not (setf probably-error (memq 'error (eldev-listify (get-text-property scan 'face message))))))
(setf scan (next-single-property-change scan 'face message)))
(display-warning 'eldev message (if probably-error :error :warning))))
(_
(princ (if nolf message (concat message "\n")) (when special-destination #'external-debugging-output))
(unless special-destination
;; On Emacs 24 stdout is not flushed. It's OK, likely no-one uses it anymore.
(cond ((fboundp 'flush-standard-output)
(flush-standard-output))
((fboundp 'set-binary-mode)
;; "As a side effect, this function flushes any pending STREAM’s data."
(set-binary-mode 'stdout nil))))))))
;; To make e.g. calling from M-: give nicer results.
nil)
(defun eldev--do-stderr-output (string &optional add-lf)
(if noninteractive
;; Starting with 1.6 we do it like this for non-interactive (i.e. the "normal")
;; usecase. This allows us to process `:nolf' (see `eldev-output' above) also here,
;; but otherwise there should be no detectable differences compared to using
;; `message' (except fewer newlines). Despite how it may look from the last `pcase'
;; branch, `debugging-output' as the destination is still substantially different:
;; for that indentation and faces are applied above.
(princ (if add-lf (concat string "\n") string) #'external-debugging-output)
(let ((inhibit-message nil)
(eldev--real-stderr-output t))
;; `message' always adds a newline and there appears to be no way to avoid that.
(message "%s" string))))
(defun eldev--get-colorizing-scheme ()
;; Main purpose of this function is to autoguess background, but I
;; don't know how to do that (see also comments in `bin/eldev.in').
(unless eldev-used-colorizing-scheme
(setf eldev-used-colorizing-scheme 'light-bg))
(cdr (assq eldev-used-colorizing-scheme eldev-colorizing-schemes)))
(eval-and-compile
(defun eldev--output-wrapper (extra-keywords colorize-as format-string arguments)
(let (keywords)
(while (keywordp format-string)
(push format-string keywords)
(setf format-string (pop arguments)))
`(eldev-output ,@extra-keywords ,@(nreverse keywords) (eldev-colorize ,format-string ',colorize-as) ,@arguments))))
(defmacro eldev-error (format-string &rest arguments)
"Format and print given error message."
(eldev--output-wrapper '(:stderr) 'error format-string arguments))
(defmacro eldev-warn (format-string &rest arguments)
"Format and print given warning message."
(eldev--output-wrapper '(:stderr) 'warn format-string arguments))
(defmacro eldev-unless-quiet (&rest body)
"Execute BODY, unless in quiet mode."
(declare (indent 0) (debug (body)))
`(unless (eq eldev-verbosity-level 'quiet) ,@body))
(defmacro eldev-print (format-string &rest arguments)
"Format and print given message, unless in quiet mode."
`(eldev-unless-quiet (eldev-output ,format-string ,@arguments)))
(defmacro eldev-when-verbose (&rest body)
"Execute BODY if in verbose (or trace) mode."
(declare (indent 0) (debug (body)))
`(when (memq eldev-verbosity-level '(verbose trace)) ,@body))
(defmacro eldev-verbose (format-string &rest arguments)
"Format and print given message if in verbose (or trace) mode."
`(eldev-when-verbose ,(eldev--output-wrapper nil 'verbose format-string arguments)))
(defmacro eldev-when-tracing (&rest body)
"Execute BODY if in trace mode."
(declare (indent 0) (debug (body)))
`(when (eq eldev-verbosity-level 'trace) ,@body))
(defmacro eldev-trace (format-string &rest arguments)
"Format and print given message if in trace mode."
`(eldev-when-tracing ,(eldev--output-wrapper nil 'trace format-string arguments)))
(defmacro eldev-debug (format-string &rest arguments)
"Format and print given debugging output message.
The message is printed to stderr in standing-out color.
Since 1.3."
(eldev--output-wrapper '(:debugging-output) 'debug format-string arguments))
(defmacro eldev-xdebug (format-string &rest arguments)
"As `eldev-debug', but only if optional debugging output is enabled.
Otherwise does nothing. See `eldev-xdebug-output-enabled'.
Since 1.4."
`(when eldev-xdebug-output-enabled
(eldev-debug ,format-string ,@arguments)))
(defmacro eldev-dump (&rest forms)
"Dump values of given FORMS using `eldev-debug'.
Typical use is to dump values of variables, but FORMS may contain
any expressions. No specific guarantees about the way the output
looks other than that it should be useful to human eyes. For
example, literal forms, most importantly string literals, are
displayed differently.
Since 1.3."
(when forms
(let (bindings
dumping-forms)
;; Some complications to properly dump values like e.g. `(point-min)': make sure we
;; precompute everything before switching buffers in the macroexpansion.
(dolist (form forms)
(if (eldev-literalp form)
;; `print-quoted' defaulted to nil up to Emacs 26.
(push `(insert ,(let ((print-quoted t)) (format "%s%s" (if dumping-forms "\n" "") form))) dumping-forms)
(let ((variable (make-symbol (format "$%S" form))))
(push `(,variable ,form) bindings)
(push `(insert ,(format "%s%S = " (if dumping-forms "\n" "") form)) dumping-forms)
(push `(eldev-prin1 ,variable (current-buffer)) dumping-forms))))
`(let (,@(nreverse bindings))
(with-temp-buffer
,@(nreverse dumping-forms)
(eldev-debug "%s" (buffer-string)))))))
(defmacro eldev-xdump (&rest forms)
"As `eldev-dump', but only if optional debugging output is enabled.
Otherwise does nothing. See `eldev-xdebug-output-enabled'.
Since 1.4."
`(when eldev-xdebug-output-enabled
(eldev-dump ,@forms)))
(defmacro eldev-time-it (format-string &rest body)
"Execute BODY and print execution time using `eldev-debug'.
FORMAT-STRING is used to format the resulting message. It should
format exactly one floating-point number (of seconds taken),
i.e. use \"%f\". FORMAT-STRING can be a literal string or a form
that evaluates to a string, but in either case will be used for
formatting. If it is a literal that doesn't format any
variables, \": %.2f s\" is appended to it.
This macro uses function `float-time' to measure time spent on
executing BODY. It is not particularly suited for measuring very
small time intervals (e.g. below millisecond granularity), though
can also be used for that: just consider the result only a rough
estimation in that case.
Since 1.4."
(declare (indent 1) (debug (stringp body)))
(let ((notch (make-symbol "$notch")))
;; Detect if `format-string' already formats the seconds. FIXME: Can this be improved?