-
Notifications
You must be signed in to change notification settings - Fork 12
/
compat-29.el
1599 lines (1391 loc) · 65.7 KB
/
compat-29.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
;;; compat-29.el --- Functionality added in Emacs 29.1 -*- lexical-binding: t; -*-
;; Copyright (C) 2021-2024 Free Software Foundation, Inc.
;; 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:
;; Functionality added in Emacs 29.1, needed by older Emacs versions.
;;; Code:
(eval-when-compile (load "compat-macs.el" nil t t))
(compat-require compat-28 "28.1")
;; Preloaded in loadup.el
(compat-require seq "29.1") ;; <compat-tests:seq>
(compat-version "29.1")
;;;; Defined in startup.el
(compat-defvar lisp-directory ;; <compat-tests:lisp-directory>
(file-truename
(file-name-directory
(locate-file "simple" load-path (get-load-suffixes))))
"Directory where Emacs's own *.el and *.elc Lisp files are installed.")
;;;; Defined in window.c
(compat-defalias window-configuration-equal-p compare-window-configurations) ;; <compat-tests:window-configuration-equal-p>
;;;; Defined in xdisp.c
(compat-defun get-display-property (position prop &optional object properties) ;; <compat-tests:get-display-property>
"Get the value of the `display' property PROP at POSITION.
If OBJECT, this should be a buffer or string where the property is
fetched from. If omitted, OBJECT defaults to the current buffer.
If PROPERTIES, look for value of PROP in PROPERTIES instead of
the properties at POSITION."
(if properties
(unless (listp properties)
(signal 'wrong-type-argument (list 'listp properties)))
(setq properties (get-text-property position 'display object)))
(cond
((vectorp properties)
(catch 'found
(dotimes (i (length properties))
(let ((ent (aref properties i)))
(when (eq (car ent) prop)
(throw 'found (cadr ent )))))))
((consp (car properties))
(condition-case nil
(cadr (assq prop properties))
;; Silently handle improper lists:
(wrong-type-argument nil)))
((and (consp (cdr properties))
(eq (car properties) prop))
(cadr properties))))
;;;; Defined in fns.c
(compat-defun ntake (n list) ;; <compat-tests:ntake>
"Modify LIST to keep only the first N elements.
If N is zero or negative, return nil.
If N is greater or equal to the length of LIST, return LIST unmodified.
Otherwise, return LIST after truncating it."
(and (> n 0) (let ((cons (nthcdr (1- n) list)))
(when cons (setcdr cons nil))
list)))
(compat-defun take (n list) ;; <compat-tests:take>
"Return the first N elements of LIST.
If N is zero or negative, return nil.
If N is greater or equal to the length of LIST, return LIST (or a copy)."
(declare (pure t) (side-effect-free t))
(let (copy)
(while (and (< 0 n) list)
(push (pop list) copy)
(setq n (1- n)))
(nreverse copy)))
(compat-defun string-equal-ignore-case (string1 string2) ;; <compat-tests:string-equal-ignore-case>
"Like `string-equal', but case-insensitive.
Upper-case and lower-case letters are treated as equal.
Unibyte strings are converted to multibyte for comparison."
(declare (pure t) (side-effect-free t))
(eq t (compare-strings string1 0 nil string2 0 nil t)))
(compat-defun plist-get (plist prop &optional predicate) ;; <compat-tests:plist-get>
"Handle optional argument PREDICATE."
:extended t
(pcase predicate
((or `nil `eq) (plist-get plist prop))
(`equal (lax-plist-get plist prop))
(_ (catch 'found
(while (consp plist)
(when (funcall predicate prop (car plist))
(throw 'found (cadr plist)))
(setq plist (cddr plist)))))))
(compat-defun plist-put (plist prop val &optional predicate) ;; <compat-tests:plist-get>
"Handle optional argument PREDICATE."
:extended t
(pcase predicate
((or `nil `eq) (plist-put plist prop val))
(`equal (lax-plist-put plist prop val))
(_ (catch 'found
(let ((tail plist))
(while (consp tail)
(when (funcall predicate prop (car tail))
(setcar (cdr tail) val)
(throw 'found plist))
(setq tail (cddr tail))))
(nconc plist (list prop val))))))
(compat-defun plist-member (plist prop &optional predicate) ;; <compat-tests:plist-get>
"Handle optional argument PREDICATE."
:extended t
(pcase predicate
((or `nil `eq) (plist-member plist prop))
(_ (catch 'found
(while (consp plist)
(when (funcall predicate prop (car plist))
(throw 'found plist))
(setq plist (cddr plist)))))))
;;;; Defined in gv.el
(compat-guard t ;; <compat-tests:plist-get-gv>
(gv-define-expander compat--plist-get
(lambda (do plist prop &optional predicate)
(macroexp-let2 macroexp-copyable-p key prop
(gv-letplace (getter setter) plist
(macroexp-let2 nil p `(cdr (compat--plist-member ,getter ,key ,predicate))
(funcall do
`(car ,p)
(lambda (val)
`(if ,p
(setcar ,p ,val)
,(funcall setter
`(cons ,key (cons ,val ,getter)))))))))))
(unless (get 'plist-get 'gv-expander)
(put 'plist-get 'gv-expander (get 'compat--plist-get 'gv-expander))))
;;;; Defined in editfns.c
(compat-defun pos-bol (&optional n) ;; <compat-tests:pos-bol>
"Return the position of the first character on the current line.
With optional argument N, scan forward N - 1 lines first.
If the scan reaches the end of the buffer, return that position.
This function ignores text display directionality; it returns the
position of the first character in logical order, i.e. the smallest
character position on the logical line. See `vertical-motion' for
movement by screen lines.
This function does not move point. Also see `line-beginning-position'."
(declare (side-effect-free t))
(let ((inhibit-field-text-motion t))
(line-beginning-position n)))
(compat-defun pos-eol (&optional n) ;; <compat-tests:pos-bol>
"Return the position of the last character on the current line.
With argument N not nil or 1, move forward N - 1 lines first.
If scan reaches end of buffer, return that position.
This function ignores text display directionality; it returns the
position of the last character in logical order, i.e. the largest
character position on the line.
This function does not move point. Also see `line-end-position'."
(declare (side-effect-free t))
(let ((inhibit-field-text-motion t))
(line-end-position n)))
;;;; Defined in subr.el
(compat-defmacro with-delayed-message (_args &rest body) ;; <compat-tests:with-delayed-message>
"Like `progn', but display MESSAGE if BODY takes longer than TIMEOUT seconds.
The MESSAGE form will be evaluated immediately, but the resulting
string will be displayed only if BODY takes longer than TIMEOUT seconds.
NOTE: The compatibility function never displays the message,
which is not problematic since the only effect of the function is
to display a progress message to the user. Backporting this
feature is not possible, since the implementation is directly
baked into the Elisp interpreter.
\(fn (timeout message) &rest body)"
(declare (indent 1))
(macroexp-progn body))
(compat-defun funcall-with-delayed-message (timeout message function) ;; <compat-tests:with-delayed-message>
"Like `funcall', but display MESSAGE if FUNCTION takes longer than TIMEOUT.
TIMEOUT is a number of seconds, and can be an integer or a
floating point number. If FUNCTION takes less time to execute
than TIMEOUT seconds, MESSAGE is not displayed.
NOTE: The compatibility function never displays the message,
which is not problematic since the only effect of the function is
to display a progress message to the user. Backporting this
feature is not possible, since the implementation is directly
baked into the Elisp interpreter."
(ignore timeout message)
(funcall function))
(compat-defun string-lines (string &optional omit-nulls keep-newlines) ;; <compat-tests:string-lines>
"Handle additional KEEP-NEWLINES argument."
:extended "28.1"
(if (equal string "")
(if omit-nulls
nil
(list ""))
(let ((lines nil)
(start 0))
(while (< start (length string))
(let ((newline (string-search "\n" string start)))
(if newline
(progn
(when (or (not omit-nulls)
(not (= start newline)))
(let ((line (substring string start
(if keep-newlines
(1+ newline)
newline))))
(when (not (and keep-newlines omit-nulls
(equal line "\n")))
(push line lines))))
(setq start (1+ newline)))
(if (zerop start)
(push string lines)
(push (substring string start) lines))
(setq start (length string)))))
(nreverse lines))))
(compat-defun readablep (object) ;; <compat-tests:readablep>
"Say whether OBJECT has a readable syntax.
This means that OBJECT can be printed out and then read back
again by the Lisp reader. This function returns nil if OBJECT is
unreadable, and the printed representation (from `prin1') of
OBJECT if it is readable."
(declare (side-effect-free error-free))
(ignore-errors (equal object (read (prin1-to-string object)))))
(compat-defun buffer-local-restore-state (states) ;; <compat-tests:buffer-local-set-state>
"Restore values of buffer-local variables recorded in STATES.
STATES should be an object returned by `buffer-local-set-state'."
(dolist (state states)
(if (cadr state)
(set (car state) (caddr state))
(kill-local-variable (car state)))))
(compat-defun buffer-local-set-state--get (pairs) ;; <compat-tests:buffer-local-set-state>
"Internal helper function."
(let ((states nil))
(while pairs
(push (list (car pairs)
(and (boundp (car pairs))
(local-variable-p (car pairs)))
(and (boundp (car pairs))
(symbol-value (car pairs))))
states)
(setq pairs (cddr pairs)))
(nreverse states)))
(compat-defmacro buffer-local-set-state (&rest pairs) ;; <compat-tests:buffer-local-set-state>
"Like `setq-local', but allow restoring the previous state of locals later.
This macro returns an object that can be passed to `buffer-local-restore-state'
in order to restore the state of the local variables set via this macro.
\(fn [VARIABLE VALUE]...)"
(declare (debug setq))
(unless (zerop (mod (length pairs) 2))
(error "PAIRS must have an even number of variable/value members"))
`(prog1
(buffer-local-set-state--get ',pairs)
(,(if (fboundp 'compat--setq-local) 'compat--setq-local 'setq-local)
,@pairs)))
(compat-defun list-of-strings-p (object) ;; <compat-tests:list-of-strings-p>
"Return t if OBJECT is nil or a list of strings."
(declare (pure t) (side-effect-free t))
(while (and (consp object) (stringp (car object)))
(setq object (cdr object)))
(null object))
(compat-defun plistp (object) ;; <compat-tests:plistp>
"Non-nil if and only if OBJECT is a valid plist."
(let ((len (proper-list-p object)))
(and len (zerop (% len 2)))))
(compat-defun delete-line () ;; <compat-tests:delete-line>
"Delete the current line."
(delete-region (pos-bol) (pos-bol 2)))
(compat-defmacro with-restriction (start end &rest rest) ;; <compat-tests:with-restriction>
"Execute BODY with restrictions set to START and END.
The current restrictions, if any, are restored upon return.
When the optional :label LABEL argument is present, in which
LABEL is a symbol, inside BODY, `narrow-to-region' and `widen'
can be used only within the START and END limits. To gain access
to other portions of the buffer, use `without-restriction' with the
same LABEL argument.
\(fn START END [:label LABEL] BODY)"
(declare (indent 0) (debug t))
`(save-restriction
(narrow-to-region ,start ,end)
;; Locking is ignored
,@(if (eq (car rest) :label) (cddr rest) rest)))
(compat-defmacro without-restriction (&rest rest) ;; <compat-tests:without-restriction>
"Execute BODY without restrictions.
The current restrictions, if any, are restored upon return.
When the optional :label LABEL argument is present, the
restrictions set by `with-restriction' with the same LABEL argument
are lifted.
\(fn [:label LABEL] BODY)"
(declare (indent 0) (debug t))
`(save-restriction
(widen)
;; Locking is ignored
,@(if (eq (car rest) :label) (cddr rest) rest)))
(compat-defmacro with-memoization (place &rest code) ;; <compat-tests:with-memoization>
"Return the value of CODE and stash it in PLACE.
If PLACE's value is non-nil, then don't bother evaluating CODE
and return the value found in PLACE instead."
(declare (indent 1))
(gv-letplace (getter setter) place
`(or ,getter
,(macroexp-let2 nil val (macroexp-progn code)
`(progn
,(funcall setter val)
,val)))))
(compat-defalias string-split split-string) ;; <compat-tests:string-split>
(compat-defun compiled-function-p (object) ;; <compat-tests:compiled-function-p>
"Return non-nil if OBJECT is a function that has been compiled.
Does not distinguish between functions implemented in machine code
or byte-code."
(or (subrp object) (byte-code-function-p object)))
(compat-defun function-alias-p (func &optional noerror) ;; <compat-tests:function-alias-p>
"Return nil if FUNC is not a function alias.
If FUNC is a function alias, return the function alias chain.
If the function alias chain contains loops, an error will be
signalled. If NOERROR, the non-loop parts of the chain is returned."
(declare (side-effect-free t))
(let ((chain nil)
(orig-func func))
(nreverse
(catch 'loop
(while (and (symbolp func)
(setq func (symbol-function func))
(symbolp func))
(when (or (memq func chain)
(eq func orig-func))
(if noerror
(throw 'loop chain)
(signal 'cyclic-function-indirection (list orig-func))))
(push func chain))
chain))))
(compat-defun buffer-match-p (condition buffer-or-name &optional arg) ;; <compat-tests:buffer-match-p>
"Return non-nil if BUFFER-OR-NAME matches CONDITION.
CONDITION is either:
- the symbol t, to always match,
- the symbol nil, which never matches,
- a regular expression, to match a buffer name,
- a predicate function that takes a buffer object and ARG as
arguments, and returns non-nil if the buffer matches,
- a cons-cell, where the car describes how to interpret the cdr.
The car can be one of the following:
* `derived-mode': the buffer matches if the buffer's major mode
is derived from the major mode in the cons-cell's cdr.
* `major-mode': the buffer matches if the buffer's major mode
is eq to the cons-cell's cdr. Prefer using `derived-mode'
instead when both can work.
* `not': the cadr is interpreted as a negation of a condition.
* `and': the cdr is a list of recursive conditions, that all have
to be met.
* `or': the cdr is a list of recursive condition, of which at
least one has to be met."
(letrec
((buffer (get-buffer buffer-or-name))
(match
(lambda (conditions)
(catch 'match
(dolist (condition conditions)
(when (cond
((eq condition t))
((stringp condition)
(string-match-p condition (buffer-name buffer)))
((functionp condition)
(condition-case nil
(funcall condition buffer)
(wrong-number-of-arguments
(funcall condition buffer arg))))
((eq (car-safe condition) 'major-mode)
(eq
(buffer-local-value 'major-mode buffer)
(cdr condition)))
((eq (car-safe condition) 'derived-mode)
(provided-mode-derived-p
(buffer-local-value 'major-mode buffer)
(cdr condition)))
((eq (car-safe condition) 'not)
(not (funcall match (cdr condition))))
((eq (car-safe condition) 'or)
(funcall match (cdr condition)))
((eq (car-safe condition) 'and)
(catch 'fail
(dolist (c (cdr condition))
(unless (funcall match (list c))
(throw 'fail nil)))
t)))
(throw 'match t)))))))
(funcall match (list condition))))
(compat-defun match-buffers (condition &optional buffers arg) ;; <compat-tests:match-buffers>
"Return a list of buffers that match CONDITION.
See `buffer-match' for details on CONDITION. By default all
buffers are checked, this can be restricted by passing an
optional argument BUFFERS, set to a list of buffers to check.
ARG is passed to `buffer-match', for predicate conditions in
CONDITION."
(let (bufs)
(dolist (buf (or buffers (buffer-list)))
(when (buffer-match-p condition (get-buffer buf) arg)
(push buf bufs)))
bufs))
(compat-defvar set-transient-map-timeout nil ;; <compat-tests:set-transient-map>
"Timeout in seconds for deactivation of a transient keymap.
If this is a number, it specifies the amount of idle time
after which to deactivate the keymap set by `set-transient-map',
thus overriding the value of the TIMEOUT argument to that function.")
(compat-defvar set-transient-map-timer nil ;; <compat-tests:set-transient-map>
"Timer for `set-transient-map-timeout'.")
(declare-function format-spec "format-spec")
(compat-defun set-transient-map (map &optional keep-pred on-exit message timeout) ;; <compat-tests:set-transient-map>
"Handle the optional arguments MESSAGE and TIMEOUT."
:extended t
(unless (fboundp 'format-spec)
(require 'format-spec))
(let* ((timeout (or set-transient-map-timeout timeout))
(message
(when message
(let (keys)
(map-keymap (lambda (key cmd) (and cmd (push key keys))) map)
(format-spec (if (stringp message) message "Repeat with %k")
`((?k . ,(mapconcat
(lambda (key)
(substitute-command-keys
(format "\\`%s'"
(key-description (vector key)))))
keys ", ")))))))
(clearfun (make-symbol "clear-transient-map"))
(exitfun
(lambda ()
(internal-pop-keymap map 'overriding-terminal-local-map)
(remove-hook 'pre-command-hook clearfun)
(when message (message ""))
(when set-transient-map-timer (cancel-timer set-transient-map-timer))
(when on-exit (funcall on-exit)))))
(fset clearfun
(lambda ()
(with-demoted-errors "set-transient-map PCH: %S"
(if (cond
((null keep-pred) nil)
((and (not (eq map (cadr overriding-terminal-local-map)))
(memq map (cddr overriding-terminal-local-map)))
t)
((eq t keep-pred)
(let ((mc (lookup-key map (this-command-keys-vector))))
(when (and mc (symbolp mc))
(setq mc (or (command-remapping mc) mc)))
(and mc (eq this-command mc))))
(t (funcall keep-pred)))
(when message (message "%s" message))
(funcall exitfun)))))
(add-hook 'pre-command-hook clearfun)
(internal-push-keymap map 'overriding-terminal-local-map)
(when timeout
(when set-transient-map-timer (cancel-timer set-transient-map-timer))
(setq set-transient-map-timer (run-with-idle-timer timeout nil exitfun)))
(when message (message "%s" message))
exitfun))
;;;; Defined in simple.el
(compat-defun char-uppercase-p (char) ;; <compat-tests:char-uppercase-p>
"Return non-nil if CHAR is an upper-case character.
If the Unicode tables are not yet available, e.g. during bootstrap,
then gives correct answers only for ASCII characters."
(cond ((unicode-property-table-internal 'lowercase)
(characterp (get-char-code-property char 'lowercase)))
((and (>= char ?A) (<= char ?Z)))))
(compat-defun use-region-noncontiguous-p () ;; <compat-tests:region-noncontiguous-p>
"Return non-nil for a non-contiguous region if `use-region-p'."
(and (use-region-p) (region-noncontiguous-p)))
(compat-defun use-region-beginning () ;; <compat-tests:use-region>
"Return the start of the region if `use-region-p'."
(and (use-region-p) (region-beginning)))
(compat-defun use-region-end () ;; <compat-tests:use-region>
"Return the end of the region if `use-region-p'."
(and (use-region-p) (region-end)))
(compat-defun get-scratch-buffer-create () ;; <compat-tests:get-scratch-buffer-create>
"Return the *scratch* buffer, creating a new one if needed."
(or (get-buffer "*scratch*")
(let ((scratch (get-buffer-create "*scratch*")))
;; Don't touch the buffer contents or mode unless we know that
;; we just created it.
(with-current-buffer scratch
(when initial-scratch-message
(insert (substitute-command-keys initial-scratch-message))
(set-buffer-modified-p nil))
(funcall initial-major-mode))
scratch)))
;;;; Defined in subr-x.el
(compat-defmacro with-buffer-unmodified-if-unchanged (&rest body) ;; <compat-tests:with-buffer-unmodified-if-unchanged>
"Like `progn', but change buffer-modified status only if buffer text changes.
If the buffer was unmodified before execution of BODY, and
buffer text after execution of BODY is identical to what it was
before, ensure that buffer is still marked unmodified afterwards.
For example, the following won't change the buffer's modification
status:
(with-buffer-unmodified-if-unchanged
(insert \"a\")
(delete-char -1))
Note that only changes in the raw byte sequence of the buffer text,
as stored in the internal representation, are monitored for the
purpose of detecting the lack of changes in buffer text. Any other
changes that are normally perceived as \"buffer modifications\", such
as changes in text properties, `buffer-file-coding-system', buffer
multibyteness, etc. -- will not be noticed, and the buffer will still
be marked unmodified, effectively ignoring those changes."
(declare (debug t) (indent 0))
(let ((hash (gensym))
(buffer (gensym)))
`(let ((,hash (and (not (buffer-modified-p))
(buffer-hash)))
(,buffer (current-buffer)))
(prog1
(progn
,@body)
;; If we didn't change anything in the buffer (and the buffer
;; was previously unmodified), then flip the modification status
;; back to "unchanged".
(when (and ,hash (buffer-live-p ,buffer))
(with-current-buffer ,buffer
(when (and (buffer-modified-p)
(equal ,hash (buffer-hash)))
(restore-buffer-modified-p nil))))))))
(compat-defun add-display-text-property (start end prop value ;; <compat-tests:add-display-text-property>
&optional object)
"Add display property PROP with VALUE to the text from START to END.
If any text in the region has a non-nil `display' property, those
properties are retained.
If OBJECT is non-nil, it should be a string or a buffer. If nil,
this defaults to the current buffer."
(let ((sub-start start)
(sub-end 0)
disp)
(while (< sub-end end)
(setq sub-end (next-single-property-change sub-start 'display object
(if (stringp object)
(min (length object) end)
(min end (point-max)))))
(if (not (setq disp (get-text-property sub-start 'display object)))
;; No old properties in this range.
(put-text-property sub-start sub-end 'display (list prop value)
object)
;; We have old properties.
(let ((vector nil))
;; Make disp into a list.
(setq disp
(cond
((vectorp disp)
(setq vector t)
(append disp nil))
((not (consp (car disp)))
(list disp))
(t
disp)))
;; Remove any old instances.
(when-let ((old (assoc prop disp)))
(setq disp (delete old disp)))
(setq disp (cons (list prop value) disp))
(when vector
(setq disp (vconcat disp)))
;; Finally update the range.
(put-text-property sub-start sub-end 'display disp object)))
(setq sub-start sub-end))))
(compat-defmacro while-let (spec &rest body) ;; <compat-tests:while-let>
"Bind variables according to SPEC and conditionally evaluate BODY.
Evaluate each binding in turn, stopping if a binding value is nil.
If all bindings are non-nil, eval BODY and repeat.
The variable list SPEC is the same as in `if-let*'."
(declare (indent 1) (debug if-let))
(let ((done (gensym "done")))
`(catch ',done
(while t
(if-let* ,spec
(progn
,@body)
(throw ',done nil))))))
;;;; Defined in files.el
(compat-defun directory-abbrev-make-regexp (directory) ;; <compat-tests:directory-abbrev-make-regexp>
"Create a regexp to match DIRECTORY for `directory-abbrev-alist'."
(let ((regexp
;; We include a slash at the end, to avoid spurious
;; matches such as `/usr/foobar' when the home dir is
;; `/usr/foo'.
(concat "\\`" (regexp-quote directory) "\\(/\\|\\'\\)")))
;; The value of regexp could be multibyte or unibyte. In the
;; latter case, we need to decode it.
(if (multibyte-string-p regexp)
regexp
(decode-coding-string regexp
(if (eq system-type 'windows-nt)
'utf-8
locale-coding-system)))))
(compat-defun directory-abbrev-apply (filename) ;; <compat-tests:directory-abbrev-apply>
"Apply the abbreviations in `directory-abbrev-alist' to FILENAME.
Note that when calling this, you should set `case-fold-search' as
appropriate for the filesystem used for 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)))))))
(compat-defun file-name-split (filename) ;; <compat-tests:file-name-split>
"Return a list of all the components of FILENAME.
On most systems, this will be true:
(equal (string-join (file-name-split filename) \"/\") filename)"
(let ((components nil))
;; If this is a directory file name, then we have a null file name
;; at the end.
(when (directory-name-p filename)
(push "" components)
(setq filename (directory-file-name filename)))
;; Loop, chopping off components.
(while (length> filename 0)
(push (file-name-nondirectory filename) components)
(let ((dir (file-name-directory filename)))
(setq filename (and dir (directory-file-name dir)))
;; If there's nothing left to peel off, we're at the root and
;; we can stop.
(when (and dir (equal dir filename))
(push (if (equal dir "") ""
;; On Windows, the first component might be "c:" or
;; the like.
(substring dir 0 -1))
components)
(setq filename nil))))
components))
(compat-defun file-attribute-file-identifier (attributes) ;; <compat-tests:file-attribute-getters>
"The inode and device numbers in ATTRIBUTES returned by `file-attributes'.
The value is a list of the form (INODENUM DEVICE), where DEVICE could be
either a single number or a cons cell of two numbers.
This tuple of numbers uniquely identifies the file."
(nthcdr 10 attributes))
(compat-defun file-name-parent-directory (filename) ;; <compat-tests:file-name-parent-directory>
"Return the directory name of the parent directory of FILENAME.
If FILENAME is at the root of the filesystem, return nil.
If FILENAME is relative, it is interpreted to be relative
to `default-directory', and the result will also be relative."
(let* ((expanded-filename (expand-file-name filename))
(parent (file-name-directory (directory-file-name expanded-filename))))
(cond
;; filename is at top-level, therefore no parent
((or (null parent)
;; `equal' is enough, we don't need to resolve symlinks here
;; with `file-equal-p', also for performance
(equal parent expanded-filename))
nil)
;; filename is relative, return relative parent
((not (file-name-absolute-p filename))
(file-relative-name parent))
(t
parent))))
(compat-defvar file-has-changed-p--hash-table ;; <compat-tests:file-has-changed-p>
(make-hash-table :test #'equal)
"Internal variable used by `file-has-changed-p'.")
(compat-defun file-has-changed-p (file &optional tag) ;; <compat-tests:file-has-changed-p>
"Return non-nil if FILE has changed.
The size and modification time of FILE are compared to the size
and modification time of the same FILE during a previous
invocation of `file-has-changed-p'. Thus, the first invocation
of `file-has-changed-p' always returns non-nil when FILE exists.
The optional argument TAG, which must be a symbol, can be used to
limit the comparison to invocations with identical tags; it can be
the symbol of the calling function, for example."
(let* ((file (directory-file-name (expand-file-name file)))
(remote-file-name-inhibit-cache t)
(fileattr (file-attributes file 'integer))
(attr (and fileattr
(cons (file-attribute-size fileattr)
(file-attribute-modification-time fileattr))))
(sym (concat (symbol-name tag) "@" file))
(cachedattr (gethash sym file-has-changed-p--hash-table)))
(unless (equal attr cachedattr)
(puthash sym attr file-has-changed-p--hash-table))))
;;;; Defined in keymap.el
(compat-defun key-valid-p (keys) ;; <compat-tests:key-valid-p>
"Say whether KEYS is a valid key.
A key is a string consisting of one or more key strokes.
The key strokes are separated by single space characters.
Each key stroke is either a single character, or the name of an
event, surrounded by angle brackets. In addition, any key stroke
may be preceded by one or more modifier keys. Finally, a limited
number of characters have a special shorthand syntax.
Here's some example key sequences.
\"f\" (the key `f')
\"S o m\" (a three key sequence of the keys `S', `o' and `m')
\"C-c o\" (a two key sequence of the keys `c' with the control modifier
and then the key `o')
\"H-<left>\" (the key named \"left\" with the hyper modifier)
\"M-RET\" (the \"return\" key with a meta modifier)
\"C-M-<space>\" (the \"space\" key with both the control and meta modifiers)
These are the characters that have shorthand syntax:
NUL, RET, TAB, LFD, ESC, SPC, DEL.
Modifiers have to be specified in this order:
A-C-H-M-S-s
which is
Alt-Control-Hyper-Meta-Shift-super"
(declare (pure t) (side-effect-free t))
(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 " "))
;; Every key might have these modifiers, and they should be
;; in this order.
(when (string-match (concat "\\`" prefixes) key)
(setq key (substring key (match-end 0))))
(unless (or (and (= (length key) 1)
;; Don't accept control characters as keys.
(not (< (aref key 0) ?\s))
;; Don't accept Meta'd characters as keys.
(or (multibyte-string-p key)
(not (<= 127 (aref key 0) 255))))
(and (string-match-p "\\`<[-_A-Za-z0-9]+>\\'" key)
;; Don't allow <M-C-down>.
(= (progn
(string-match
(concat "\\`<" prefixes) key)
(match-end 0))
1))
(string-match-p
"\\`\\(NUL\\|RET\\|TAB\\|LFD\\|ESC\\|SPC\\|DEL\\)\\'"
key))
;; Invalid.
(throw 'exit nil)))
t))))))
(compat-defun keymap--check (key) ;; <compat-tests:keymap--check>
"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)))
(compat-defun key-parse (keys) ;; <compat-tests:key-parse>
"Convert KEYS to the internal Emacs key representation.
See `kbd' for a descripion of KEYS."
(declare (pure t) (side-effect-free t))
;; A pure function is expected to preserve the match data.
(save-match-data
(let ((case-fold-search nil)
(len (length keys)) ; We won't alter keys in the loop below.
(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)
;; Try to catch events of the form "<as df>".
(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\\|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)
;; We used to accept . and ? here,
;; but . is simply wrong,
;; and C-? is not used (we use DEL instead).
(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)))
(compat-defun keymap-set (keymap key definition) ;; <compat-tests:defvar-keymap>
"Set KEY to DEFINITION in KEYMAP.
KEY is a string that satisfies `key-valid-p'.
DEFINITION is anything that can be a key's definition:
nil (means key is undefined in this keymap),
a command (a Lisp function suitable for interactive calling),
a string (treated as a keyboard macro),
a keymap (to define a prefix key),
a symbol (when the key is looked up, the symbol will stand for its
function definition, which should at that time be one of the above,
or another symbol whose function definition is used, etc.),
a cons (STRING . DEFN), meaning that DEFN is the definition
(DEFN should be a valid definition in its own right) and
STRING is the menu item name (which is used only if the containing
keymap has been created with a menu name, see `make-keymap'),
or a cons (MAP . CHAR), meaning use definition of CHAR in keymap MAP,
or an extended menu item definition.
(See info node `(elisp)Extended Menu Items'.)"
(keymap--check key)
(when (stringp definition)
(keymap--check definition)
(setq definition (key-parse definition)))
(define-key keymap (key-parse key) definition))
(compat-defun keymap-unset (keymap key &optional remove) ;; <compat-tests:keymap-unset>
"Remove key sequence KEY from KEYMAP.
KEY is a string that satisfies `key-valid-p'.
If REMOVE, remove the binding instead of unsetting it. This only
makes a difference when there's a parent keymap. When unsetting
a key in a child map, it will still shadow the same key in the
parent keymap. Removing the binding will allow the key in the
parent keymap to be used."
(keymap--check key)
(compat--define-key keymap (key-parse key) nil remove))
(compat-defun keymap-global-set (key command) ;; <compat-tests:keymap-global-set>
"Give KEY a global binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a string that satisfies `key-valid-p'.
Note that if KEY has a local binding in the current buffer,
that local binding will continue to shadow any global binding
that you make with this function.
NOTE: The compatibility version is not a command."
(keymap-set (current-global-map) key command))
(compat-defun keymap-local-set (key command) ;; <compat-tests:keymap-local-set>
"Give KEY a local binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a string that satisfies `key-valid-p'.
The binding goes in the current buffer's local map, which in most
cases is shared with all other buffers in the same major mode.
NOTE: The compatibility version is not a command."
(let ((map (current-local-map)))
(unless map
(use-local-map (setq map (make-sparse-keymap))))
(keymap-set map key command)))
(compat-defun keymap-global-unset (key &optional remove) ;; <compat-tests:keymap-global-unset>
"Remove global binding of KEY (if any).
KEY is a string that satisfies `key-valid-p'.
If REMOVE (interactively, the prefix arg), remove the binding
instead of unsetting it. See `keymap-unset' for details.
NOTE: The compatibility version is not a command."
(keymap-unset (current-global-map) key remove))
(compat-defun keymap-local-unset (key &optional remove) ;; <compat-tests:keymap-local-unset>
"Remove local binding of KEY (if any).
KEY is a string that satisfies `key-valid-p'.
If REMOVE (interactively, the prefix arg), remove the binding
instead of unsetting it. See `keymap-unset' for details.
NOTE: The compatibility version is not a command."
(when (current-local-map)
(keymap-unset (current-local-map) key remove)))
(compat-defun keymap-substitute (keymap olddef newdef &optional oldmap prefix) ;; <compat-tests:keymap-substitute>