-
Notifications
You must be signed in to change notification settings - Fork 279
/
evil-common.el
3837 lines (3570 loc) · 154 KB
/
evil-common.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
;;; evil-common.el --- Common functions and utilities -*- lexical-binding: t -*-
;; Author: Vegard Øye <vegard_oye at hotmail.com>
;; Maintainer: Vegard Øye <vegard_oye at hotmail.com>
;; Version: 1.15.0
;;
;; This file is NOT part of GNU Emacs.
;;; License:
;; This file is part of Evil.
;;
;; Evil 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.
;;
;; Evil 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 Evil. If not, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'evil-vars)
(require 'rect)
(require 'thingatpt)
(require 'cl-lib)
(declare-function evil-visual-state-p "evil-states")
(declare-function evil-visual-restore "evil-states")
(declare-function evil-motion-state "evil-states")
(declare-function evil-replace-state-p "evil-states")
(declare-function evil-set-jump "evil-jumps")
;;; Compatibility with different Emacs versions
;; x-set-selection and x-get-selection have been deprecated since 25.1
;; by gui-set-selection and gui-get-selection
(defalias 'evil-get-selection
(if (fboundp 'gui-get-selection) 'gui-get-selection 'x-get-selection))
(defalias 'evil-set-selection
(if (fboundp 'gui-set-selection) 'gui-set-selection 'x-set-selection))
(defmacro evil-with-delay (condition hook &rest body)
"Execute BODY when CONDITION becomes true, checking with HOOK.
HOOK can be a simple symbol or of the form (HOOK APPEND LOCAL NAME)
where:
NAME specifies the name of the entry added to HOOK.
If APPEND is non-nil, the entry is appended to the hook.
If LOCAL is non-nil, the buffer-local value of HOOK is modified."
(declare (debug (form sexp body)) (indent 2))
(cl-destructuring-bind (hook-sym &optional append local name)
(mapcar #'macroexp-quote (if (consp hook) hook (list hook)))
(macroexp-let2* nil
((fun-name `(make-symbol
,(or name (format "evil-delay-in-%s" hook-sym))))
;; `apply-partially' is used in case this macro is expanded
;; (via `evil-define-key') in a file which still does not
;; activate `lexical-binding'.
(fun `(apply-partially
(lambda (name &rest _)
(when ,(or condition t)
(remove-hook ,hook-sym name ,local)
,@body
t))
,fun-name)))
`(unless ,(and condition `(funcall ,fun))
(progn (fset ,fun-name ,fun)
,@(when local `((put ,fun-name 'permanent-local-hook t)))
(add-hook ,hook-sym ,fun-name ,append ,local))))))
(defun evil-delay (condition form hook &optional append local name)
"Execute FORM when CONDITION becomes true, checking with HOOK.
NAME specifies the name of the entry added to HOOK. If APPEND is
non-nil, the entry is appended to the hook. If LOCAL is non-nil,
the buffer-local value of HOOK is modified."
(declare (obsolete evil-with-delay "1.15.0") (indent 2))
(eval `(evil-with-delay ,condition (,hook ,append ,local ,name) ,form) t))
;;; List functions
(defmacro evil--add-to-alist (alist &rest elements)
"Add the association of KEY and VAL to the value of ALIST.
If the list already contains an entry for KEY, update that entry;
otherwise prepend it to the list.
\(fn ALIST [KEY VAL]...)"
`(progn
,@(cl-loop
for (key val) on elements by #'cddr collect
(if (< emacs-major-version 26)
(macroexp-let2* nil ((k key) (p `(assoc ,k ,alist)))
`(if ,p (setcdr ,p ,val)
(push (cons ,k ,val) ,alist)))
`(setf (alist-get ,key ,alist nil nil #'equal) ,val)))
,alist))
;; custom version of `delete-if'
(defun evil-filter-list (predicate list &optional pointer)
"Delete by side-effect all items satisfying PREDICATE in LIST.
Stop when reaching POINTER. If the first item satisfies PREDICATE,
there is no way to remove it by side-effect; therefore, write
\(setq foo (evil-filter-list #\\='predicate foo)) to be sure of
changing the value of `foo'."
(let ((tail list) elt head)
(while (and tail (not (eq tail pointer)))
(setq elt (car tail))
(cond
((funcall predicate elt)
(setq tail (cdr tail))
(if head
(setcdr head tail)
(setq list tail)))
(t
(setq head tail
tail (cdr tail)))))
list))
(defun evil-member-if (predicate list &optional pointer)
"Find the first item satisfying PREDICATE in LIST.
Stop when reaching POINTER, which should point at a link
in the list."
(let (elt)
(catch 'done
(while (and (consp list) (not (eq list pointer)))
(setq elt (car list))
(if (funcall predicate elt)
(throw 'done elt)
(setq list (cdr list)))))))
(defun evil-member-recursive-if (predicate tree)
"Find the first item satisfying PREDICATE in TREE."
(declare (obsolete nil "1.15.0"))
(cond
((funcall predicate tree)
tree)
((listp tree)
(catch 'done
(dolist (elt tree)
(when (setq elt (evil-member-recursive-if predicate elt))
(throw 'done elt)))))))
(defun evil-concat-lists (&rest sequences)
"Concatenate lists, removing duplicates.
Elements are compared with `eq'."
(let (result)
(dolist (sequence sequences)
(dolist (elt sequence)
(push elt result)))
(nreverse (cl-remove-duplicates result :test #'eq))))
(defun evil-concat-alists (&rest sequences)
"Concatenate association lists, removing duplicates.
An alist is a list of cons cells (KEY . VALUE) where each key
may occur only once. Later values overwrite earlier values."
(let (result)
(dolist (sequence sequences)
(dolist (elt sequence)
(setq result (assq-delete-all (car-safe elt) result))
(push elt result)))
(nreverse result)))
(defun evil-concat-plists (&rest sequences)
"Concatenate property lists, removing duplicates.
A property list is a list (:KEYWORD1 VALUE1 :KEYWORD2 VALUE2...)
where each keyword may occur only once. Later values overwrite
earlier values."
(let (result)
(dolist (sequence sequences result)
(while sequence
(setq result
(plist-put result (pop sequence) (pop sequence)))))))
(defun evil-concat-keymap-alists (&rest sequences)
"Concatenate keymap association lists, removing duplicates.
A keymap alist is a list of cons cells (VAR . MAP) where each keymap
may occur only once, but where the variables may be repeated
\(e.g., (VAR . MAP1) (VAR . MAP2) is allowed). The order matters,
with the highest priority keymaps being listed first."
(let (result)
(dolist (sequence sequences)
(dolist (elt sequence)
(unless (rassq (cdr-safe elt) result)
(push elt result))))
(nreverse result)))
(defun evil-plist-delete (prop plist)
"Delete by side effect the property PROP from PLIST.
If PROP is the first property in PLIST, there is no way
to remove it by side-effect; therefore, write
\(setq foo (evil-plist-delete :prop foo)) to be sure of
changing the value of `foo'."
(let ((tail plist) elt head)
(while tail
(setq elt (car tail))
(cond
((eq elt prop)
(setq tail (cdr (cdr tail)))
(if head
(setcdr (cdr head) tail)
(setq plist tail)))
(t
(setq head tail
tail (cdr (cdr tail))))))
plist))
(defun evil-get-property (alist key &optional prop)
"Return property PROP for KEY in ALIST.
ALIST is an association list with entries of the form
\(KEY . PLIST), where PLIST is a property list.
If PROP is nil, return all properties for KEY.
If KEY is t, return an association list of keys
and their PROP values."
(declare (obsolete nil "1.15.0"))
(cond
((null prop)
(cdr (assq key alist)))
((eq key t)
(let (result val)
(dolist (entry alist result)
(setq key (car entry)
val (cdr entry))
(when (plist-member val prop)
(setq val (plist-get val prop))
(push (cons key val) result)))))
(t
(plist-get (cdr (assq key alist)) prop))))
(defun evil-put-property (alist-var key prop val &rest properties)
"Set PROP to VAL for KEY in ALIST-VAR.
ALIST-VAR points to an association list with entries of the form
\(KEY . PLIST), where PLIST is a property list storing PROP and VAL."
(declare (obsolete nil "1.15.0"))
(set alist-var
(let* ((alist (symbol-value alist-var))
(plist (cdr (assq key alist))))
(setq plist (plist-put plist prop val))
(when properties
(setq plist (evil-concat-plists plist properties)
val (car (last properties))))
(setq alist (assq-delete-all key alist))
(push (cons key plist) alist)))
val)
(defun evil-state-property (state prop &optional value)
"Return the value of property PROP for STATE.
PROP is a keyword as used by `evil-define-state'. STATE is the state's
symbolic name. If VALUE is non-nil and the value is a variable, return
the value of that variable.
If STATE is t, return an association list of states and their PROP
values instead."
(if (eq state t)
(cl-loop for (key . plist) in evil-state-properties with result do
(let ((p (plist-member plist prop)))
(when p (push (cons key (cadr p)) result)))
finally return result)
(let ((val (plist-get (cdr (assq state evil-state-properties)) prop)))
(if (and value (symbolp val) (boundp val))
(symbol-value val)
val))))
(eval-and-compile (defalias 'evil-swap #'cl-rotatef))
(defmacro evil-sort (&rest vars)
"Sort the symbol values of VARS.
Place the smallest value in the first argument and the largest in the
last, sorting in between."
(if (= (length vars) 2)
`(when (> ,@vars) (evil-swap ,@vars))
(let ((sorted (make-symbol "sortvar")))
`(let ((,sorted (sort (list ,@vars) #'<)))
(setq ,@(apply #'nconc
(mapcar (lambda (var) (list var `(pop ,sorted)))
vars)))))))
(defun evil-vector-to-string (vector)
"Turn VECTOR into a string, changing <escape> to \"\\e\"."
(mapconcat (lambda (c) (if (eq c 'escape) "\e" (list c)))
vector
""))
;;; Command properties
(defmacro evil-define-command (command &rest body)
"Define a command COMMAND.
\(fn COMMAND (ARGS...) DOC [[KEY VALUE]...] BODY...)"
(declare (indent defun)
(doc-string 3)
(debug (&define name
[&optional lambda-list]
[&optional stringp]
[&rest keywordp sexp]
[&optional ("interactive" [&rest form])]
def-body)))
(let ((interactive '(interactive))
args doc doc-form keys)
;; collect arguments
(when (listp (car body))
(setq args (pop body)))
;; collect docstring
(cond ((stringp (car body)) (setq doc (pop body)))
((eq (car-safe (car body)) #'format) (setq doc-form (pop body))))
;; collect keywords
(while (keywordp (car body))
(let* ((key (pop body))
(arg (pop body)))
(setq keys (plist-put keys key arg)))) ; TODO: add keyword check
;; collect `interactive' form
(when (eq (caar body) 'interactive)
(cl-destructuring-bind (form . attrs)
(apply #'evil-interactive-form (cdr (pop body)))
(setq interactive `(interactive ,form)
keys (evil-concat-plists keys attrs))))
`(progn
;; the compiler does not recognize `defun' inside `let'
,(when (and command body)
`(defun ,command ,args
,@(when doc `(,doc))
,interactive
,@body))
,(when (and command doc-form)
`(put ',command 'function-documentation ,doc-form))
;; set command properties for symbol or lambda function
(let ((func ,(if (and (null command) body)
`(lambda ,args
,interactive
,@body)
`#',command)))
(apply #'evil-set-command-properties func ',keys)
func))))
(define-obsolete-variable-alias
'evil-command-properties 'evil--command-properties "1.15.0")
(defvar evil--command-properties nil
"Specifications made by `evil-define-command'.")
(defun evil-command-properties (command)
"Return the Evil command property list for COMMAND.
See also `evil-get-command-property'."
(if (symbolp command) (get command 'evil--command-plist)
(cdr (assq command evil--command-properties))))
(define-obsolete-function-alias
'evil-get-command-properties #'evil-command-properties "1.15.0")
(gv-define-setter evil-command-properties (val command)
`(if (symbolp ,command) (put ,command 'evil--command-plist ,val)
,(macroexp-let2 nil p `(assq ,command evil--command-properties)
`(if ,p (setcdr ,p ,val)
(push (cons ,command ,val) evil--command-properties)))))
(defalias 'evil-has-command-properties-p #'evil-command-properties
"Whether Evil properties are defined for COMMAND.
See also `evil-has-command-property-p'.")
(defun evil-has-command-property-p (command property)
"Whether COMMAND has Evil PROPERTY.
See also `evil-has-command-properties-p'."
(plist-member (evil-command-properties command) property))
(defun evil-get-command-property (command property &optional default)
"Return the value of Evil PROPERTY of COMMAND.
If the command does not have the property, return DEFAULT.
See also `evil-get-command-properties'."
(let ((p (plist-member (evil-command-properties command) property)))
(if p (cadr p) default)))
(defun evil-add-command-properties (command &rest properties)
"Set each Evil command property KEY to its VAL for COMMAND.
To replace existing properties, use `evil-set-command-properties'.
\(fn COMMAND [KEY VAL]...)"
(let ((props (evil-command-properties command)))
(while properties
(setq props (plist-put props (pop properties) (pop properties))))
(setf (evil-command-properties command) props)))
(defalias 'evil-set-command-property #'evil-add-command-properties
"Set PROPERTY to VALUE for COMMAND.
To set multiple properties at once, see
`evil-set-command-properties' and `evil-add-command-properties'.
\(fn COMMAND PROPERTY VALUE)")
(defalias 'evil-put-command-property #'evil-set-command-property)
(defun evil-set-command-properties (command &rest properties)
"Replace all of COMMAND's properties with PROPERTIES.
PROPERTIES should be a property list.
This erases all previous properties; to only add properties,
use `evil-set-command-property'."
(setf (evil-command-properties command) properties))
(defun evil-remove-command-properties (command &rest properties)
"Remove PROPERTIES from COMMAND.
PROPERTIES should be a list of properties (:PROP1 :PROP2 ...).
If PROPERTIES is the empty list, all properties are removed."
(let (plist)
(when properties
(setq plist (evil-command-properties command))
(dolist (property properties)
(setq plist (evil-plist-delete property plist))))
(apply #'evil-set-command-properties command plist)))
(defun evil-yank-handler (&optional motion)
"Return the yank handler for MOTION.
MOTION defaults to the current motion."
(evil-get-command-property (or motion evil-this-motion) :yank-handler))
(defun evil-declare-motion (command)
"Declare COMMAND to be a movement function.
This ensures that it behaves correctly in visual state."
(evil-add-command-properties command :keep-visual t :repeat 'motion))
(defun evil-declare-repeat (command)
"Declare COMMAND to be repeatable."
(evil-add-command-properties command :repeat t))
(defun evil-declare-not-repeat (command)
"Declare COMMAND to be nonrepeatable."
(evil-add-command-properties command :repeat nil))
(defalias 'evil-declare-ignore-repeat #'evil-declare-not-repeat)
(defun evil-declare-change-repeat (command)
"Declare COMMAND to be repeatable by buffer changes rather than
keystrokes."
(evil-add-command-properties command :repeat 'change))
(defun evil-declare-insert-at-point-repeat (command)
"Declare COMMAND to be repeatable by buffer changes."
(evil-add-command-properties command :repeat 'insert-at-point))
(defun evil-declare-abort-repeat (command)
"Declare COMMAND to be nonrepeatable."
(evil-add-command-properties command :repeat 'abort))
(defun evil-delimited-arguments (string &optional count)
"Parse STRING as a sequence of delimited arguments.
Return a list of COUNT strings, or as many arguments as the string
contains. The first non-blank character is taken to be the delimiter.
If some arguments are missing from STRING, the resulting list is
padded with nil values. Two delimiters following directly after each
other gives an empty string."
(unless count (setq count -1))
(let ((idx 0) delim regexp result)
(when (string-match "^[[:space:]]*\\([^[:space:]]\\)" string)
(setq delim (match-string 1 string)
regexp (format "%s\\(\\(?:\\\\.\\|[^%s]\\)*\\)"
(regexp-quote delim) delim))
(while (and (/= count 0) (string-match regexp string idx)
(/= (match-beginning 1) (length string)))
(setq idx (match-end 0)
count (1- count))
(push
(if (when (= count 0)
(not (string-match-p
(concat (regexp-quote delim) "[[:space:]]*$")
string idx)))
(substring string (match-beginning 1))
(match-string 1 string))
result)))
(dotimes (_ count) (push nil result))
(nreverse result)))
(defun evil-concat-charsets (&rest sets)
"Concatenate character sets.
A character set is the part between [ and ] in a regular expression.
If any character set is complemented, the result is also complemented."
(let ((bracket "") (complement "") (hyphen "") result)
(dolist (set sets)
(when (string-match-p "^\\^" set)
(setq set (substring set 1)
complement "^"))
(when (string-match-p "^]" set)
(setq set (substring set 1)
bracket "]"))
(when (string-match-p "^-" set)
(setq set (substring set 1)
hyphen "-"))
(setq result (concat result set)))
(format "%s%s%s%s" complement bracket hyphen result)))
;;; Key sequences
(defun evil-keypress-parser (&optional input)
"Read from keyboard or INPUT and build a command description.
Return (CMD COUNT), where COUNT is the numeric prefix argument.
Both COUNT and CMD may be nil."
(when input (setq unread-command-events (append input unread-command-events)))
(let (count negative)
(catch 'done
(while t
(let ((seq (read-key-sequence "")))
(when seq
(let ((cmd (key-binding seq)))
(cond
((null cmd) (throw 'done (list nil nil)))
((arrayp cmd) ; keyboard macro, recursive call
(let ((cmd (evil-keypress-parser cmd)))
(throw 'done
(list (car cmd)
(if (or count (cadr cmd))
(list (car cmd) (* (or count 1)
(or (cadr cmd) 1))))))))
((or (eq cmd #'digit-argument)
(and (equal seq "0") count))
(let* ((event (aref seq (1- (length seq))))
(char (or (when (characterp event) event)
(when (symbolp event)
(get event 'ascii-character))))
(digit (when (integerp char) (- (logand char ?\177) ?0))))
(setq count (+ (* 10 (or count 0)) digit))))
((eq cmd #'negative-argument)
(setq negative (not negative)))
(t
(throw 'done (list cmd
(and count
(* count
(if negative -1 1))))))))))))))
(defun evil-read-key (&optional prompt)
"Read a key from the keyboard.
Translates it according to the input method."
(let ((old-global-map (current-global-map))
(new-global-map (make-sparse-keymap))
(overriding-terminal-local-map nil)
(overriding-local-map evil-read-key-map)
seq char cmd)
(unwind-protect
(condition-case nil
(progn
(define-key new-global-map [menu-bar]
(lookup-key global-map [menu-bar]))
(define-key new-global-map [tab-bar]
(lookup-key global-map [tab-bar]))
(define-key new-global-map [tool-bar]
(lookup-key global-map [tool-bar]))
(setq new-global-map
(append new-global-map
(list (make-char-table 'display-table
'self-insert-command))))
(use-global-map new-global-map)
(setq seq (read-key-sequence prompt nil t)
char (aref seq 0)
cmd (key-binding seq))
(while (arrayp cmd)
(setq char (aref cmd 0)
cmd (key-binding cmd)))
(cond
((eq cmd 'self-insert-command) char)
(cmd (call-interactively cmd))
(t (user-error "No replacement character typed"))))
(quit
(when (fboundp 'evil-repeat-abort)
(evil-repeat-abort))
(signal 'quit nil)))
(use-global-map old-global-map))))
(defun evil-read-quoted-char ()
"Command that calls `read-quoted-char'.
This command can be used wherever `read-quoted-char' is required
as a command. Its main use is in the `evil-read-key-map'."
(interactive)
(read-quoted-char))
(defvar evil-digraph-read-key-keymap
(let ((map (make-sparse-keymap))
(n ?0))
(while (<= n ?9)
(define-key map (vector (intern (concat "kp-" (string n)))) nil)
(cl-incf n))
map)
"By default, used to exclude otherwise disabled fallbacks.")
(declare-function evil-digraph "evil-digraphs")
(defun evil-read-digraph-char-with-overlay (overlay)
"Read two chars, displaying the first in OVERLAY, replacing \"?\".
Return the digraph from `evil-digraph', else return second char."
(interactive)
(unwind-protect
(let ((read-key-empty-map
(let ((map (copy-keymap evil-digraph-read-key-keymap)))
(set-keymap-parent map read-key-empty-map)
;; Disable read-key-sequence unbound fallbacks, e.g. downcasing
(define-key map [t] 'dummy)
map))
char1 char2)
;; create overlay prompt
(overlay-put overlay 'invisible t)
(overlay-put overlay 'after-string
#("?" 0 1 (face minibuffer-prompt cursor 1)))
(setq char1 (read-key))
(overlay-put overlay 'after-string
(propertize (char-to-string char1)
'face 'minibuffer-prompt
'cursor 1))
(setq char2 (read-key))
(or (evil-digraph (list char1 char2))
;; use the last character if undefined
char2))
(delete-overlay overlay)))
(defun evil-read-digraph-char (&optional hide-chars)
"Read two keys from keyboard forming a digraph.
This function creates an overlay at (point), hiding the next
HIDE-CHARS characters. HIDE-CHARS defaults to 1."
(interactive)
(let ((overlay (make-overlay
(point) (min (+ (point) (or hide-chars 1))
(point-max)))))
(evil-read-digraph-char-with-overlay overlay)))
(defun evil-read-motion (&optional motion count type modifier)
"Read a MOTION, motion COUNT and motion TYPE from the keyboard.
The type may be overridden with MODIFIER, which may be a type
or a Visual selection as defined by `evil-define-visual-selection'.
Return a list (MOTION COUNT [TYPE])."
(let (command prefix)
(setq evil-this-type-modified nil)
(unless motion
(while (progn
(setq command (evil-keypress-parser)
motion (pop command)
prefix (pop command))
(when prefix
(setq count
(if count
(string-to-number
(concat (number-to-string count)
(number-to-string prefix)))
prefix)))
;; if the command is a type modifier, read more
(when (rassq motion evil-visual-alist)
(setq modifier
(or modifier
(car (rassq motion evil-visual-alist))))))))
(when modifier
(setq type (or type (evil-type motion 'exclusive)))
(cond
((eq modifier 'char)
;; TODO: this behavior could be less hard-coded
(setq type (if (eq type 'exclusive) 'inclusive 'exclusive)))
(t (setq type modifier)))
(setq evil-this-type-modified type))
(list motion count type)))
(defun evil-mouse-events-p (keys)
"Return non-nil iff KEYS contains a mouse event."
(cl-loop for key across keys thereis
(or (mouse-event-p key)
(mouse-movement-p key))))
(defun evil-extract-count (keys)
"Split the key-sequence KEYS into prefix-argument and the rest.
Return the list (PREFIX CMD SEQ REST), where PREFIX is the
prefix count, CMD the command to be executed, SEQ the subsequence
calling CMD, and REST is all remaining events in the
key-sequence. PREFIX and REST may be nil if they do not exist.
If a command is bound to some keyboard macro, it is expanded
recursively."
(catch 'done
(let ((len (length keys))
(beg 0)
(end 1)
found-prefix)
(while (<= end len)
(let* ((seq (substring keys beg end))
(cmd (key-binding seq)))
(cond
((memq cmd '(undefined nil))
(user-error "No command bound to `%s'" seq))
((arrayp cmd) ; keyboard macro, replace command with macro
(setq keys (vconcat (substring keys 0 beg)
cmd
(substring keys end))
end (1+ beg)
len (length keys)))
((functionp cmd)
(if (or (memq cmd '(digit-argument negative-argument))
(and found-prefix
(equal (vconcat seq) (vector ?0))))
;; skip those commands
(setq found-prefix t ; found at least one prefix argument
beg end
end (1+ end))
;; a real command, finish
(throw 'done
(list (unless (zerop beg)
(string-to-number
(concat (substring keys 0 beg))))
cmd
seq
(when (< end len)
(substring keys end))))))
(t ; append a further event
(setq end (1+ end))))))
(user-error "Key sequence contains no complete binding"))))
(defun evil-extract-append (file-or-append)
"Return an (APPEND . FILENAME) pair based on FILE-OR-APPEND.
FILE-OR-APPEND should either be a filename or a \">> FILE\"
directive. APPEND will be t if FILE-OR-APPEND is an append
directive and nil otherwise. FILENAME will be the extracted
filename."
(if (and (stringp file-or-append)
(string-match "\\(>> *\\)" file-or-append))
(cons t (substring file-or-append (match-end 1)))
(cons nil file-or-append)))
(defun evil-set-keymap-prompt (map prompt)
"Set the prompt-string of MAP to PROMPT."
(delq (keymap-prompt map) map)
(when prompt
(setcdr map (cons prompt (cdr map)))))
(defun evil-lookup-key (map key)
"Return non-nil value if KEY is bound in MAP."
(let ((definition (lookup-key map key)))
(unless (numberp definition) ; in-band error
definition)))
;;; Display
(defun evil-set-cursor (specs)
"Change the cursor's apperance according to SPECS.
SPECS may be a cursor type as per `cursor-type', a color
string as passed to `set-cursor-color', a zero-argument
function for changing the cursor, or a list of the above."
(unless (and (not (functionp specs))
(listp specs)
(null (cdr-safe (last specs))))
(setq specs (list specs)))
(dolist (spec specs)
(cond
((functionp spec)
(ignore-errors (funcall spec)))
((stringp spec)
(evil-set-cursor-color spec))
(t
(setq cursor-type spec)))))
(defun evil-set-cursor-color (color)
"Set the cursor color to COLOR."
(unless (equal (frame-parameter nil 'cursor-color) color)
;; `set-cursor-color' forces a redisplay, so only
;; call it when the color actually changes
(set-cursor-color color)))
(defun evil-refresh-cursor (&optional state buffer)
"Refresh the cursor for STATE in BUFFER.
BUFFER defaults to the current buffer. If STATE is nil the
cursor type is either `evil-force-cursor' or the current state."
(defvar evil-local-mode)
(when evil-local-mode
(let* ((state (or state evil-force-cursor evil-state 'normal))
(default (or evil-default-cursor t))
(cursor (evil-state-property state :cursor t))
(color (or (and (stringp cursor) cursor)
(and (listp cursor) (evil-member-if #'stringp cursor))
(frame-parameter nil 'cursor-color))))
(with-current-buffer (or buffer (current-buffer))
;; if both STATE and `evil-default-cursor'
;; specify a color, don't set it twice
(evil-set-cursor (if (and color (listp default))
(cl-remove-if #'stringp default)
default))
(evil-set-cursor cursor)))))
(defmacro evil-save-cursor (&rest body)
"Save the current cursor; execute BODY; restore the cursor."
(declare (indent defun) (debug t) (obsolete nil "1.15.0"))
`(let ((cursor cursor-type)
(color (frame-parameter (selected-frame) 'cursor-color))
(inhibit-quit t))
(unwind-protect
(progn ,@body)
(setq cursor-type cursor)
(evil-set-cursor-color color))))
(defun evil-echo (string &rest args)
"Display an unlogged message in the echo area.
That is, the message is not logged in the *Messages* buffer.
\(To log the message, just use `message'.)"
(unless evil-no-display
(let (message-log-max)
(apply #'message string args))))
(defun evil-echo-area-save ()
"Save the current echo area in `evil-echo-area-message'."
(setq evil-echo-area-message (current-message)))
(defun evil-echo-area-restore ()
"Restore the echo area from `evil-echo-area-message'.
Does not restore if `evil-write-echo-area' is non-nil."
(unless evil-write-echo-area
(if evil-echo-area-message
(message "%s" evil-echo-area-message)
(message nil)))
(setq evil-echo-area-message nil
evil-write-echo-area nil))
;; toggleable version of `with-temp-message'
(defmacro evil-save-echo-area (&rest body)
"Save the echo area; execute BODY; restore the echo area.
Intermittent messages are not logged in the *Messages* buffer."
(declare (indent defun) (debug t))
`(let ((inhibit-quit t)
evil-echo-area-message evil-write-echo-area)
(evil-echo-area-save)
(unwind-protect
(progn ,@body)
(evil-echo-area-restore))))
(defmacro evil-without-display (&rest body)
"Execute BODY without Evil displays.
Inhibits echo area messages, mode line updates and cursor changes."
(declare (indent defun)
(debug t))
`(let ((evil-no-display t))
,@body))
(defun evil-count-lines (beg end)
"Return absolute line-number-difference betweeen BEG and END.
This should give the same results no matter where on the line BEG
and END are."
(if (= beg end)
0
(let ((end-at-bol (save-excursion (goto-char (max beg end))
(bolp))))
(if end-at-bol
(count-lines beg end)
(1- (count-lines beg end))))))
;;; Movement
(defun evil-normalize-position (pos)
"Return POS if it does not exceed the buffer boundaries.
If POS is less than `point-min', return `point-min'.
Is POS is more than `point-max', return `point-max'.
If POS is a marker, return its position."
(cond
((not (number-or-marker-p pos))
pos)
((< pos (point-min))
(point-min))
((> pos (point-max))
(point-max))
((markerp pos)
(marker-position pos))
(t
pos)))
(defmacro evil-save-goal-column (&rest body)
"Restore the goal column after execution of BODY.
See also `evil-save-column'."
(declare (indent defun)
(debug t))
`(let ((goal-column goal-column)
(temporary-goal-column temporary-goal-column))
,@body))
(defmacro evil-save-column (&rest body)
"Restore the column after execution of BODY.
See also `evil-save-goal-column'."
(declare (indent defun)
(debug t))
`(let ((col (current-column)))
(evil-save-goal-column
,@body
(move-to-column col))))
(defun evil--stick-to-eol-p ()
"Called by vertical movement commands to help determine cursor position."
(and evil-track-eol
(eq (or goal-column temporary-goal-column) most-positive-fixnum)
(memq last-command '(next-line previous-line))))
(defun evil-eolp ()
"Like `eolp' but accounts for `evil-move-beyond-eol' being nil."
(ignore-errors
(save-excursion
(unless (or evil-move-beyond-eol (memq evil-state '(insert replace)))
(forward-char))
(eolp))))
(defmacro evil-ensure-column (&rest body)
"Execute BODY so that column after execution is correct.
If `evil-start-of-line' is nil, treat BODY as if it were a `next-line' command.
This mostly copies the approach of Emacs' `line-move-1', but is modified
so it is more compatible with Evil's notion of EOL tracking."
(declare (indent defun) (debug t))
`(progn
(unless evil-start-of-line
(setq this-command 'next-line
temporary-goal-column
(cond ((memq last-command '(next-line previous-line))
temporary-goal-column)
((and track-eol (eolp) (not (bolp))) most-positive-fixnum)
(t (current-column)))))
,@body
(if evil-start-of-line
(evil-first-non-blank)
(line-move-to-column
(or goal-column
(if (consp temporary-goal-column)
;; Guard against a negative value as `temporary-goal-column'
;; may have a negative component when both `whitespace-mode'
;; and `display-line-numbers-mode' are enabled (#1297).
(max 0 (+ (truncate (car temporary-goal-column))
(cdr temporary-goal-column)))
temporary-goal-column))))))
(defun evil-narrow (beg end)
"Restrict the buffer to BEG and END.
BEG or END may be nil, specifying a one-sided restriction including
`point-min' or `point-max'. See also `evil-with-restriction.'"
(declare (obsolete nil "1.15.0"))
(narrow-to-region
(if beg (max beg (point-min)) (point-min))
(if end (min end (point-max)) (point-max))))
(defmacro evil-with-restriction (beg end &rest body)
"Execute BODY with the buffer narrowed to BEG and END.
BEG or END may be nil to specify a one-sided restriction."
(declare (indent 2) (debug t))
`(save-restriction
(let ((evil-restriction-stack
(cons (cons (point-min) (point-max)) evil-restriction-stack)))
(narrow-to-region (or ,beg (point-min)) (or ,end (point-max)))
,@body)))
(defmacro evil-without-restriction (&rest body)
"Execute BODY with the top-most narrowing removed.
This works only if the previous narrowing has been generated by
`evil-with-restriction'."
(declare (indent defun) (debug t))
`(save-restriction
(widen)
(narrow-to-region (car (car evil-restriction-stack))
(cdr (car evil-restriction-stack)))
(let ((evil-restriction-stack (cdr evil-restriction-stack)))
,@body)))
(defmacro evil-narrow-to-field (&rest body)
"Narrow to the current field."
(declare (indent defun)
(debug t))
`(evil-with-restriction (field-beginning) (field-end)
,@body))
(defun evil-move-beginning-of-line (&optional arg)
"Move to the beginning of the line as displayed.
Like `move-beginning-of-line', but retains the goal column."
(evil-save-goal-column
(move-beginning-of-line arg)
(beginning-of-line)))
(defun evil-move-end-of-line (&optional arg)
"Move to the end of the line as displayed.
Like `move-end-of-line', but retains the goal column."
(evil-save-goal-column
(move-end-of-line arg)
(end-of-line)))
(defun evil-adjust-cursor (&optional _)
"Move point one character back if at the end of a non-empty line.
This behavior is controlled by `evil-move-beyond-eol'."
(and (not evil-move-beyond-eol)
(eolp)
(evil-move-cursor-back t)))
(defun evil-move-cursor-back (&optional force)
"Move point one character back within the current line.
Contingent on the variable `evil-move-cursor-back' or the FORCE
argument. Movement is constrained to the current field."
(or (not (or evil-move-cursor-back force))
(bolp)
(when (bound-and-true-p visual-line-mode)
(= (point) (save-excursion (vertical-motion 0) (point))))
(goto-char (constrain-to-field (1- (point)) (point)))))
(defun evil-line-position (line &optional column)
"Return the position of LINE.
If COLUMN is specified, return its position on the line.
A negative number means the end of the line."
(save-excursion
(goto-char (point-min))
(forward-line (1- line))
(when (numberp column)
(if (< column 0)
(forward-line)
(move-to-column column)))
(point)))