forked from bonega/evil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evil-common.el
3222 lines (2991 loc) · 121 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
;; Author: Vegard Øye <vegard_oye at hotmail.com>
;; Maintainer: Vegard Øye <vegard_oye at hotmail.com>
;; Version: 0.0.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/>.
(require 'evil-vars)
(require 'rect)
;;; Code:
(declare-function evil-visual-state-p "evil-states")
;;; Compatibility for Emacs 23
(unless (fboundp 'deactivate-input-method)
(defalias 'deactivate-input-method 'inactivate-input-method))
(unless (boundp 'input-method-deactivate-hook)
(defvaralias 'input-method-deactivate-hook 'input-method-inactivate-hook))
(condition-case nil
(require 'windmove)
(error
(message "evil: Could not load `windmove', \
window commands not available.")
nil))
(when (and (require 'undo-tree nil t)
(fboundp 'global-undo-tree-mode))
(global-undo-tree-mode 1))
;;; Compatibility with different Emacs versions
(defmacro evil-called-interactively-p ()
"Wrapper for `called-interactively-p'.
In older versions of Emacs, `called-interactively-p' takes
no arguments. In Emacs 23.2 and newer, it takes one argument."
(if (version< emacs-version "23.2")
'(called-interactively-p)
'(called-interactively-p 'any)))
(unless (fboundp 'region-active-p)
(defun region-active-p ()
"Returns t iff region and mark are active."
(and transient-mark-mode mark-active)))
;; Emacs <23 does not know `characterp'
(unless (fboundp 'characterp)
(defalias 'characterp 'char-valid-p))
;; `make-char-table' requires this property in Emacs 22
(unless (get 'display-table 'char-table-extra-slots)
(put 'display-table 'char-table-extra-slots 0))
;; macro helper
(eval-and-compile
(defun evil-unquote (exp)
"Return EXP unquoted."
(while (eq (car-safe exp) 'quote)
(setq exp (cadr exp)))
exp))
(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."
(if (and (not (booleanp condition)) (eval condition))
(eval form)
(let* ((name (or name (format "evil-delay-form-in-%s" hook)))
(fun (make-symbol name))
(condition (or condition t)))
(fset fun `(lambda (&rest args)
(when ,condition
(remove-hook ',hook #',fun ',local)
,form)))
(put fun 'permanent-local-hook t)
(add-hook hook fun append local))))
(put 'evil-delay 'lisp-indent-function 2)
;;; List functions
(defun evil-add-to-alist (list-var key val &rest elements)
"Add the assocation of KEY and VAL to the value of LIST-VAR.
If the list already contains an entry for KEY, update that entry;
otherwise add at the end of the list."
(let ((tail (symbol-value list-var)))
(while (and tail (not (equal (car-safe (car-safe tail)) key)))
(setq tail (cdr tail)))
(if tail
(setcar tail (cons key val))
(set list-var (append (symbol-value list-var)
(list (cons key val)))))
(if elements
(apply #'evil-add-to-alist list-var elements)
(symbol-value list-var))))
;; 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."
(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)
(add-to-list 'result elt nil #'eq)))
(nreverse result)))
(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."
(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."
(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."
(let ((val (evil-get-property evil-state-properties state prop)))
(if (and value (symbolp val) (boundp val))
(symbol-value val)
val)))
(defmacro evil-swap (this that &rest vars)
"Swap the values of variables THIS and THAT.
If three or more arguments are given, the values are rotated.
E.g., (evil-swap A B C) sets A to B, B to C, and C to A."
`(progn
(setq ,this (prog1 ,that
(setq ,that ,this)))
,@(when vars
`((evil-swap ,that ,@vars)))))
(defmacro evil-sort (min max &rest vars)
"Place the smallest value in MIN and the largest in MAX.
If three or more arguments are given, place the smallest
value in the first argument and the largest in the last,
sorting in between."
(let ((sorted (make-symbol "sortvar")))
`(let ((,sorted (sort (list ,min ,max ,@vars) '<)))
(setq ,min (pop ,sorted)
,max (pop ,sorted)
,@(apply #'append
(mapcar #'(lambda (var)
(list var `(pop ,sorted)))
vars))))))
;;; Command properties
(defmacro evil-define-command (command &rest body)
"Define a command COMMAND.
\(fn COMMAND (ARGS...) DOC [[KEY VALUE]...] BODY...)"
(declare (indent defun)
(debug (&define name
[&optional lambda-list]
[&optional stringp]
[&rest keywordp sexp]
[&optional ("interactive" [&rest form])]
def-body)))
(let ((interactive '(interactive))
arg args doc doc-form key keys)
;; collect arguments
(when (listp (car-safe body))
(setq args (pop body)))
;; collect docstring
(when (> (length body) 1)
(if (eq (car-safe (car-safe body)) 'format)
(setq doc-form (pop body))
(when (stringp (car-safe body))
(setq doc (pop body)))))
;; collect keywords
(setq keys (plist-put keys :repeat t))
(while (keywordp (car-safe body))
(setq key (pop body)
arg (pop body))
(unless nil ; TODO: add keyword check
(setq keys (plist-put keys key arg))))
;; collect `interactive' form
(when (and body (consp (car body))
(eq (car (car body)) 'interactive))
(let* ((iform (pop body))
(result (apply #'evil-interactive-form (cdr iform)))
(form (car result))
(attrs (cdr result)))
(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))))
;; If no Evil properties are defined for the command, several parts of
;; Evil apply certain default rules; e.g., the repeat system decides
;; whether the command is repeatable by monitoring buffer changes.
(defun evil-has-command-property-p (command property)
"Whether COMMAND has Evil PROPERTY.
See also `evil-has-command-properties-p'."
(plist-member (evil-get-command-properties command) property))
(defun evil-has-command-properties-p (command)
"Whether Evil properties are defined for COMMAND.
See also `evil-has-command-property-p'."
(and (evil-get-command-properties command) t))
(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'."
(if (evil-has-command-property-p command property)
(evil-get-property evil-command-properties command property)
default))
(defun evil-get-command-properties (command)
"Return all Evil properties of COMMAND.
See also `evil-get-command-property'."
(evil-get-property evil-command-properties command))
(defun evil-set-command-property (command property value)
"Set PROPERTY to VALUE for COMMAND.
To set multiple properties at once, see
`evil-set-command-properties' and `evil-add-command-properties'."
(evil-put-property 'evil-command-properties command property value))
(defalias 'evil-put-command-property 'evil-set-command-property)
(defun evil-add-command-properties (command &rest properties)
"Add PROPERTIES to COMMAND.
PROPERTIES should be a property list.
To replace all properties at once, use `evil-set-command-properties'."
(apply #'evil-put-property
'evil-command-properties command properties))
(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'."
(setq evil-command-properties
(assq-delete-all command evil-command-properties))
(when properties
(apply #'evil-add-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-get-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."
(setq motion (or motion evil-this-motion))
(evil-get-command-property 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))
(defun evil-declare-ignore-repeat (command)
"Declare COMMAND to be nonrepeatable."
(evil-add-command-properties command :repeat 'ignore))
(defun evil-declare-change-repeat (command)
"Declare COMMAND to be repeatable by buffer changes."
(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 num)
"Parse STRING as a sequence of delimited arguments.
Returns a list of NUM 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."
(save-match-data
(let ((string (or string ""))
(count (or num -1)) (idx 0)
argument delim match result)
(when (string-match "^[[:space:]]*\\([^[:space:]]\\)" string)
(setq delim (match-string 1 string)
argument (format "%s\\(\\(?:[\\].\\|[^%s]\\)*\\)"
(regexp-quote delim)
delim))
(while (and (/= count 0) (string-match argument string idx))
(setq match (match-string 1 string)
idx (match-end 1)
count (1- count))
(when (= count 0)
(unless (save-match-data
(string-match
(format "%s[[:space:]]*$" delim) string idx))
(setq match (substring string (match-beginning 1)))))
(unless (and (zerop (length match))
(zerop (length (substring string idx))))
(push match result))))
(when (and num (< (length result) num))
(dotimes (i (- num (length result)))
(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)
(save-match-data
(dolist (set sets)
(when (string-match "^\\^" set)
(setq set (substring set 1)
complement "^"))
(when (string-match "^]" set)
(setq set (substring set 1)
bracket "]"))
(when (string-match "^-" 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.
Returns (CMD COUNT), where COUNT is the numeric prefix argument.
Both COUNT and CMD may be nil."
(let ((input (listify-key-sequence input))
(inhibit-quit t)
char cmd count digit event seq)
(while (progn
(setq event (or (pop input) (read-event)))
(when (eq event ?\e)
(when (sit-for evil-esc-delay t)
(setq event 'escape)))
(setq char (or (when (characterp event) event)
(when (symbolp event)
(get event 'ascii-character))))
;; this trick from simple.el's `digit-argument'
;; converts keystrokes like C-0 and C-M-1 to digits
(if (or (characterp char) (integerp char))
(setq digit (- (logand char ?\177) ?0))
(setq digit nil))
(if (keymapp cmd)
(setq seq (append seq (list event)))
(setq seq (list event)))
(setq cmd (key-binding (vconcat seq) t))
(cond
;; if CMD is a keymap, we need to read more
((keymapp cmd)
t)
;; numeric prefix argument
((or (eq cmd #'digit-argument)
(and (eq (length seq) 1)
(not (keymapp cmd))
count
(memq digit '(0 1 2 3 4 5 6 7 8 9))))
;; store digits in a string, which is easily converted
;; to a number afterwards
(setq count (concat (or count "")
(number-to-string digit)))
t)
;; catch middle digits like "da2w"
((and (not cmd)
(> (length seq) 1)
(memq digit '(0 1 2 3 4 5 6 7 8 9)))
(setq count (concat (or count "")
(number-to-string digit)))
;; remove the digit from the key sequence
;; so we can see if the previous one goes anywhere
(setq seq (nbutlast seq 1))
(setq cmd (key-binding (vconcat seq)))
t)
((eq cmd 'negative-argument)
(unless count
(setq count "-"))))))
;; determine COUNT
(when (stringp count)
(if (string= count "-")
(setq count nil)
(setq count (string-to-number count))))
;; return command description
(when (arrayp cmd)
(let ((result (evil-keypress-parser cmd)))
(setq cmd (car result)
count (cond
((and count (cadr result))
(* count (cadr result)))
(count count)
(t (cadr result))))))
(list cmd count)))
(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 evil-read-key-map)
overriding-local-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 [tool-bar]
(lookup-key global-map [tool-bar]))
(add-to-list 'new-global-map
(make-char-table 'display-table
'self-insert-command) t)
(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
(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))
(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 ((modifiers '((evil-visual-char . char)
(evil-visual-line . line)
(evil-visual-block . block)))
command prefix)
(unless motion
(while (progn
(setq command (evil-keypress-parser)
motion (pop command)
prefix (pop command))
(when prefix
(if count
(setq count (string-to-number
(concat (number-to-string count)
(number-to-string prefix))))
(setq count 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
(if (eq type 'exclusive)
(setq type 'inclusive)
(setq type 'exclusive)))
(t
(setq type modifier))))
(list motion count type)))
(defun evil-mouse-events-p (keys)
"Returns non-nil iff KEYS contains a mouse event."
(catch 'done
(dotimes (i (length keys))
(when (or (and (fboundp 'mouse-event-p)
(mouse-event-p (aref keys i)))
(mouse-movement-p (aref keys i)))
(throw 'done t)))
nil))
(defun evil-extract-count (keys)
"Splits the key-sequence KEYS into prefix-argument and the rest.
Returns 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 nil))
(while (and (<= end len))
(let ((cmd (key-binding (substring keys beg end))))
(cond
((memq cmd '(undefined nil))
(error "No command bound to %s" (substring keys beg end)))
((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
(evil-get-command-property
cmd :digit-argument-redirection)))
;; 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
(substring keys beg end)
(when (< end len)
(substring keys end))))))
(t ; append a further event
(setq end (1+ end))))))
(error "Key sequence contains no complete binding"))))
(defmacro evil-redirect-digit-argument (map keys target)
"Bind a wrapper function calling TARGET or `digit-argument'.
MAP is a keymap for binding KEYS to the wrapper for TARGET.
The wrapper only calls `digit-argument' if a prefix-argument
has already been started; otherwise TARGET is called."
(let* ((target (eval target))
(wrapper (intern (format "evil-digit-argument-or-%s"
target))))
`(progn
(define-key ,map ,keys ',wrapper)
(evil-define-command ,wrapper ()
:digit-argument-redirection ,target
:keep-visual t
:repeat nil
(interactive)
(cond
(current-prefix-arg
(setq this-command #'digit-argument)
(call-interactively #'digit-argument))
(t
(setq this-command #',target)
(call-interactively #',target)))))))
(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)))))
;;; 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 (listp specs)
(null (cdr-safe (last specs))))
(setq specs (list specs)))
(dolist (spec specs)
(cond
((functionp spec)
(condition-case nil
(funcall spec)
(error nil)))
((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.
STATE defaults to the current state.
BUFFER defaults to the current buffer."
(when (and (boundp 'evil-local-mode) evil-local-mode)
(let* ((state (or state 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)))))
(with-current-buffer (or buffer (current-buffer))
;; if both STATE and `evil-default-cursor'
;; specify a color, don't set it twice
(when (and color (listp default))
(setq default (evil-filter-list #'stringp default)))
(evil-set-cursor default)
(evil-set-cursor cursor)))))
(put 'evil-refresh-cursor 'permanent-local-hook t)
(defmacro evil-save-cursor (&rest body)
"Save the current cursor; execute BODY; restore the cursor."
(declare (indent defun)
(debug t))
`(let ((cursor cursor-type)
(color (frame-parameter (selected-frame) 'cursor-color))
(inhibit-quit t))
(unwind-protect
(progn ,@body)
(evil-set-cursor cursor)
(evil-set-cursor 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)
(unwind-protect
(progn
(evil-echo-area-save)
,@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-num-visible-lines ()
"Returns the number of currently visible lines."
(- (window-height) 1))
(defun evil-max-scroll-up ()
"Returns the maximal number of lines that can be scrolled up."
(1- (line-number-at-pos (window-start))))
(defun evil-max-scroll-down ()
"Returns the maximal number of lines that can be scrolled down."
(if (pos-visible-in-window-p (window-end))
0
(1+ (- (line-number-at-pos (point-max))
(line-number-at-pos (window-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)
"Restores 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)
"Restores 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-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.'"
(setq beg (or (evil-normalize-position beg) (point-min)))
(setq end (or (evil-normalize-position end) (point-max)))
(narrow-to-region beg end))
(defmacro evil-with-restriction (beg end &rest body)
"Execute BODY with the buffer narrowed to BEG and END.
BEG or END may be nil as passed to `evil-narrow'; this creates
a one-sided restriction."
(declare (indent 2)
(debug t))
`(save-restriction
(evil-narrow ,beg ,end)
,@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 force)
"Move point one character back if at the end of a non-empty line.
This behavior is contingent on the variable `evil-move-cursor-back';
use the FORCE parameter to override it."
(when (and (eolp)
(not (bolp))
(= (point)
(save-excursion
(evil-move-end-of-line)
(point))))
(evil-move-cursor-back force)))
(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. Honors field boundaries, i.e., constrains the movement
to the current field as recognized by `line-beginning-position'."
(when (or evil-move-cursor-back force)
(unless (or (= (point) (line-beginning-position))
(and (boundp 'visual-line-mode)
visual-line-mode
(= (point) (save-excursion
(beginning-of-visual-line)
(point)))))
(backward-char))))
(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
(when (fboundp 'evil-goto-line)
(evil-goto-line line))
(if (numberp column)
(if (< column 0)
(beginning-of-line 2)
(move-to-column column))
(beginning-of-line))
(point)))
(defun evil-column (&optional pos)
"Return the horizontal position of POS.
POS defaults to point."
(save-excursion
(when pos
(goto-char pos))
(current-column)))
(defun evil-move-to-column (column &optional dir force)
"Move point to column COLUMN in the current line.
Places point at left of the tab character (at the right if DIR
is non-nil) and returns point."
(interactive "p")
(move-to-column column force)
(unless force
(when (or (not dir) (and (numberp dir) (< dir 1)))
(when (> (current-column) column)
(evil-move-cursor-back))))
(point))
(defmacro evil-loop (spec &rest body)
"Loop with countdown variable.
Evaluate BODY with VAR counting down from COUNT to 0.
COUNT can be negative, in which case VAR counts up instead.