forked from abo-abo/lispy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lispy.el
9743 lines (9082 loc) · 343 KB
/
lispy.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
;;; lispy.el --- vi-like Paredit. -*- lexical-binding: t -*-
;; Copyright (C) 2014-2019 Oleh Krehel
;; Author: Oleh Krehel <[email protected]>
;; URL: https://github.com/abo-abo/lispy
;; Version: 0.27.0
;; Keywords: lisp
;; This file is not part of GNU Emacs
;; This file 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, 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.
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Due to the structure of Lisp syntax it's very rare for the
;; programmer to want to insert characters right before "(" or right
;; after ")". Thus unprefixed printable characters can be used to call
;; commands when the point is at one of these locations, which are
;; further referred to as special.
;;
;; Conveniently, when located at special position it's very clear to
;; which sexp the list-manipulating command will be applied to, what
;; the result be and where the point should end up afterwards. You
;; can enhance this effect with `show-paren-mode' or similar.
;;
;; Here's an illustration to this effect, with `lispy-clone' ("*"
;; represents the point):
;; |--------------------+-----+--------------------|
;; | before | key | after |
;; |--------------------+-----+--------------------|
;; | (looking-at "(")* | c | (looking-at "(") |
;; | | | (looking-at "(")* |
;; |--------------------+-----+--------------------|
;; | *(looking-at "(") | c | *(looking-at "(") |
;; | | | (looking-at "(") |
;; |--------------------+-----+--------------------|
;;
;; When special, the digit keys call `digit-argument', since most
;; `lispy' commands accept a numeric argument. For instance, "3c" is
;; equivalent to "ccc" (clone sexp 3 times), and "4j" is equivalent to
;; "jjjj" (move point 4 sexps down). Some useful applications are
;; "9l" and "9h" - they exit list forwards and backwards respectively
;; at most 9 times which makes them effectively equivalent to
;; `end-of-defun' and `beginning-of-defun'.
;;
;; To move the point into a special position, use:
;; "]" - calls `lispy-forward'
;; "[" - calls `lispy-backward'
;; "C-3" - calls `lispy-right' (exit current list forwards)
;; ")" - calls `lispy-right-nostring' (exit current list
;; forwards, but self-insert in strings and comments)
;;
;; These are the few Lispy commands that don't care whether the point
;; is special or not. Other such bindings are `DEL', `C-d', `C-k'.
;;
;; To get out of the special position, you can use any of the good-old
;; navigational commands such as `C-f' or `C-n'.
;; Additionally `SPC' will break out of special to get around the
;; situation when you have the point between open parens like this
;; "(|(" and want to start inserting. `SPC' will change the code to
;; this: "(| (".
;;
;; A lot of Lispy commands come in pairs: one reverses the other.
;; Some examples are:
;; |-----+--------------------------+------------+-------------------|
;; | key | command | key | command |
;; |-----+--------------------------+------------+-------------------|
;; | j | `lispy-down' | k | `lispy-up' |
;; | s | `lispy-move-down' | w | `lispy-move-up' |
;; | > | `lispy-slurp' | < | `lispy-barf' |
;; | c | `lispy-clone' | C-d or DEL | |
;; | C | `lispy-convolute' | C | reverses itself |
;; | d | `lispy-different' | d | reverses itself |
;; | M-j | `lispy-split' | + | `lispy-join' |
;; | O | `lispy-oneline' | M | `lispy-multiline' |
;; | S | `lispy-stringify' | C-u " | `lispy-quotes' |
;; | ; | `lispy-comment' | C-u ; | `lispy-comment' |
;; | xi | `lispy-to-ifs' | xc | `lispy-to-cond' |
;; | F | `lispy-follow' | D | `pop-tag-mark' |
;; |-----+--------------------------+------------+-------------------|
;;
;; Here's a list of commands for inserting pairs:
;; |-----+------------------------------------|
;; | key | command |
;; |-----+------------------------------------|
;; | ( | `lispy-parens' |
;; | { | `lispy-braces' |
;; | } | `lispy-brackets' |
;; | " | `lispy-quotes' |
;; |-----+------------------------------------|
;;
;; Here's a list of modified insertion commands that handle whitespace
;; in addition to self-inserting:
;; |-----+------------------------------------|
;; | key | command |
;; |-----+------------------------------------|
;; | SPC | `lispy-space' |
;; | : | `lispy-colon' |
;; | ^ | `lispy-hat' |
;; | ' | `lispy-tick' |
;; | ` | `lispy-backtick' |
;; | C-m | `lispy-newline-and-indent' |
;; |-----+------------------------------------|
;;
;; You can see the full list of bound commands with "F1 f lispy-mode".
;;
;; Most special commands will leave the point special after they're
;; done. This allows to chain them as well as apply them continuously
;; by holding the key. Some useful holdable keys are "jkf<>cws;".
;; Not so useful, but fun is "/": start it from "|(" position and hold
;; until all your Lisp code is turned into Python :).
;;
;; Some Clojure support depends on `cider'.
;; Some Scheme support depends on `geiser'.
;; Some Common Lisp support depends on `slime' or `sly'.
;; You can get them from MELPA.
;;
;; See http://abo-abo.github.io/lispy/ for a detailed documentation.
;;
;;; Code:
;;* Requires
(eval-when-compile
(require 'org)
(require 'iedit)
(require 'eldoc)
(require 'ediff)
(require 'ediff-util)
(require 'semantic)
(require 'semantic/db))
(require 'zoutline)
(require 'mode-local)
(require 'lispy-tags)
(require 'help-fns)
(require 'edebug)
(require 'etags)
(require 'outline)
(require 'avy)
(require 'newcomment)
(require 'lispy-inline)
(setq iedit-toggle-key-default nil)
(require 'delsel)
(require 'pcase)
(require 'hydra)
(eval-after-load 'cider '(require 'le-clojure))
(defsubst lispy-looking-back (regexp)
"Forward to (`looking-back' REGEXP)."
(looking-back regexp (line-beginning-position)))
;;* Locals: extract block
(defvar lispy-map-input-overlay nil
"The input overlay for mapping transformations.")
(defvar lispy-map-target-beg 1
"The target start for mapping transformations.")
(defvar lispy-map-target-len 1
"The target end for mapping transformations.")
;; TODO: Should this be suspect to comment-char handling as well?
(defvar-local lispy-outline-header ";;"
"Store the buffer-local outline start.")
(defvar lispy-map-format-function nil)
;;* Customization
(defgroup lispy nil
"List navigation and editing for the Lisp family."
:group 'bindings
:prefix "lispy-")
(defvar lispy-left "[([{]"
"Opening delimiter.")
(defvar lispy-right "[])}]"
"Closing delimiter.")
(defvar lispy-outline "^;;\\(?:;[^#]\\|\\*+\\)"
"Outline delimiter.")
(defcustom lispy-no-space nil
"When non-nil, don't insert a space before parens/brackets/braces/colons."
:type 'boolean
:group 'lispy)
(make-variable-buffer-local 'lispy-no-space)
(defcustom lispy-lax-eval t
"When non-nil, fix \"unbound variable\" error by setting the it to nil.
This is useful when hacking functions with &optional arguments.
So evaling (setq mode (or mode major-mode)) will set mode to nil on
the first eval, and to major-mode on the second eval."
:type 'boolean
:group 'lispy)
(defcustom lispy-verbose t
"If t, lispy will display some messages on error state.
These messages are similar to \"Beginning of buffer\" error for
`backward-char' and can safely be ignored."
:type 'boolean
:group 'lispy)
(defcustom lispy-verbose-verbs t
"If t, verbs produced by `lispy-defverb' will have a hint in the echo area.
The hint will consist of the possible nouns that apply to the verb."
:type 'boolean
:group 'lispy)
(defcustom lispy-close-quotes-at-end-p nil
"If t, when pressing `\"' at the end of a quoted string, move past the end quote."
:type 'boolean
:group 'lispy)
(defcustom lispy-helm-columns '(70 80)
"Max lengths of tag and tag+filename when completing with `helm'."
:group 'lispy
:type '(list integer integer))
(defcustom lispy-no-permanent-semantic nil
"When t, `lispy' will not enable function `semantic-mode' when it's off."
:type 'boolean
:group 'lispy)
(defcustom lispy-completion-method 'ivy
"Method to select a candidate from a list of strings."
:type '(choice
(const :tag "Ivy" ivy)
;; sensible choice for many tags
(const :tag "Helm" helm)
;; `ido-vertical-mode' is highly recommended here
(const :tag "Ido" ido)
;; `icomplete-mode' and `icy-mode' will affect this
(const :tag "Default" default)))
(defcustom lispy-visit-method 'ffip
"Method to switch to a file in the current project."
:type '(choice
(const :tag "Find File in Project" ffip)
(const :tag "Projectile" projectile)))
(defcustom lispy-avy-style-char 'pre
"Method of displaying the overlays for a char during visual selection."
:type '(choice
(const :tag "Pre" pre)
(const :tag "At" at)
(const :tag "At full" at-full)
(const :tag "Post" post)))
(defcustom lispy-avy-style-paren 'at
"Method of displaying the overlays for a paren during visual selection."
:type '(choice
(const :tag "Pre" pre)
(const :tag "At" at)
(const :tag "At full" at-full)
(const :tag "Post" post)))
(defcustom lispy-avy-style-symbol 'pre
"Method of displaying the overlays for a symbol during visual selection."
:type '(choice
(const :tag "Pre" pre)
(const :tag "At" at)
(const :tag "At full" at-full)
(const :tag "Post" post)))
(defcustom lispy-avy-keys (number-sequence ?a ?z)
"Keys for jumping."
:type '(repeat :tag "Keys" (character :tag "char")))
(declare-function counsel-imenu "ext:counsel")
(defcustom lispy-imenu-function #'counsel-imenu
"Function used to jump to an imenu entry."
:type 'function)
(defface lispy-command-name-face
'((((class color) (background light))
:background "#d8d8f7" :inherit font-lock-function-name-face)
(((class color) (background dark))
:background "#333333" :inherit font-lock-function-name-face))
"Face for Elisp commands."
:group 'lispy-faces)
(defface lispy-cursor-face
'((((class color) (background light))
:background "#000000" :foreground "#ffffff")
(((class color) (background dark))
:background "#ffffff" :foreground "#000000"))
"Face for `lispy-view-test'."
:group 'lispy-faces)
(defface lispy-test-face
'((t (:inherit lispy-face-hint)))
"Face for `lispy-view-test'."
:group 'lispy-faces)
(defvar lispy-mode-map (make-sparse-keymap))
(defvar lispy-known-verbs nil
"List of registered verbs.")
(defvar lispy-ignore-whitespace nil
"When set to t, function `lispy-right' will not clean up whitespace.")
(defcustom lispy-compat '(edebug)
"List of package compatibility options.
Enabling them adds overhead, so make sure that you are actually
using those packages."
:type '(repeat
(choice
(const :tag "god-mode" god-mode)
(const :tag "magit-blame-mode" magit-blame-mode)
(const :tag "edebug" edebug)
(const :tag "cider" cider)
(const :tag "macrostep" macrostep))))
(defvar-local lispy-old-outline-settings nil
"Store the old values of `outline-regexp' and `outline-level'.
`lispy-mode' overrides those while it's on.")
(defcustom lispy-safe-delete nil
"When non-nil, killing/deleting an active region keeps delimiters balanced.
This applies to `lispy-delete', `lispy-kill-at-point', `lispy-paste', and
`lispy-delete-backward'. This also applies to `lispy-yank' when
`delete-selection-mode' is non-nil."
:group 'lispy
:type 'boolean)
(defcustom lispy-safe-copy nil
"When non-nil, `lispy-new-copy' won't copy unbalanced delimiters in a region."
:group 'lispy
:type 'boolean)
(defcustom lispy-safe-paste nil
"When non-nil, `lispy-paste' and `lispy-yank' will add missing delimiters."
:group 'lispy
:type 'boolean)
(defcustom lispy-safe-threshold 1500
"The max size of an active region that lispy will try to keep balanced.
This only applies when `lispy-safe-delete', `lispy-safe-copy', and/or
`lispy-safe-paste' are non-nil."
:group 'lispy
:type 'number)
(defcustom lispy-safe-actions-ignore-strings t
"When non-nil, don't try to act safely in strings.
Any unmatched delimiters inside of strings will be copied or deleted. This only
applies when `lispy-safe-delete', `lispy-safe-copy', and/or `lispy-safe-paste'
are non-nil."
:group 'lispy
:type 'boolean)
(defcustom lispy-safe-actions-ignore-comments t
"When non-nil, don't try to act safely in comments.
Any unmatched delimiters inside of comments will be copied or deleted. This only
applies when `lispy-safe-delete', `lispy-safe-copy', and/or `lispy-safe-paste'
are non-nil."
:group 'lispy
:type 'boolean)
(defcustom lispy-safe-actions-no-pull-delimiters-into-comments nil
"When non-nil, don't pull unmatched delimiters into comments when deleting.
This prevents the accidental unbalancing of expressions from commenting out
delimiters. This only applies when `lispy-safe-delete', `lispy-safe-copy',
and/or `lispy-safe-paste' are non-nil."
:group 'lispy
:type 'boolean)
(defcustom lispy-insert-space-after-wrap t
"When non-nil, insert a space after the point when wrapping.
This applies to the commands that use `lispy-pair'."
:group 'lispy
:type 'boolean)
(defcustom lispy-thread-last-macro "thread-last"
"Threading macro to use by default in command `lispy-thread-last'."
:type '(radio
(const :tag "Elisp" "thread-last")
(const :tag "Clojure" "->>")
(string :tag "Custom")))
(defun lispy-comment-char (&optional level postfix)
"Get the `comment-start' character, or `;' if nil, repeated LEVEL times concated with POSTFIX."
(concat
(apply #'concat (make-list (or level 1) (or comment-start ";")))
(or postfix "")))
(defun lispy-dir-string< (a b)
(if (string-match "/$" a)
(if (string-match "/$" b)
(string< a b)
t)
(if (string-match "/$" b)
nil
(string< a b))))
(defun lispy--normalize-files (fs)
(cl-sort
(cl-set-difference
fs
'("./" "../") :test #'equal)
#'lispy-dir-string<))
(defun lispy--completion-common-len (str)
(if (eq (get-text-property 0 'face str)
'completions-common-part)
(next-property-change 0 str)
0))
(defun lispy--complete-fname-1 (str pt)
"Try to complete a partial file name in STR at PT.
Depends on `default-directory'."
(with-temp-buffer
(insert str)
(comint-mode)
(let* ((com (comint-filename-completion))
(cands
(all-completions
(buffer-substring-no-properties
(nth 0 com)
(nth 1 com))
(nth 2 com))))
(when cands
(list (- pt (lispy--completion-common-len (car cands)))
pt
(delete
"../"
(delete
"./"
(all-completions
(buffer-substring-no-properties
(nth 0 com)
(nth 1 com))
(nth 2 com)))))))))
(defun lispy-complete-fname-at-point ()
"Completion source for `completion-at-point-functions'."
(when (lispy--in-string-p)
(let ((ini-bnd (bounds-of-thing-at-point 'filename)))
(if ini-bnd
(lispy--complete-fname-1
(buffer-substring-no-properties (car ini-bnd) (point))
(point))
(list (point) (point)
(lispy--normalize-files
(all-completions "" #'read-file-name-internal)))))))
(defconst lispy-font-lock-keywords
'(("^;; ?\\(\\*\\|\\*[^*\n].*\\)$" 1 'org-level-1 prepend)
("^;; ?\\(\\*\\{2\\}\\|\\*\\{2\\}[^*\n].*\\)$" 1 'org-level-2 prepend)
("^;; ?\\(\\*\\{3\\}\\|\\*\\{3\\}[^*\n].*\\)$" 1 'org-level-3 prepend)
("^;; ?\\(\\*\\{4\\}\\|\\*\\{4\\}[^*\n].*\\)$" 1 'org-level-4 prepend)
("^;; ?\\(\\*\\{5\\}\\|\\*\\{5\\}[^*\n].*\\)$" 1 'org-level-5 prepend)))
;;;###autoload
(define-minor-mode lispy-mode
"Minor mode for navigating and editing LISP dialects.
When `lispy-mode' is on, most unprefixed keys,
i.e. [a-zA-Z+-./<>], conditionally call commands instead of
self-inserting. The condition (called special further on) is one
of:
- the point is before \"(\"
- the point is after \")\"
- the region is active
For instance, when special, \"j\" moves down one sexp, otherwise
it inserts itself.
When special, [0-9] call `digit-argument'.
When `lispy-mode' is on, \"[\" and \"]\" move forward and
backward through lists, which is useful to move into special.
\\{lispy-mode-map}"
:keymap lispy-mode-map
:group 'lispy
:lighter " LY"
(if lispy-mode
(progn
(require 'eldoc)
(eldoc-remove-command 'special-lispy-eval)
(eldoc-remove-command 'special-lispy-x)
(eldoc-add-command 'lispy-space)
(setq lispy-old-outline-settings
(cons outline-regexp outline-level))
(setq-local outline-level 'lispy-outline-level)
(cond ((eq major-mode 'latex-mode)
(setq-local lispy-outline "^\\(?:%\\*+\\|\\\\\\(?:sub\\)?section{\\)")
(setq lispy-outline-header "%")
(setq-local outline-regexp "\\(?:%\\*+\\|\\\\\\(?:sub\\)?section{\\)"))
((eq major-mode 'clojure-mode)
(eval-after-load 'le-clojure
'(setq completion-at-point-functions
'(lispy-clojure-complete-at-point
cider-complete-at-point)))
(setq-local outline-regexp (substring lispy-outline 1)))
((eq major-mode 'python-mode)
(setq-local lispy-outline "^#\\*+")
(setq lispy-outline-header "#")
(setq-local outline-regexp "#\\*+")
(setq-local outline-heading-end-regexp "\n"))
(t
(setq-local outline-regexp (substring lispy-outline 1))))
(when (called-interactively-p 'any)
(mapc #'lispy-raise-minor-mode
(cons 'lispy-mode lispy-known-verbs)))
(font-lock-add-keywords major-mode lispy-font-lock-keywords))
(when lispy-old-outline-settings
(setq outline-regexp (car lispy-old-outline-settings))
(setq outline-level (cdr lispy-old-outline-settings))
(setq lispy-old-outline-settings nil))
(font-lock-remove-keywords major-mode lispy-font-lock-keywords)))
(defun lispy-raise-minor-mode (mode)
"Make MODE the first on `minor-mode-map-alist'."
(let ((x (assq mode minor-mode-map-alist)))
(when x
(setq minor-mode-map-alist
(cons x (delq mode minor-mode-map-alist))))))
;;* Macros
(defmacro lispy-dotimes (n &rest bodyform)
"Execute N times the BODYFORM unless an error is signaled.
Return nil if couldn't execute BODYFORM at least once.
Otherwise return the amount of times executed."
(declare (indent 1)
(debug (form body)))
`(let ((i 0))
(catch 'result
(condition-case e
(progn
(while (<= (cl-incf i) ,n)
,@bodyform)
,n)
(error
(when (eq (car e) 'buffer-read-only)
(message "Buffer is read-only: %s" (current-buffer)))
(cl-decf i)
(and (> i 0) i))))))
(defmacro lispy-save-excursion (&rest body)
"More intuitive (`save-excursion' BODY)."
(declare (indent 0))
`(let ((out (save-excursion
,@body)))
(when (lispy-bolp)
(back-to-indentation))
out))
(defmacro lispy-from-left (&rest body)
"Ensure that BODY is executed from start of list."
(declare (debug (body)))
(let ((at-start (cl-gensym "at-start")))
`(let ((,at-start (lispy--leftp)))
(unless ,at-start
(lispy-different))
(unwind-protect
(lispy-save-excursion
,@body)
(unless (eq ,at-start (lispy--leftp))
(lispy-different))))))
(defmacro lispy-flet (binding &rest body)
"Temporarily override BINDING and execute BODY."
(declare (indent 1))
(let* ((name (car binding))
(old (cl-gensym (symbol-name name))))
`(let ((,old (symbol-function ',name)))
(unwind-protect
(progn
(fset ',name (lambda ,@(cdr binding)))
,@body)
(fset ',name ,old)))))
(defmacro lispy-multipop (lst n)
"Remove LST's first N elements and return them."
`(if (<= (length ,lst) ,n)
(prog1 ,lst
(setq ,lst nil))
(prog1 ,lst
(setcdr
(nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
nil))))
(defvar lispy-whitespace-types '(clojure-commas)
"List of tokens to treat as whitespace")
(defvar lispy-site-directory (file-name-directory
load-file-name)
"The directory where all of the lispy files are located.")
;;* Verb related
(defun lispy-disable-verbs-except (verb)
"Disable all verbs except VERB."
(mapc
(lambda (v) (funcall v -1))
(remq verb lispy-known-verbs)))
(defun lispy-quit ()
"Remove modifiers."
(interactive)
(lispy-disable-verbs-except nil))
(defmacro lispy-defverb (name grammar)
"Define the verb NAME.
GRAMMAR is a list of nouns that work with this verb."
(let* ((sym (intern (format "lispy-%s-mode" name)))
(keymap (intern (format "lispy-%s-mode-map" name)))
(doc (format "%s verb.\n\n \\{lispy-%s-mode-map}"
(capitalize name) name))
(lighter (format " [%s]" name))
(verb (intern (format "lispy-%s-verb" name)))
(msg (format "[%s]: %s" name
(mapconcat #'car grammar " "))))
`(progn
(defvar ,sym nil
,(format "Non-nil if Lispy-%s mode is enabled.
Use the command `%s' to change this variable."
(capitalize name)
sym))
(make-variable-buffer-local ',sym)
(defvar ,keymap (make-sparse-keymap))
(defun ,sym (&optional arg)
,doc
(interactive (list (or current-prefix-arg 'toggle)))
(let ((last-message (current-message)))
(setq ,sym (if (eq arg 'toggle)
(not ,sym)
(> (prefix-numeric-value arg)
0)))
(cond (,sym (lispy-disable-verbs-except ',sym))
(t nil))
(if (called-interactively-p 'any)
(unless (and (current-message)
(not (equal last-message (current-message))))
(if ,sym
(when lispy-verbose-verbs
(message ,msg))
(message "")))))
(force-mode-line-update))
(mapc (lambda (x)
(lispy-define-key
,keymap
(car x) (cadr x)
:disable ',sym))
',grammar)
(unless (memq ',sym lispy-known-verbs)
(push ',sym lispy-known-verbs))
(defun ,verb ()
(interactive)
(if (bound-and-true-p ,sym)
(,sym -1)
(,sym 1)))
(with-no-warnings
(add-minor-mode ',sym ,lighter ,keymap nil nil)))))
;;* Globals: navigation
(defsubst lispy-right-p ()
"Return t if after variable `lispy-right'."
(looking-back lispy-right
(line-beginning-position)))
(defsubst lispy-left-p ()
"Return t if before variable `lispy-left'."
(looking-at lispy-left))
(defun lispy-forward (arg)
"Move forward list ARG times or until error.
Return t if moved at least once,
otherwise call function `lispy-right' and return nil."
(interactive "p")
(when (= arg 0)
(setq arg 2000))
(lispy--exit-string)
(let ((bnd (lispy--bounds-comment)))
(when bnd
(goto-char (1+ (cdr bnd)))))
(let ((pt (point))
(r (lispy-dotimes arg
(when (= (point) (point-max))
(error "Reached end of buffer"))
(forward-list))))
;; `forward-list' returns true at and of buffer
(if (or (null r)
(= pt (point))
(and (not (lispy-right-p))
(progn
(backward-list)
(forward-list)
(= pt (point)))))
(prog1 nil
(lispy--out-forward 1))
(point))))
(defun lispy-backward (arg)
"Move backward list ARG times or until error.
If couldn't move backward at least once, move up backward and return nil."
(interactive "p")
(when (= arg 0)
(setq arg 2000))
(lispy--exit-string)
(let ((bnd (lispy--bounds-comment)))
(when bnd
(goto-char (car bnd))))
(let ((pt (point))
(r (lispy-dotimes arg
(when (= (point) (point-min))
(error "Reached beginning of buffer"))
(backward-list))))
;; `backward-list' returns true at beginning of buffer
(if (or (null r)
(= pt (point))
(and (not (lispy-left-p))
(progn
(forward-list)
(backward-list)
(= pt (point)))))
(prog1 nil
(condition-case nil
(progn
(lispy--out-forward 1)
(backward-list))
(error
(progn
(goto-char pt)
(up-list -1)))))
(point))))
(defun lispy-right (arg)
"Move outside list forwards ARG times.
Return nil on failure, t otherwise."
(interactive "p")
(lispy--remember)
(when (bound-and-true-p abbrev-mode)
(ignore-errors (expand-abbrev)))
(cond ((region-active-p)
(lispy-mark-right arg))
((looking-at lispy-outline)
(lispy-outline-right))
(t
(lispy--out-forward arg))))
(defun lispy-right-nostring (arg)
"Call `lispy--out-forward' with ARG unless in string or comment.
Self-insert otherwise."
(interactive "p")
(if (or (lispy--in-string-or-comment-p)
(looking-back "?\\\\"
(line-beginning-position)))
(self-insert-command arg)
(lispy--out-forward arg)))
(defun lispy-left (arg)
"Move outside list forwards ARG times.
Return nil on failure, t otherwise."
(interactive "p")
(lispy--remember)
(cond ((region-active-p)
(lispy-mark-left arg))
((looking-at lispy-outline)
(lispy-outline-left))
(t
(or (lispy--out-backward arg)
(ignore-errors
(up-list -1))))))
(defun lispy-left-maybe (arg)
"Call `lispy-left', unless we're in a REPL."
(interactive "p")
(let ((cmd (lookup-key (current-local-map) (this-command-keys))))
(if cmd
(call-interactively cmd)
(lispy-left arg))))
(defun lispy-out-forward-newline (arg)
"Call `lispy--out-forward', then ARG times `newline-and-indent'."
(interactive "p")
(lispy--out-forward 1)
(lispy-dotimes arg
(newline-and-indent)))
(defvar lispy-meol-point 1
"Point where `lispy-move-end-of-line' should go when already at eol.")
(defun lispy-move-end-of-line ()
"Forward to `move-end-of-line' unless already at end of line.
Then return to the point where it was called last.
If this point is inside string, move outside string."
(interactive)
(let ((pt (point))
bnd)
(if (eq pt (line-end-position))
(if (setq bnd (lispy--bounds-string))
(goto-char (cdr bnd))
(when (and (< lispy-meol-point pt)
(>= lispy-meol-point (line-beginning-position)))
(goto-char lispy-meol-point)
(when (setq bnd (lispy--bounds-string))
(goto-char (cdr bnd)))))
(setq lispy-meol-point (point))
(move-end-of-line 1))))
(defun lispy-move-beginning-of-line ()
"Forward to `move-beginning-of-line'.
Reveal outlines."
(interactive)
(lispy--ensure-visible)
(if (bolp)
(back-to-indentation)
(move-beginning-of-line 1)))
(defun lispy--re-search-in-code (regexp direction &optional count)
"Move to the next REGEXP in DIRECTION, COUNT times.
DIRECTION is either 'forward or 'backward.
Return the amount of successful moves, or nil otherwise."
(setq count (or count 1))
(let ((to-move (abs count))
(advancer
(if (eq direction 'forward)
(if (> count 0)
#'re-search-forward
#'re-search-backward)
(if (> count 0)
#'re-search-backward
#'re-search-forward)))
(pt (point)))
(if (and (eq direction 'forward) (> count 0))
(when (looking-at regexp)
(goto-char (match-end 0))))
(while (and (> to-move 0)
(funcall advancer regexp nil t))
(unless (lispy--in-string-or-comment-p)
(cl-decf to-move)))
(if (= to-move (abs count))
(progn
(goto-char pt)
nil)
(if (eq direction 'forward)
(goto-char (match-beginning 0)))
(- count to-move))))
;;* Locals: navigation
(defun lispy-flow (arg)
"Move inside list ARG times.
Don't enter strings or comments.
Return nil if can't move."
(interactive "p")
(lispy--remember)
(let ((pt (point))
r)
(cond
((and (lispy-bolp)
(looking-at (lispy-comment-char)))
(setq r (lispy--re-search-in-code lispy-left 'forward arg)))
((lispy-left-p)
(setq r (lispy--re-search-in-code lispy-left 'forward arg)))
((lispy-right-p)
(backward-char)
(when (setq r (lispy--re-search-in-code lispy-right 'backward arg))
(forward-char))))
(or r
(progn
(goto-char pt)
nil))))
(defun lispy-down (arg)
"Move down ARG times inside current list."
(interactive "p")
(lispy--remember)
(cond ((region-active-p)
(let ((leftp (= (point) (region-beginning))))
(when leftp
(exchange-point-and-mark))
(cond ((save-excursion
(skip-chars-forward " \n")
(eobp)))
((lispy--symbolp (lispy--string-dwim))
(lispy-dotimes arg
(when (lispy-slurp 1)
(lispy-different)
(lispy-barf 1)
(lispy-different))))
((looking-at "[\n ]+\\(;\\)")
(deactivate-mark)
(goto-char (match-beginning 1))
(lispy--mark (lispy--bounds-comment)))
(t
(lispy-dotimes arg
(forward-sexp 1)
(lispy-different)
(if (lispy--in-comment-p)
(progn
(goto-char (1+ (cdr (lispy--bounds-comment))))
(skip-chars-forward "\n"))
(forward-sexp 2)
(forward-sexp -1))
(lispy-different))))
(when leftp
(exchange-point-and-mark))))
((lispy-left-p)
(lispy-forward arg)
(let ((pt (point))
(lispy-ignore-whitespace t))
(if (lispy-forward 1)
(lispy-backward 1)
(goto-char pt)
(lispy-different))))
((lispy-right-p)
(let ((pt (point)))
(unless (lispy-forward arg)
(goto-char pt))))
((or (looking-at lispy-outline)
(and (bolp) (looking-at (lispy-comment-char))))
(let ((pt (point))
(outline-regexp lispy-outline))
(lispy-dotimes arg
(outline-next-visible-heading 1)
(if (looking-at lispy-outline)
(setq pt (point))
(goto-char pt)
(error "Last outline reached")))))
(t
(lispy-forward 1)
(lispy-backward 1)))
(lispy--ensure-visible))
(defun lispy-up (arg)
"Move up ARG times inside current list."
(interactive "p")
(lispy--remember)
(cond ((region-active-p)
(let ((leftp (= (point) (region-beginning))))
(unless leftp
(exchange-point-and-mark))
(cond ((save-excursion
(skip-chars-backward "\n ")
(bobp)))
((looking-back "^ *\\(;\\)[^\n]*[\n ]*"
(save-excursion
(ignore-errors
(backward-sexp 1))
(point)))
(deactivate-mark)
(goto-char (match-beginning 1))
(lispy--mark (lispy--bounds-comment))
(exchange-point-and-mark))
((lispy--symbolp (lispy--string-dwim))
(lispy-dotimes arg
(when (lispy-slurp 1)
(lispy-different)
(lispy-barf 1)
(lispy-different))))
(t
(lispy-dotimes arg
(backward-sexp 1)
(lispy-different)
(if (lispy--in-comment-p)
(progn
(goto-char (1- (car (lispy--bounds-comment))))
(skip-chars-backward "\n"))
(backward-sexp 2)
(backward-sexp -1))
(lispy-different))))
(unless leftp
(exchange-point-and-mark))))
((lispy-left-p)
(let ((pt (point)))
(unless (lispy-backward arg)
(goto-char pt))))
((lispy-right-p)
(lispy-backward arg)
(let ((pt (point)))
(if (lispy-backward 1)
(lispy-forward 1)
(goto-char pt)
(lispy-different))))