-
Notifications
You must be signed in to change notification settings - Fork 28
/
lightspeed.fnl
1743 lines (1505 loc) · 77.1 KB
/
lightspeed.fnl
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
; Imports & aliases ///1
(local api vim.api)
(local contains? vim.tbl_contains)
(local empty? vim.tbl_isempty)
(local map vim.tbl_map)
(local {: abs : ceil : max : min : pow} math)
; Fennel utils ///1
(macro ++ [x] `(set ,x (+ ,x 1)))
(macro one-of? [x ...]
"Expands to an `or` form, like (or (= x y1) (= x y2) ...)"
`(or ,(unpack
(icollect [_ y (ipairs [...])]
`(= ,x ,y)))))
(macro when-not [cond ...]
`(when (not ,cond) ,...))
(fn inc [x] (+ x 1))
(fn dec [x] (- x 1))
(fn clamp [val min max]
(if (< val min) min
(> val max) max
:else val))
(fn last [tbl] (. tbl (length tbl)))
; Nvim utils ///1
(fn echo [msg]
(vim.cmd :redraw) (api.nvim_echo [[msg]] false []))
(fn replace-keycodes [s]
(api.nvim_replace_termcodes s true false true))
(local <backspace> (replace-keycodes "<bs>"))
(local <ctrl-v> (replace-keycodes "<c-v>"))
(fn get-motion-force [mode]
(match (when (mode:match :o) (mode:sub -1))
last-ch (when (one-of? last-ch <ctrl-v> :V :v) last-ch)))
(fn operator-pending-mode? []
(-> (api.nvim_get_mode) (. :mode) (string.match :o)))
(fn change-operation? []
(and (operator-pending-mode?) (= vim.v.operator :c)))
(fn get-cursor-pos [] [(vim.fn.line ".") (vim.fn.col ".")])
(fn same-pos? [[l1 c1] [l2 c2]] (and (= l1 l2) (= c1 c2)))
(fn char-at-pos [[line byte-col] {: char-offset}] ; expects (1,1)-indexed input
"Get character at the given position in a multibyte-aware manner.
An optional offset argument can be given to get the nth-next screen
character instead."
(let [line-str (vim.fn.getline line)
char-idx (vim.fn.charidx line-str (dec byte-col)) ; charidx expects 0-indexed col
char-nr (vim.fn.strgetchar line-str (+ char-idx (or char-offset 0)))]
(when (not= char-nr -1)
(vim.fn.nr2char char-nr))))
(fn get-fold-edge [lnum reverse?]
(match ((if reverse? vim.fn.foldclosed vim.fn.foldclosedend) lnum)
-1 nil
fold-edge fold-edge))
(fn maparg-expr [name mode]
"Like vim.fn.maparg, but returns the rhs of <expr> mappings evaluated."
(let [rhs (vim.fn.maparg name mode)
; Note: We could use `maparg` with the `dict` arg, and check the `expr`
; field, but this works as well.
(ok? eval-rhs) (pcall vim.fn.eval rhs)]
(if (and ok? (= (type eval-rhs) :string)) eval-rhs rhs)))
; Glossary ///1
; Instant-repeat (1-char search)
; While Lightspeed is active, repeatedly pressing f/F/t/T goes to (or
; right before/after) the next/previous match (effectively repeats the
; last 1-character search with a count of 1). Pressing any other key
; exits from this "standby" mode; subsequent calls will behave as new
; invocations.
; Beacon (2-char search)
; An extmark positioned over an on-screen matching pair, giving
; information about how it can be reached. It can take on many forms; in
; the common case, the first field shows the 2nd character of the
; original pair, as a reminder (that is, it is shown on top of the
; _first_ character), while the second field shows a "target label"
; (that is possibly a "shortcut"). If there is only one match, the
; extmark shows the pair as it is, with a different highlighting (we
; will jump there automatically then).
; Beacons can also overlap each other - in that case, the invariant to
; be maintained is that the target label (i.e., the second/right field)
; should remain visible in all circumstances.
; Label (2-char search)
; The character needed to be pressed to jump to the match position,
; after the whole search pattern has been given. It is always shown on
; top of the second character of the pair.
; Shortcut (2-char search)
; A position where the assigned label itself is enough to determine the
; target you want to jump to (for example when a character is always
; followed by a certain other character in the search area). Those you
; can reach via typing the label character right after the first input,
; bypassing the second one. The label gets a different highlight in
; these cases.
; Setup ///1
(var opts {:ignore_case false
:exit_after_idle_msecs {:labeled nil
:unlabeled nil}
; s/x
:jump_to_unique_chars {:safety_timeout 400}
:match_only_the_start_of_same_char_seqs true
:substitute_chars {"\r" "¬"} ; 0x00AC
:force_beacons_into_match_width false
:safe_labels ["s" "f" "n" "u" "t" "/"
"S" "F" "N" "L" "H" "M" "U" "G" "T" "?" "Z"]
:labels ["s" "f" "n"
"j" "k" "l" "h" "o" "d" "w" "e" "m" "b"
"u" "y" "v" "r" "g" "t" "c" "x" "/" "z"
"S" "F" "N"
"J" "K" "L" "H" "O" "D" "W" "E" "M" "B"
"U" "Y" "V" "R" "G" "T" "C" "X" "?" "Z"]
:special_keys {:next_match_group "<space>"
:prev_match_group "<tab>"}
; f/t
:limit_ft_matches 4
:repeat_ft_with_target_char false})
(local removed-opts [:jump_to_first_match
:instant_repeat_fwd_key
:instant_repeat_bwd_key
:x_mode_prefix_key
:full_inclusive_prefix_key
:grey_out_search_area
:highlight_unique_chars
:jump_on_partial_input_safety_timeout
:cycle_group_fwd_key
:cycle_group_bwd_key])
(fn get-warning-msg [arg-fields]
(let [msg [["ligthspeed.nvim\n" :Question]
["The following fields in the "] ["opts" :Visual]
[" table has been renamed or removed:\n\n"]]
field-names (icollect [_ field (ipairs arg-fields)]
[(.. "\t" field "\n")])
msg-for-jump-to-first-match
[["The plugin implements \"smart\" auto-jump now, that you can fine-tune via "]
["opts.labels" :Visual] [" and "] ["opts.safe_labels" :Visual] [". See "]
[":h lightspeed-config" :Visual] [" for details."]]
msg-for-instant-repeat-keys
[["There are dedicated "] ["<Plug>" :Visual] [" keys available for native-like "]
[";" :Visual] [" and "] ["," :Visual] [" functionality now, "]
["that can also be used for instant repeat only, if you prefer. See "]
[":h lightspeed-custom-mappings" :Visual] ["."]]
msg-for-x-prefix
[["Use "] ["<Plug>Lightspeed_x" :Visual] [" and "] ["<Plug>Lightspeed_X" :Visual]
[" instead."]]
msg-for-grey-out
[["This flag has been removed. To turn the 'greywash' feature off, "]
["just set all attributes of the corresponding highlight group to 'none': "]
[":hi LightspeedGreywash guifg=none guibg=none ..." :Visual]]
msg-for-hl-unique-chars
[["Use "] ["jump_to_unique_chars" :Visual] [" instead. See "]
[":h lightspeed-config" :Visual] [" for details."]]
msg-for-cycle-keys
[["Use the "] ["opts.special_keys" :Visual] [" table instead. See "]
[":h lightspeed-config" :Visual] [" for details."]]
spec-messages
{:jump_to_first_match msg-for-jump-to-first-match
:instant_repeat_fwd_key msg-for-instant-repeat-keys
:instant_repeat_bwd_key msg-for-instant-repeat-keys
:x_mode_prefix_key msg-for-x-prefix
:full_inclusive_prefix_key msg-for-x-prefix
:grey_out_search_area msg-for-grey-out
:highlight_unique_chars msg-for-hl-unique-chars
:jump_on_partial_input_safety_timeout msg-for-hl-unique-chars
:cycle_group_fwd_key msg-for-cycle-keys
:cycle_group_bwd_key msg-for-cycle-keys}]
(each [_ field-name-chunk (ipairs field-names)]
(table.insert msg field-name-chunk))
(table.insert msg ["\n"])
(each [field spec-msg (pairs spec-messages)]
(when (contains? arg-fields field)
(table.insert msg [(.. field "\n") :IncSearch])
(each [_ chunk (ipairs spec-msg)]
(table.insert msg chunk))
(table.insert msg ["\n\n"])))
msg))
; Prevent setting or accessing removed fields directly.
(let [guard (fn [t k]
(when (contains? removed-opts k)
(api.nvim_echo (get-warning-msg [k]) true {})))]
(setmetatable opts {:__index guard
:__newindex guard}))
; Prevent setting removed fields via the `setup` function.
(fn normalize-opts [opts]
(let [removed-arg-opts []]
(each [k v (pairs opts)]
(when (contains? removed-opts k)
(table.insert removed-arg-opts k)
(tset opts k nil)))
(when-not (empty? removed-arg-opts)
(api.nvim_echo (get-warning-msg removed-arg-opts) true {}))
opts))
(fn setup [user-opts]
(set opts (-> (normalize-opts user-opts)
(setmetatable {:__index opts}))))
; Highlight ///1
(local hl
{:group {:label "LightspeedLabel"
:label-distant "LightspeedLabelDistant"
:shortcut "LightspeedShortcut"
:masked-ch "LightspeedMaskedChar"
:unlabeled-match "LightspeedUnlabeledMatch"
:one-char-match "LightspeedOneCharMatch"
:unique-ch "LightspeedUniqueChar"
:pending-op-area "LightspeedPendingOpArea"
:greywash "LightspeedGreyWash"
:cursor "LightspeedCursor"}
:priority {:cursor 65535 :label 65534 :greywash 65533}
:ns (api.nvim_create_namespace "")
:cleanup (fn [self ?target-windows]
(when ?target-windows
(each [_ w (ipairs ?target-windows)]
(api.nvim_buf_clear_namespace w.bufnr self.ns (dec w.topline) w.botline)))
; We need to clean up the cursor highlight in the current window anyway.
(api.nvim_buf_clear_namespace 0 self.ns
(dec (vim.fn.line "w0"))
(vim.fn.line "w$")))})
(fn init-highlight [force?]
(local bg vim.o.background)
(local defaults
{hl.group.label {:fg (match bg :light "#f02077" _ "#ff2f87")
:ctermfg "Red"
:bold true :underline true}
hl.group.label-distant {:fg (match bg :light "#399d9f" _ "#99ddff")
:ctermfg (match bg :light "Blue" _ "Cyan")
:bold true :underline true}
hl.group.shortcut {:bg "#f00077"
:fg "#ffffff"
:ctermbg "Red"
:ctermfg "White"
:bold true}
hl.group.masked-ch {:fg (match bg :light "#cc9999" _ "#b38080")
:ctermfg "DarkGrey"}
hl.group.unlabeled-match {:fg (match bg :light "#272020" _ "#f3ecec")
:ctermfg (match bg :light "Black" _ "White")
:bold true}
hl.group.greywash {:fg "#777777"
:ctermfg "Grey"}
hl.group.unique-ch {:link hl.group.unlabeled-match}
hl.group.one-char-match {:link hl.group.shortcut}
hl.group.pending-op-area {:link "IncSearch"}
hl.group.cursor {:link "Cursor"}})
(each [group-name def-map (pairs defaults)]
(when (not force?) (tset def-map :default true))
(api.nvim_set_hl 0 group-name def-map)))
(fn grey-out-search-area [reverse? ?target-windows omni?]
(if (or ?target-windows omni?)
(each [_ win (ipairs (or ?target-windows
[(. (vim.fn.getwininfo (vim.fn.win_getid)) 1)]))]
(vim.highlight.range win.bufnr hl.ns hl.group.greywash
[(dec win.topline) 0] [(dec win.botline) -1]
{:priority hl.priority.greywash}))
(let [[curline curcol] (map dec (get-cursor-pos))
[win-top win-bot] [(dec (vim.fn.line "w0")) (dec (vim.fn.line "w$"))]
[start finish] (if reverse?
[[win-top 0] [curline curcol]]
[[curline (inc curcol)] [win-bot -1]])]
; Expects 0,0-indexed args; `finish` is exclusive.
(vim.highlight.range 0 hl.ns hl.group.greywash start finish
{:priority hl.priority.greywash}))))
(fn highlight-range [hl-group
[startline startcol &as start]
[endline endcol &as end]
{: motion-force : inclusive-motion?}]
"A wrapper around `vim.highlight.range` that handles forced motion
types properly."
(let [hl-range (fn [start end end-inclusive?]
(vim.highlight.range 0 hl.ns hl-group start end
{:inclusive end-inclusive?
:priority hl.priority.label}))]
(match motion-force
<ctrl-v> (let [[startcol endcol] [(min startcol endcol)
(max startcol endcol)]]
(for [line startline endline]
; Blockwise operations make the motion inclusive on
; both ends, unconditionally.
(hl-range [line startcol] [line endcol] true)))
:V (hl-range [startline 0] [endline -1])
; We are in OP mode, doing chairwise motion, so 'v' _flips_ its
; inclusive/exclusive behaviour (:h o_v).
:v (hl-range start end (not inclusive-motion?))
nil (hl-range start end inclusive-motion?))))
; Common ///1
(fn echo-no-prev-search [] (echo "no previous search"))
(fn echo-not-found [s] (echo (.. "not found: " s)))
(fn push-cursor! [direction]
"Push cursor 1 character to the left or right, possibly beyond EOL."
(vim.fn.search "\\_." (match direction :fwd "W" :bwd "bW")))
; Jump ///
(fn cursor-before-eof? []
(and (= (vim.fn.line ".") (vim.fn.line "$"))
(= (vim.fn.virtcol ".") (dec (vim.fn.virtcol "$")))))
(fn push-beyond-eof! []
(local saved vim.o.virtualedit)
(set vim.o.virtualedit :onemore)
; Note: No need to undo this afterwards, the cursor will be
; moved to the end of the operated area anyway.
(vim.cmd "norm! l")
(api.nvim_create_autocmd
[:CursorMoved :WinLeave :BufLeave :InsertEnter :CmdlineEnter :CmdwinEnter]
{:callback #(set vim.o.virtualedit saved)
:once true}))
(fn simulate-inclusive-op! [mode]
"When applied after an exclusive motion (like setting the cursor via
the API), make the motion appear to behave as an inclusive one."
(match (vim.fn.matchstr mode "^no\\zs.") ; get forcing modifier
; In the normal case (no modifier), we should push the cursor
; forward. (The EOF edge case requires some hackery though.)
"" (if (cursor-before-eof?) (push-beyond-eof!) (push-cursor! :fwd))
; We also want the `v` modifier to behave in the native way, that
; is, to toggle between inclusive/exclusive if applied to a charwise
; motion (:h o_v). As `v` will change our (technically) exclusive
; motion to inclusive, we should push the cursor back to undo that.
:v (push-cursor! :bwd)
; Blockwise (<c-v>) itself makes the motion inclusive, do nothing in
; that case.
))
(fn force-matchparen-refresh []
; HACK: :DoMatchParen turns matchparen on simply by triggering
; CursorMoved events (see matchparen.vim). We can do the same, which
; is cleaner for us than calling :DoMatchParen directly, since that
; would wrap this in a `windo`, and might visit another buffer,
; breaking our visual selection (and thus also dot-repeat,
; apparently). (See :h visual-start, and the discussion at #38.)
; Programming against the API would be more robust of course, but in
; the unlikely case that the implementation details would change, this
; still cannot do any damage on our side if called with pcall (the
; feature just ceases to work then).
(pcall api.nvim_exec_autocmds "CursorMoved" {:group "matchparen"})
; If vim-matchup is installed, it can similarly be forced to refresh
; by triggering a CursorMoved event. (The same caveats apply.)
(pcall api.nvim_exec_autocmds "CursorMoved" {:group "matchup_matchparen"}))
(fn jump-to!* [target {: mode : reverse? : inclusive-motion?
: add-to-jumplist? : adjust}]
(local op-mode? (string.match mode :o))
; Note: <C-o> will ignore this if the line has not changed (neovim#9874).
(when add-to-jumplist? (vim.cmd "norm! m`"))
(vim.fn.cursor target)
; Adjust position after the jump (for t-mode or x-mode).
(adjust)
; We should get this before the (possible) hacks below.
(local adjusted-pos (get-cursor-pos))
; Since Vim interprets our jump as an exclusive motion (:h exclusive),
; we need custom tweaks to behave as an inclusive one. (This is only
; relevant in the forward direction, as inclusiveness applies to the
; end of the selection.)
(when (and op-mode? inclusive-motion? (not reverse?))
(simulate-inclusive-op! mode))
(when-not op-mode? (force-matchparen-refresh))
adjusted-pos)
; //> Jump
(fn highlight-cursor [?pos]
"The cursor is down on the command line during `getchar`,
so we set a temporary highlight on it to see where we are."
(let [[line col &as pos] (or ?pos (get-cursor-pos))
; nil means the cursor is on an empty line.
ch-at-curpos (or (char-at-pos pos {}) " ")] ; char-at-pos needs 1,1-idx
; (Ab)using extmarks even here, to be able to highlight the cursor on empty lines too.
(api.nvim_buf_set_extmark 0 hl.ns (dec line) (dec col)
{:virt_text [[ch-at-curpos hl.group.cursor]]
:virt_text_pos "overlay"
:hl_mode "combine"
:priority hl.priority.cursor})))
(fn handle-interrupted-change-op! []
"Return to Normal mode and restore the cursor position after an
interrupted change operation."
(let [seq (.. "<C-\\><C-G>" ; :h CTRL-\_CTRL-G
(if (> (vim.fn.col ".") 1) "<RIGHT>" ""))]
(api.nvim_feedkeys (replace-keycodes seq) :n true)))
(fn exec-user-autocmds [pattern]
(api.nvim_exec_autocmds "User" {: pattern :modeline false}))
(fn enter [mode]
(exec-user-autocmds :LightspeedEnter)
(match mode
:ft (exec-user-autocmds :LightspeedFtEnter)
:sx (exec-user-autocmds :LightspeedSxEnter)))
; Note: One of the main purpose of these macros, besides wrapping cleanup stuff,
; is to enforce and encapsulate the requirement that tail-positioned "exit"
; forms in `match` blocks should always return nil. (Interop with side-effecting
; VimL functions can be dangerous, they might return 0 for example, like
; `feedkey`, and with that they can screw up Fennel match forms in a breeze,
; resulting in misterious bugs, so it's better to be paranoid.)
(macro exit-template [search-mode early-exit? ...]
`(do
; Be sure _not_ to call the macro twice accidentally,
; `handle-interrupted-change-op!` might move the cursor twice then!
,(when early-exit?
`(when (change-operation?) (handle-interrupted-change-op!)))
; Putting the form here, after the change-op handler, because it might feed
; keys too. (Is that a valid problem? Change operation can only be
; interrupted by <c-c> or <esc> I guess...)
; (Note: I'd like to understand why it's necessary to wrap the varargs in
; an additional `do` - else only sees the first item.)
(do ,...)
,(match search-mode
:ft `(exec-user-autocmds :LightspeedFtLeave)
:sx `(exec-user-autocmds :LightspeedSxLeave))
(exec-user-autocmds :LightspeedLeave)
nil))
(fn get-input [?timeout]
(let [char-available? #(not= "" (vim.fn.getcharstr true))
getchar-timeout #(when (vim.wait ?timeout char-available? 100)
(vim.fn.getcharstr false))
; pcall for handling <C-c>.
(ok? ch) (pcall (if ?timeout getchar-timeout vim.fn.getcharstr))]
; <esc> should cleanly exit anytime.
(when (and ok? (not= ch (replace-keycodes "<esc>")))
ch)))
(fn ignore-input-until-timeout [input-to-ignore timeout]
(match (get-input timeout)
input (when (not= input input-to-ignore)
(vim.fn.feedkeys input :i))))
; repeat.vim support
; (see the docs in the script:
; https://github.com/tpope/vim-repeat/blob/master/autoload/repeat.vim)
(fn set-dot-repeat [cmd ?count]
; Note: dot-repeatable (i.e. non-yank) operation is assumed, we're not
; checking it here.
(let [op vim.v.operator
; We cannot getreg('.') at this point, since the change has not
; happened yet - therefore the below hack (thx Sneak).
change (when (= op :c) (replace-keycodes "<c-r>.<esc>"))
seq (.. op (or ?count "") cmd (or change ""))]
; Using pcall, since vim-repeat might not be installed.
; Use the same register for the repeated operation.
(pcall vim.fn.repeat#setreg seq vim.v.register)
; Note: we're feeding count inside the seq itself.
(pcall vim.fn.repeat#set seq -1)))
(fn get-plug-key [search-mode reverse? x/t? repeat-invoc]
(.. "<Plug>Lightspeed_"
(match repeat-invoc :dot "dotrepeat_" _ "")
; Forcing to bools with not-not, as those values can be nils.
(match [search-mode (not (not reverse?)) (not (not x/t?))]
[:ft false false] "f"
[:ft true false] "F"
[:ft false true ] "t"
[:ft true true ] "T"
[:sx false false] "s"
[:sx true false] "S"
[:sx false true ] "x"
[:sx true true ] "X")))
; TODO: Handle <a-?> keys, i.e., those with multibyte representation
; (`maparg` will not work with them, and we cannot convert `in` _to_
; a keycode(-sequence), so it's not trivial. Related: Vim #1810.)
(fn get-repeat-action [in search-mode x/t? instant-repeat?
from-reverse-cold-repeat? ?target-char]
(let [mode (if (= (vim.fn.mode) :n) :n :x) ; vim-cutlass compat (#28)
; (note: non-OP mode assumed)
in-mapped-to (maparg-expr in mode)
repeat-plug-key (.. "<Plug>Lightspeed_;_" search-mode)
revert-plug-key (.. "<Plug>Lightspeed_,_" search-mode)]
(if (or (= in <backspace>)
(and (= search-mode :ft) opts.repeat_ft_with_target_char (= in ?target-char))
(one-of? in-mapped-to
(get-plug-key search-mode false x/t?)
(if from-reverse-cold-repeat? revert-plug-key repeat-plug-key)))
:repeat
(and instant-repeat?
(or (= in "\t")
(one-of? in-mapped-to
(get-plug-key search-mode true x/t?)
(if from-reverse-cold-repeat? repeat-plug-key revert-plug-key))))
:revert)))
; 1-character search ///1
; Precursory remarks: do not readily succumb to the siren call of
; generality here. 1- and 2-character search, according to this plugin's
; concept, are specialized tools for different purposes, and their
; behaviour is different enough to validate a separate implementation,
; without an encompassing wrapper function. There are annoying overlaps
; for sure, but this is a case where mindless DRY-ing (if that makes
; sense) might ultimately introduce more complexity and maintenance
; issues than it absorbs, I guess. Time might prove me wrong.
; State for 1-character search that is persisted between invocations.
(local ft {:state {:dot {:in nil} ; `reverse?` & `t-mode?` are hardcoded into
; the dot-repeat command
:cold {:in nil
:reverse? nil
:t-mode? nil}}})
(fn ft.go [self {: reverse? : t-mode? : repeat-invoc}]
"Entry point for 1-character search."
(let [mode (. (api.nvim_get_mode) :mode) ; endnote #4
op-mode? (mode:match :o)
dot-repeatable-op? (and op-mode? (not= vim.v.operator :y))
instant-repeat? (= (type repeat-invoc) :table)
instant-state (when instant-repeat? repeat-invoc)
reverted-instant-repeat? (?. instant-state :reverted?)
cold-repeat? (= repeat-invoc :cold)
dot-repeat? (= repeat-invoc :dot)
invoked-as-reverse? reverse?
; The actual (absolute) search direction.
reverse? (if cold-repeat? (#(if invoked-as-reverse? (not $) $)
self.state.cold.reverse?)
reverse?)
t-mode? (if cold-repeat? self.state.cold.t-mode? t-mode?)
; After a reverted repeat , we highlight the next n matches as always,
; as per `limit_ft_matches`, but _stay_ where we are. (We have already
; moved the cursor back to the previous position on the stack!)
count (if reverted-instant-repeat? 0 vim.v.count1)
; In case of instant-repeating t/T (this includes reverting), we have to
; skip the first match, else we would find the same target in front of
; us again and again, and be stuck. (Instant-repeat implies that we are
; right before a target, so it's fine to simply increment `count` here.)
count (if (and instant-repeat? t-mode?) (inc count) count)]
(macro exit [...] `(exit-template :ft false ,...))
(macro exit-early [...] `(exit-template :ft true ,...))
(macro with-highlight-cleanup [...]
`(let [res# (do ,...)]
(api.nvim_buf_clear_namespace 0 hl.ns 0 -1)
res#))
(fn match-positions [pattern reverse? limit]
(let [view (vim.fn.winsaveview)
cleanup #(do (vim.fn.winrestview view) nil)]
(var match-count 0)
(fn []
(if (and limit (>= match-count limit))
(cleanup)
(match (vim.fn.searchpos pattern (if reverse? "bW" "W"))
[0 _] (cleanup)
[line col &as pos] (do (++ match-count) pos))))))
; When instant-repeating, keep highlighting the same one group of matches,
; and do not shift until reaching the end of the group - it is less
; disorienting if the "snake" does not move continuously, on every repeat.
(fn get-num-of-matches-to-be-highlighted []
(match opts.limit_ft_matches
(where group-limit (> group-limit 0))
(let [matches-left-behind (or (-?> instant-state (. :stack) (length)) 0)
; Leaving behind a match = eating one from the highlighted group.
; [] | [2 3 4 ...] -> [1] | [3 4 ...]
eaten-up (% matches-left-behind group-limit)
remaining (- group-limit eaten-up)]
; Switch to next group if no remaining matches.
(if (= remaining 0) group-limit remaining))
_ 0))
;;;
(when-not instant-repeat?
(enter :ft))
(when-not repeat-invoc
(echo "")
(highlight-cursor)
(vim.cmd :redraw))
(match (if instant-repeat? instant-state.in
dot-repeat? self.state.dot.in
cold-repeat? self.state.cold.in
(match (or (with-highlight-cleanup (get-input))
(exit-early))
<backspace> (or self.state.cold.in
(exit-early (echo-no-prev-search)))
in in))
in1
(do
(local to-eol? (= in1 "\r"))
(when-not repeat-invoc
(set self.state.cold {:in in1 : reverse? : t-mode?})) ; endnote #1
(var jump-pos nil)
(var match-count 0)
(let [next-pos (vim.fn.searchpos "\\_." (if reverse? :nWb :nW))
pattern (if to-eol? "\\n"
(.. "\\V" (if opts.ignore_case "\\c" "\\C")
(in1:gsub "\\" "\\\\")))
limit (+ count (get-num-of-matches-to-be-highlighted))]
(each [[line col &as pos] (match-positions pattern reverse? limit)]
; If we've started cold-repeating t/T from right before a match,
; then skip that match (endnote #2).
(when-not (and (= match-count 0) cold-repeat? t-mode? (same-pos? pos next-pos))
(if (<= match-count (dec count)) (set jump-pos pos)
(when-not op-mode?
(let [ch (or (char-at-pos pos {}) "\r")
ch (or (?. opts.substitute_chars ch) ch)]
(api.nvim_buf_set_extmark 0 hl.ns (dec line) (dec col)
{:virt_text [[ch hl.group.one-char-match]]
:virt_text_pos "overlay"
:priority hl.priority.label}))))
(++ match-count))))
(if (and (not reverted-instant-repeat?)
(or (= match-count 0)
; Just the character in front of us, but no more matches.
(and (= match-count 1) instant-repeat? t-mode?)))
(exit-early (echo-not-found in1))
(do
(when-not reverted-instant-repeat?
(jump-to!* jump-pos
{: mode : reverse?
:inclusive-motion? true ; just like the native f/t
:add-to-jumplist? (not instant-repeat?)
:adjust #(when t-mode?
(push-cursor! (if reverse? :fwd :bwd))
(when (and to-eol? (not reverse?) (mode:match :n))
(push-cursor! :fwd)))}))
(if op-mode?
(exit (when dot-repeatable-op?
(set self.state.dot {:in in1})
(set-dot-repeat (replace-keycodes
(get-plug-key :ft reverse? t-mode? :dot))
count)))
(do
(highlight-cursor)
(vim.cmd :redraw)
(match (or (with-highlight-cleanup
(get-input opts.exit_after_idle_msecs.unlabeled))
(exit))
in2
(let [stack (or (?. instant-state :stack) [])
; Then we would want to continue (repeat) with the reverse key,
; anc vice versa.
from-reverse-cold-repeat?
(if instant-repeat? instant-state.from-reverse-cold-repeat?
(and cold-repeat? invoked-as-reverse?))]
(match (get-repeat-action in2 :ft t-mode? instant-repeat?
from-reverse-cold-repeat? in1)
:repeat (do (table.insert stack (get-cursor-pos))
(ft:go {: reverse? : t-mode?
:repeat-invoc {:in in1 : stack :reverted? false
: from-reverse-cold-repeat?}}))
:revert (do (-?> (table.remove stack) (vim.fn.cursor)) ; jump!
(ft:go {: reverse? : t-mode?
:repeat-invoc {:in in1 : stack :reverted? true
: from-reverse-cold-repeat?}}))
_ (exit (vim.fn.feedkeys in2 :i)))))))))))))
; 2-character search ///1
; Helpers ///
(fn get-horizontal-bounds []
(let [match-width 2
textoff (. (vim.fn.getwininfo (vim.fn.win_getid)) 1 :textoff)
offset-in-win (dec (vim.fn.wincol))
offset-in-editable-win (- offset-in-win textoff)
; I.e., screen-column of the first visible column in the editable area.
left-bound (- (vim.fn.virtcol ".") offset-in-editable-win)
window-width (api.nvim_win_get_width 0)
right-edge (+ left-bound (dec (- window-width textoff)))
right-bound (- right-edge (dec match-width))] ; the whole match should be visible
[left-bound right-bound])) ; screen columns
(fn onscreen-match-positions [pattern reverse? {: cross-window? : to-eol?}]
"Returns an iterator streaming the return values of `searchpos` for
the given pattern, stopping at the window edge; in case of 2-character
search, folds and offscreen parts of non-wrapped lines are skipped too.
Caveat: side-effects take place here (cursor movement, &cpo), and the
clean-up happens only when the iterator is exhausted, so be careful with
early termination in loops."
(let [view (vim.fn.winsaveview)
cpo vim.o.cpo
opts (if reverse? "b" "")
wintop (vim.fn.line "w0")
winbot (vim.fn.line "w$")
stopline (if reverse? wintop winbot)
cleanup #(do (vim.fn.winrestview view) (set vim.o.cpo cpo) nil)
[left-bound right-bound] (get-horizontal-bounds)]
; HACK: vim.fn.cursor expects bytecol, but we want to put the cursor
; to `right-bound` as virtcol (screen col); so simply start crawling
; to the right, checking the virtcol... (When targeting the left
; bound, we might undershoot too - the virtcol of a position is
; always <= the bytecol of it -, but in that case it's no problem,
; just some unnecessary work afterwards, as we're still outside the
; on-screen area).
(fn reach-right-bound []
(while (and (< (vim.fn.virtcol ".") right-bound)
(not (>= (vim.fn.col ".") (dec (vim.fn.col "$"))))) ; reached EOL
(vim.cmd "norm! l")))
(fn skip-to-fold-edge! []
(match ((if reverse? vim.fn.foldclosed vim.fn.foldclosedend)
(vim.fn.line "."))
-1 :not-in-fold
fold-edge (do (vim.fn.cursor fold-edge 0)
(vim.fn.cursor 0 (if reverse? 1 (vim.fn.col "$")))
; ...regardless of whether it _actually_ moved
:moved-the-cursor)))
(fn skip-to-next-in-window-pos! []
; virtcol = like `col`, starting from the beginning of the line in the
; buffer, but every char counts as the #of screen columns it occupies
; (or would occupy), instead of the #of bytes.
(local [line virtcol &as from-pos] [(vim.fn.line ".") (vim.fn.virtcol ".")])
(match (if (< virtcol left-bound)
(if reverse?
(when (>= (dec line) stopline)
[(dec line) right-bound])
[line left-bound])
(> virtcol right-bound)
(if reverse?
[line right-bound]
(when (<= (inc line) stopline)
[(inc line) left-bound])))
to-pos (when (not= from-pos to-pos)
(vim.fn.cursor to-pos)
(when reverse? (reach-right-bound))
:moved-the-cursor)))
; Do not skip overlapping matches.
(set vim.o.cpo (cpo:gsub "c" ""))
; To be able to match the top-left or bottom-right corner (see below).
(var win-enter? nil)
(var match-count 0)
(when cross-window?
(set win-enter? true)
(vim.fn.cursor (if reverse? [winbot right-bound] [wintop left-bound]))
(when reverse? (reach-right-bound)))
(fn recur [match-at-curpos?]
(local match-at-curpos? (or match-at-curpos?
(when win-enter? (set win-enter? false) true)))
(if (and limit (>= match-count limit)) (cleanup)
(match (vim.fn.searchpos
pattern (.. opts (if match-at-curpos? "c" "")) stopline)
[0 _] (cleanup)
[line col &as pos]
(match (skip-to-fold-edge!)
:moved-the-cursor (recur false)
:not-in-fold
(if (or vim.wo.wrap
(<= left-bound col right-bound)
to-eol?) ; then we want the offscreen matches too
(do (++ match-count) [line col left-bound right-bound])
(match (skip-to-next-in-window-pos!)
; Arg = true, as we might be _on_ a match.
:moved-the-cursor (recur true)
_ (cleanup)))))))))
(fn user-forced-autojump? []
(or (not opts.labels) (empty? opts.labels)))
(fn user-forced-no-autojump? []
(or (not opts.safe_labels) (empty? opts.safe_labels)))
(fn get-targetable-windows [reverse? omni?]
(let [curr-win-id (vim.fn.win_getid)
; HACK!! The output of vim.fn.winlayout looks sg like:
; ['col', [['leaf', 1002], ['row', [['leaf', 1003], ['leaf', 1001]]], ['leaf', 1000]]]
; Instead of doing an in-order traversal of the window tree ourselves,
; we simply split this _string_ on the current window id, and extract
; the rest of the id-s, depending on the search direction.
[left right] (-> (vim.fn.string (vim.fn.winlayout))
(vim.split (tostring curr-win-id)))
ids (string.gmatch (if omni? (.. left right)
reverse? left
right)
"%d+")
; TODO: filter on certain window types?
visual-or-OP-mode? (not= (vim.fn.mode) :n)
buf api.nvim_win_get_buf
ids (icollect [id ids]
(when-not (and visual-or-OP-mode?
(not= (buf id) (buf curr-win-id)))
id))
ids (if reverse? (vim.fn.reverse ids) ids)]
(map #(. (vim.fn.getwininfo $) 1) ids)))
(fn get-onscreen-lines [{: get-full-window? : reverse? : skip-folds?}]
(let [lines {} ; {lnum : line-str}
wintop (vim.fn.line "w0")
winbot (vim.fn.line "w$")]
(var lnum (if get-full-window? (if reverse? winbot wintop)
(vim.fn.line ".")))
(while (if reverse? (>= lnum wintop) (<= lnum winbot))
(local fold-edge (get-fold-edge lnum reverse?))
(if (and skip-folds? fold-edge)
(set lnum ((if reverse? dec inc) fold-edge))
(do (tset lines lnum (vim.fn.getline lnum))
(set lnum ((if reverse? dec inc) lnum)))))
lines))
; TODO: multibyte issues?
(fn get-unique-chars [reverse? ?target-windows omni?]
(let [unique-chars {} ; {key-ch : [lnum col wininfo ch-on-screen]}
curr-w (. (vim.fn.getwininfo (vim.fn.win_getid)) 1)
[curline curcol] (get-cursor-pos)]
(each [_ w (ipairs (or ?target-windows [curr-w]))]
(when ?target-windows
(api.nvim_set_current_win w.winid))
(let [[left-bound right-bound] (get-horizontal-bounds {:match-width 2})
lines (get-onscreen-lines {:get-full-window? (or ?target-windows omni?)
: reverse? :skip-folds? true})]
(each [lnum line (pairs lines)]
(let [startcol (if (and (= lnum curline) (not reverse?)
(not ?target-windows))
(inc curcol)
1)
endcol (if (and (= lnum curline) reverse?
(not ?target-windows))
(dec curcol)
(length line))]
(for [col startcol endcol]
(when (or vim.wo.wrap (and (>= col left-bound) (<= col right-bound)))
(let [orig-ch (line:sub col col)
ch (if opts.ignore_case (orig-ch:lower) orig-ch)]
(tset unique-chars ch (match (. unique-chars ch)
nil [lnum col w orig-ch]
_ false)))))))))
(when ?target-windows
(api.nvim_set_current_win curr-w.winid))
(icollect [k v (pairs unique-chars)]
(match v
; A subset of the target interface (see `get-targets*`), enough
; for `light-up-beacons`.
[lnum col w orig-ch] {:pos [lnum col]
:wininfo w
:beacon [0 [[orig-ch hl.group.unique-ch]]]}))))
(fn get-targets* [input reverse? ?wininfo ?targets]
"Return a table that will store the positions and other metadata of
all on-screen pairs that start with `input`, in the order of discovery
(i.e., distance from cursor).
A target element in its final form has the following fields (the latter
ones might be set by subsequent functions):
pos : [line col]
pair : [char char]
?wininfo : `vim.fn.getwininfo` dict
?squeezed? : bool
?overlapped? : bool
?label : char
?label-state : 'active-primary' | 'active-secondary' | 'inactive'
?beacon : [col-offset [[char hl-group]]]
"
(local targets (or ?targets []))
(local to-eol? (= input "\r"))
(local winid (vim.fn.win_getid))
(var prev-match {})
(var added-prev-match? nil)
(let [pattern (if to-eol? "\\n" ; we should send in a literal \n, for searchpos
(.. "\\V"
(if opts.ignore_case "\\c" "\\C")
(input:gsub "\\" "\\\\") ; backslash still needs to be escaped for \V
"\\_."))] ; match anything (including EOL) after it
(each [[line col &as pos] (onscreen-match-positions pattern reverse?
{: to-eol?
:cross-window? ?wininfo})]
(local target {: pos :wininfo ?wininfo})
(if to-eol? (do (tset target :pair ["\n" ""])
(table.insert targets target))
(let [ch1 (char-at-pos pos {}) ; not necessarily = `input` (if case-insensitive)
ch2 (or (char-at-pos pos {:char-offset 1})
; <enter> is the expected input for line breaks, so
; let's return the key for the sublist right away.
"\r")
to-pre-eol? (= ch2 "\r")
overlaps-prev-match? (and (= line prev-match.line)
(= col ((if reverse? dec inc) prev-match.col)))
same-char-triplet? (and overlaps-prev-match? (= ch2 prev-match.ch2))
overlaps-prev-target? (and overlaps-prev-match? added-prev-match?)]
(set prev-match {: line : col : ch2})
(if (and same-char-triplet?
(or added-prev-match? ; the 2nd 'xx' in 'xxx' is _always_ skipped
opts.match_only_the_start_of_same_char_seqs))
(set added-prev-match? false)
(let [_ (tset target :pair [ch1 ch2])
prev-target (last targets)
; Experience shows that a beacon "touching" an
; unhighlighted match can confuse the eye...
; [a][b][label1][d][e][label2]
; ...so it's better to be avoided, whenever possible.
; A 4-column delta as a condition forces a gap between the
; beacon and the next one, when the former is not
; "squeezed" back into its 2-column box, i.e., when the
; label is displayed over position 'c':
; [a][b][label1][_][e][f][label2]
min-delta-to-prevent-squeezing 4
close-to-prev-target?
(match prev-target
{:pos [prev-line prev-col]}
(and (= line prev-line)
(let [col-delta (if reverse?
(- prev-col col)
(- col prev-col))]
(< col-delta min-delta-to-prevent-squeezing))))]
(when to-pre-eol? (tset target :squeezed? true))
(when close-to-prev-target?
(tset (if reverse? target prev-target) :squeezed? true))
(when overlaps-prev-target?
; Just the opposite: the _label_ should remain visible
; in any case.
(tset (if reverse? prev-target target) :overlapped? true))
(table.insert targets target)
(set added-prev-match? true))))))
(when (next targets) targets)))
(fn distance [[line1 col1] [line2 col2] vertical-only?]
(let [editor-grid-aspect-ratio 0.3 ; arbitrary (make it configurable? get it programmatically?)