-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvi_mode.lua
1562 lines (1363 loc) · 48.4 KB
/
vi_mode.lua
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
local M = {}
-- In Textadept 11.0 (and some betas), there is some code to detect key mappings
-- using the old style ('ca' instead of 'ctrl+a'); however this interacts badly
-- with our metatable-based key maps - so we need to disable that compatibility
-- code.
_NOCOMPAT = true
------ Configuration (should make it possible to pass it in) ------
-- If true, then convert alt-x or meta-x into ESC x (NCURSES only). This means
-- that you can no longer use alt-key bindings, but means that you can quickly
-- type ESC followed by vi commands without waiting for the ESC to time out.
M.strip_alt = true
M.ex_mode = require 'textadept-vi.vi_mode_ex'
M.search_mode = require 'textadept-vi.vi_mode_search'
M.vi_tags = require 'textadept-vi.vi_tags'
M.lang = require 'textadept-vi.vi_lang'
M.vi_complete = require 'textadept-vi.vi_complete'
vi_find_files = require 'textadept-vi.vi_find_files'
vi_visual = require('textadept-vi.vi_visual')
local lpeg = require 'lpeg'
local vi_motion = require 'textadept-vi.vi_motion'
local vi_motions = require 'textadept-vi.vi_motions'
local vi_down = vi_motions.line_down
local vi_up= vi_motions.line_up
local vi_tags = M.vi_tags
local vi_ops = require'textadept-vi.vi_ops'
local vi_ta_util = require 'textadept-vi.vi_ta_util'
local vi_views = require 'textadept-vi.vi_views'
local line_length = vi_ta_util.line_length
local buf_state = vi_ta_util.buf_state
--[[
Make textadept behave a bit like vim.
--]]
-- The current mode (command, insert, etc.)
COMMAND = "vi_command"
INSERT = "vi_insert"
INSERT_CNP = "vi_complete" -- Ctrl-P/Ctrl-N search mode
VISUAL = vi_visual.VISUAL
M.COMMAND = COMMAND
M.INSERT = INSERT
M.INSERT_CNP = INSERT_CNP
M.VISUAL = VISUAL
mode = nil -- initialised below
local debugFlag = false
function dbg(...)
--if debugFlag then print(...) end
if debugFlag then
ui._print("vimode", ...)
end
end
function enter_mode(m)
mode = m
dbg("Enter mode:" .. m.name)
keys.mode = m.name
if m.restart then
local restart = m.restart
m.restart = nil
restart()
end
if m.init then
m.init()
end
update_status()
end
function do_keys(...)
local result = nil
local handler = nil
for _,sym in ipairs({...}) do
handler = (type(handler) == 'table' and handler or mode.bindings)[sym]
if type(handler) == 'function' then result = handler(sym) end
end
-- We expect to have done a full action, not partial keys.
assert(type(handler) == 'function')
return result
end
function key_handler_common(code, shift, ctrl, alt, meta)
if M.strip_alt and CURSES and (meta or alt) then
-- Inject an ESC followed by the un-alt/meta key.
events.emit(events.KEYPRESS, 7, false, false, false, false)
events.emit(events.KEYPRESS, code, shift, ctrl, false, false)
return true
end
-- This logic borrowed from core/keys.lua from textadept.
local sym = code < 256 and (not CURSES or code ~= 7) and string.char(code) or
keys.KEYSYMS[code]
if not sym then return end -- ignore unknown keys
-- dbg("Code:", code)
if alt then sym = 'alt+' .. sym end
if ctrl then sym = 'ctrl+' .. sym end
if shift then sym = 'shift+' .. sym end -- Need to change for alphabetic
if state.pending_keyhandler ~= nil then
-- Call this instead
state.pending_keyhandler(sym)
state.pending_keyhandler = nil
return true
end
end
-- Various state we modify
state = {
numarg = 0, -- The numeric prefix (eg for 10j to go down 10 times)
last_numarg = 0, -- The last numeric argument used (for repeating previous)
regarg = nil, -- The pending register argument (eg "a)
pending_action = nil, -- An action waiting for a movement
pending_command = nil, -- The name of the editing command pending
pending_keyhandler = nil, -- A function to call on the next keypress
last_action = no_action,
marks = {},
last_insert_string = nil, -- Last inserted text
insert_pos = nil,
errmsg = '', -- error from a command
registers = {}, -- cut/paste registers
variables = { -- Configurable variables
grepprg = "grep -rn --devices=skip",
findprg = nil, -- Set to a program to use instead of Lua file find.
},
visual = { }, -- State for visual mode
}
-- Implement special register behaviour (eg upper case means append)
setmetatable(state.registers, {
__index = function(t, k)
-- For upper case register names, return the lower case
-- value.
local A, Z = string.byte("AZ", 1, 2)
local kb = string.byte(k)
if kb >= A and kb <= Z then
local lk = string.lower(k)
return rawget(t, lk)
end
return rawget(t, k)
end,
__newindex = function(t, k, v)
-- For upper case register names, append to the lower-case
-- register
local A, Z = string.byte("AZ", 1, 2)
local kb = string.byte(k)
local origval
if kb >= A and kb <= Z then
local lk = string.lower(k)
origval = rawget(t, lk)
if origval then
origval.text = origval.text .. v.text
v = origval
else
rawset(t, lk, v)
end
else
rawset(t, k, v)
end
-- The " register (unnamed) holds the last copied value,
-- unless the '_' register was used.
if k ~= '_' then
rawset(t, '"', v)
end
end,
})
-- Make state visible.
M.state = state
function M.err(msg)
state.errmsg = msg
end
function enter_replace()
enter_mode(mode_insert)
buffer.overtype = true
mode_command.restart = function()
buffer.overtype = false
end
end
function update_status()
local err = state.errmsg
local msg
if mode == nil then return end
if M._saved_keys == nil then return end -- mfx
if mode.name == COMMAND then
msg = "(command) "
elseif mode.name == VISUAL then
msg = "-- VISUAL -- "
else
msg = "-- INSERT -- "
end
msg = msg .. err
ui.statusbar_text = msg
--state.errmsg = ''
end
events.connect(events.UPDATE_UI, update_status)
local self_insert_mt = {
__index = function(tab, key)
if type(key) == "string" then
if string.len(key) == 1 then
return function() buffer.add_text(key) end
end
end
end,
}
local self_insert_tab = setmetatable({}, self_insert_mt)
--- Mark the start of some potential text entry.
local function insert_start_edit()
state.insert_pos = buffer.current_pos
end
function M.vi_cut(start, end_, linewise, register)
return vi_ops.cut({s=start, e=end_, movtype=linewise and MOV_LINE or MOV_INC}, register)
end
local vi_cut = M.vi_cut
local R = lpeg.R
local S = lpeg.S
local P = lpeg.P
local V = lpeg.V
local Cmt = lpeg.Cmt
local Cb = lpeg.Cb
local Cc = lpeg.Cc
local Cg = lpeg.Cg
local Cp = lpeg.Cp
local Carg = lpeg.Carg
-- LPeg pattern to match a number in a line, at a certain
-- minimum position.
local _num_dec = Cp() * (P"-" ^ -1) * R"09" ^ 1 * Cc("dec")
-- Assume lower case if no [a-f]
local _hex_start = P"0x" * Cp() * Cg(Cc("hex"), 'hextype')
-- The last letter will pass its
local _hex_char_upper = R"AF" * Cg(Cc("HEX"), 'hextype')
local _hex_char_lower = R"af" * Cg(Cc("hex"), 'hextype')
local _num_hex = _hex_start * (R"09" + _hex_char_lower + _hex_char_upper)^1 * Cb("hextype")
local _num_any = _num_hex + _num_dec
-- predicate to check that the number ends after a certain position,
-- which will be passed as the first extra argument.
local _ends_after = Cmt(Carg(1), function(subj, pos, col)
return pos > col
end)
-- Find it anywhere (first match)
-- Returns captures: startpos, base ("dec"/"hex"), endpos
local _find_num = P{ (_num_any * _ends_after * Cp()) + 1*V(1) }
-- Find a number under (or to the right of) the cursor
local function _find_number()
local line = buffer:get_cur_line()
local col = buffer.column[buffer.current_pos]
local linepos = buffer:position_from_line(buffer:line_from_position(buffer.current_pos))
local startpos, base, endpos = _find_num:match(line, 1, col-1)
if startpos ~= nil then
return base, linepos+startpos-1, linepos + endpos-1
else
return nil
end
end
local numtype_to_base = {
dec = 10,
hex = 16,
HEX = 16,
}
local numtype_to_fmt = {
dec = '%d',
hex = '%x',
HEX = '%X',
}
-- Increment the number under (or to the right of) the cursor by
-- increment (which may be negative).
function do_inc(increment)
local numtype, start_, end_ = _find_number()
if numtype == nil then return end
local numstr = buffer:text_range(start_, end_)
local val = tonumber(numstr, numtype_to_base[numtype])
val = val + increment
local newstr = string.format(numtype_to_fmt[numtype], val)
buffer:set_selection(start_, end_)
buffer:replace_sel(newstr)
end
local function make_reg_key(reg)
return function() state.regarg = reg end
end
local register_keys = {
}
for i = 0,25 do
local k = string.char(i + string.byte("a"))
register_keys[k] = make_reg_key(k)
local uk = string.upper(k)
register_keys[uk] = make_reg_key(uk)
end
--- Paste from a register (by default the unnamed register "")
-- If after is true, then will paste after the current character or line
-- (depending on whether the buffer was line or character based)
local function vi_paste(after, rpt, register)
local buf = state.registers[register or '"']
if not buf then return end
rpt = rpt or 1
local pos = buffer.current_pos
if buf.line then
local lineno = buffer:line_from_position(pos)
if after then
lineno = lineno + 1
if lineno > buffer.line_count then
-- add a line if necessary
buffer:line_end()
buffer:new_line()
end
end
pos = buffer:position_from_line(lineno)
buffer:goto_pos(pos)
assert(pos == buffer.current_pos)
local reported_line = buffer:line_from_position(pos)
assert(reported_line == lineno)
else
local lineno = buffer:line_from_position(pos)
local lineend = buffer.line_end_position[lineno]
if after and pos <= buffer.length and pos < lineend then
pos = pos + 1
end
end
for i=1, rpt do
buffer:insert_text(pos, buf.text)
end
if not buf.line then
buffer:goto_pos(pos + buf.text:len()*rpt - 1)
end
end
-- Return the inserted text. Can be called immediately after returning
-- from insert mode.
local function get_just_inserted_text()
local result = ""
-- If the cursor moved, then assume we've inserted text.
if state.insert_pos < buffer.current_pos then
local curpos = buffer.current_pos
buffer.set_selection(state.insert_pos, curpos)
result = buffer.get_sel_text()
buffer.clear_selections()
buffer.goto_pos(curpos)
end
return result
end
--- Mark the end of an edit (either exiting insert mode, or moving the
-- cursor).
local function insert_end_edit()
local text = get_just_inserted_text()
if text:len() > 0 then state.last_insert_string = text end
end
-- Start an undo action
local function begin_undo()
local bst = buf_state(buffer)
bst.undo_level = bst.undo_level or 0
assert(bst.undo_level == 0)
buffer:begin_undo_action()
bst.undo_level = bst.undo_level + 1
end
-- End an undo action
local function end_undo()
local bst = buf_state(buffer)
buffer:end_undo_action()
assert(bst.undo_level == 1)
bst.undo_level = bst.undo_level - 1
end
-- Break an insert action to be resumed (at another location/in another
-- buffer)
local function break_edit_start()
-- Cancel any autocomplete list if active
if buffer:auto_c_active() then
buffer:auto_c_cancel()
end
end_undo()
insert_end_edit()
end
-- Resume editing
local function break_edit_end()
insert_start_edit()
begin_undo()
end
--- Return a function which does the same as its argument, but also
-- restarts the undo action.
local function break_edit(f)
return function()
break_edit_start()
f()
break_edit_end()
end
end
-- Wraps a key handler function to pass the key through to the
-- autocomplete list if present.
local function allow_autoc(f)
return function()
if buffer:auto_c_active() then
-- Allow the next handler
return false
else
return f()
end
end
end
mode_insert = {
name = INSERT,
key_handler = function(code, shift, ctrl, alt, meta)
return key_handler_common(mode_insert.bindings, code, shift, ctrl, alt, meta)
end,
bindings = {
esc = function()
insert_end_edit()
local line, pos = buffer.get_cur_line()
if pos > 1 then buffer.char_left() end
enter_mode(mode_command)
end,
['ctrl+ '] = keys['ctrl+ '],
['ctrl+\n'] = keys['ctrl+\n'],
up = allow_autoc(break_edit(vi_up)),
down = allow_autoc(break_edit(vi_down)),
left = break_edit(buffer.char_left),
right = break_edit(buffer.char_right),
home = allow_autoc(break_edit(buffer.vc_home)),
['end'] = allow_autoc(break_edit(buffer.line_end)),
pgup = allow_autoc(break_edit(buffer.page_up)),
pgdn = allow_autoc(break_edit(buffer.page_down)),
-- These don't quite behave as vim, but they'll do for now.
['ctrl+p'] = M.vi_complete.complete_backwards,
['ctrl+n'] = M.vi_complete.complete_forwards,
['ctrl+v'] = self_insert_tab,
}
}
local function no_action() end
-- Run an action, as a single undoable action.
-- Passes the current repeat count (prefix count) and register arg to it,
-- and saves it to be recalled with '.'.
function do_action(action)
local saved_rpt = state.numarg
if saved_rpt < 1 then saved_rpt = 1 end
state.last_action = function(rpt)
rpt = rpt or saved_rpt
action(rpt)
end
raw_do_action(action)
end
-- Return the current numeric prefix (and clear it)
-- Returns nil if not set.
local function get_numarg()
local numarg = state.numarg
state.numarg = 0
if numarg == 0 then
return nil
else
return numarg
end
end
-- Return the current register prefix (and clear it)
-- Returns nil if not set.
local function get_regarg()
local regarg = state.regarg
state.regarg = nil
return regarg
end
-- Convert a motion table to a key function
local function motion2key(movdesc)
local movtype, mov_f, rep = table.unpack(movdesc)
if movtype == MOV_LATER then
-- Call the movement function with the right count.
return function()
mov_f(function (md)
motion2key(md)()
end)
end
else
-- Call the movement function with the right count.
return function()
local rpt = get_numarg()
if not(rpt and rpt > 0) then rpt = rep end
mov_f(rpt)
if movtype ~= MOV_LINE then buf_state(buffer).col = nil end
end
end
end
M.motion2key = motion2key
-- Like do_action but doesn't save to last_action
function raw_do_action(action)
local rpt = get_numarg() or 1
local regarg = get_regarg() or nil
begin_undo()
action(rpt, regarg)
end_undo()
end
function addarg(n)
state.numarg = state.numarg * 10 + n
dbg("New numarg: " .. tostring(state.numarg))
end
-- Return a handler for digit n
function dodigit(n)
return function() addarg(n) end
end
-- Valid movement types
MOV_LINE = 'linewise'
MOV_INC = 'inclusive'
MOV_EXC = 'exclusive'
MOV_LATER = 'later'
MOV_TYPES = {
[MOV_LINE] = true,
[MOV_INC] = true,
[MOV_EXC] = true,
}
-- Apply a movement command, which may be attached to an editing action.
local function do_movement(f, movtype)
assert(MOV_TYPES[movtype], "Invalid or missing motion type: [["..tostring(movtype).."]]")
if state.pending_action == nil then
-- no action, just move
f()
else
-- Select the region and apply
-- TODO: handle line-oriented actions differently
-- Allow the action to be repeated
do
local move = f
local action = state.pending_action
state.last_action = function (rpt)
local start = buffer.current_pos
move()
local end_ = buffer.current_pos
if start > end_ then
start, end_ = end_, start
end
if movtype == MOV_LINE then
start = buffer.position_from_line(buffer.line_from_position(start))
local line_end = buffer.line_from_position(end_)
end_ = buffer.position_from_line(line_end) +
buffer.line_length(line_end)
else
local endlineno = buffer:line_from_position(end_)
local endcol = end_ - buffer.position_from_line(endlineno)
if movtype == MOV_INC then
-- inclusive motion - include the last character
if end_ < buffer.text_length and
endcol < buffer:line_length(endlineno) then
end_ = end_ + 1
end
else
-- exclusive motion
-- If the end is at the start of a new line, then move it
-- back to the end for this.
if endcol == 0 and end_ > start then
end_ = buffer.line_end_position[endlineno-1]
end
end
end
action(start, end_, move, movtype == MOV_LINE)
end
end
state.last_action(1)
state.pending_action = nil
end
end
-- Wrap a function f(reg) into a repeatable one which takes a repeat count
-- g(rpt, reg). The reg parameter is optional.
local function repeatable(f)
return function(rpt, reg)
for i=1,rpt do f(reg) end
end
end
local function repeat_arg(f)
return function()
local times = state.numarg
state.numarg = 0
if times == 0 then times = 1 end
for i=1,times do
f()
end
end
end
-- Wrapper to turn a simple command into one which uses the numeric prefix
local function mk_movement(f, movtype)
-- Run f numarg times (if numarg is non-zero) and clear
-- numarg
return function()
do_movement(f, movtype)
-- If this was a horizontal movement, then forget what column
-- we were trying to stay in.
if movtype ~= MOV_LINE then buf_state(buffer).col = nil end
end
end
local function enter_command()
enter_mode(mode_command)
end
function M.enter_insert_then_end_undo(cb)
-- Save the numeric argument
local rpt = 1
if state.numarg > 0 then
rpt = state.numarg
state.numarg = 0
end
state.last_numarg = rpt
enter_mode(mode_insert)
insert_start_edit()
mode_command.restart = function()
end_undo()
if cb then cb() end
end
end
local enter_insert_then_end_undo = M.enter_insert_then_end_undo
local function enter_insert_with_undo(cb)
begin_undo()
enter_insert_then_end_undo(cb)
end
-- Helper function for doing a replace operation
local function do_replace(pos, s)
local slen = s:len()
local line_end = buffer.line_end_position[buffer:line_from_position(pos)]
local endpos = pos + slen
if endpos > line_end then endpos = line_end end
buffer:set_selection(pos, endpos)
buffer:replace_sel(s)
pos = pos + slen
buffer:clear_selections()
buffer:goto_pos(pos-1)
end
local function enter_replace_with_undo(cb)
begin_undo()
-- Save the numeric argument
local rpt = get_numarg() or 1
buffer.overtype = true
enter_mode(mode_insert)
insert_start_edit()
mode_command.restart = function()
buffer.overtype = false
if rpt > 1 then
do_replace(buffer.current_pos+1, string.rep(state.last_insert_string, rpt-1))
end
end_undo()
state.last_action = function(rpt)
local rpt = rpt or 1
begin_undo()
local pos = buffer.current_pos
local s = state.last_insert_string
do_replace(pos, s:rep(rpt))
end_undo()
buffer:goto_pos(pos+rpt*(s:len())-1)
end
end
end
--- Function to be called after an insert mode operation.
-- Sets the last action to call prep_f() to prepare (eg go to end of
-- line, etc.) and then insert the last-inserted text.
function M.post_insert(prep_f)
return function()
-- This function is run when exiting from undo
state.last_action = function(rpt)
local rpt = rpt or 1
begin_undo()
prep_f()
for i=1,rpt do
buffer.add_text(state.last_insert_string)
end
end_undo()
end
end
end
local post_insert = M.post_insert
-- Do a movement (with optional repeat override) and return the range
-- selected for an edit, taking into account inclusive/exclusive etc.
--
-- movdesc: { movtype, movf, rep }
-- rpt: 0 or an override repeat
--
-- returns movement descriptor:
-- {
-- s = <start pos>,
-- e = <end pos>,
-- movtype = <movement type>,
-- raws = <start pos not adjusted to line ends, for linewise>,
-- rawe = <end pos not adjusted to line ends, for linewise>,
-- }
local function movdesc_get_range_ex(movdesc, rpt_motion, rpt_cmd)
local movtype, movf, rep = table.unpack(movdesc)
if rpt_motion == nil or rpt_motion < 1 then rpt_motion = rep end
local cmdrep = rpt_cmd or 1
local rpt = rpt_motion * cmdrep
local start, end_ = movf(rpt)
local raws, rawe = start, end_
-- Now adjust the range depending on the movement class
if movtype == MOV_LINE then
start = buffer.position_from_line(buffer.line_from_position(start))
local line_end = buffer.line_from_position(end_)
end_ = buffer.position_from_line(line_end) +
buffer.line_length(line_end)
else
local endlineno = buffer:line_from_position(end_)
local endcol = end_ - buffer.position_from_line(endlineno)
if movtype == MOV_INC then
-- inclusive motion - include the last character
if end_ <= buffer.text_length and
endcol < buffer:line_length(endlineno) then
end_ = end_ + 1
end
else
-- exclusive motion
-- If the end is at the start of a new line, then move it
-- back to the end for this.
if endcol == 0 and end_ > start then
end_ = buffer.line_end_position[endlineno-1]
end
end
end
return { s=start, e=end_, movtype=movtype,
raws=raws, rawe=rawe }
end
-- Do a movement (with optional repeat override) and return the range
-- selected for an edit, taking into account inclusive/exclusive etc.
--
-- movdesc: { movtype, movf, rep }
-- rpt: 0 or an override repeat
--
-- returns start, end positions.
local function movdesc_get_range(movdesc, rpt_motion, rpt_cmd)
local movement = movdesc_get_range_ex(movdesc, rpt_motion, rpt_cmd)
return movement.s, movement.e
end
-- Return a table implementing an action which can take a motion, and
-- which does NOT involve insert mode.
-- Also handles taking care of being able to redo the action.
--
-- actions: a table -f non-motion bindings.
-- handler: a function called with (movement, start, end, movtype, reg)
-- movement is { s=<start>, e=<end>, movtype=movtype,
-- raws=<...>, rawe=<...>
-- s,e (start/end) are the selected range, and movtype is MOV_{INC,EXC,LINE}
-- for linewise, raws and rawe are the start/end locations before
-- adjusting to start/end of lines.
-- The handler should do its action. The system will take care of
-- saving the action to repeat, and undo/redo.
-- reg is a register parameter provided (eg with "ayw)
local function with_motion(actions, handler)
local function apply_action(mdesc)
local cmdrpt = get_numarg()
local reg = get_regarg()
local movement = movdesc_get_range_ex(mdesc, nil, cmdrpt)
begin_undo()
handler(movement, reg)
end_undo()
state.last_action = function(new_rpt)
local rpt = (new_rpt and new_rpt > 0) and new_rpt or cmdrpt
local movement = movdesc_get_range_ex(mdesc, rpt, 1)
begin_undo()
handler(movement, reg)
end_undo()
end
end
wrapped_handler = function(movdesc)
if movdesc[1] == MOV_LATER then
-- Special case - we don't get the action until later.
return function()
local mov_f = movdesc[2]
mov_f(function (mdesc)
apply_action(vi_motion.movf_to_self(mdesc))
end)
end
else
return function()
apply_action(movdesc)
end
end
end
return vi_motion.bind_motions(actions, wrapped_handler)
end
-- Return a table implementing an action which can take a motion, and
-- which involves text being entered in insert mode.
-- Also handles taking care of being able to redo the action.
--
-- actions: a table -f non-motion bindings.
-- handler: a function called with (start, end, movtype)
-- start/end are the selected range, and movtype is MOV_{INC,EXC,LINE}
-- The handler should do whatever needs doing before entering insert
-- mode and return. The system will handle entering insert mode and
-- being able to repeat, as well as undo.
local function with_motion_insert(actions, handler)
local function apply_action(movdesc)
local cmdrpt = get_numarg()
local regarg = get_regarg()
local movement = movdesc_get_range_ex(movdesc, nil, cmdrpt)
begin_undo()
handler(movement)
insert_start_edit()
enter_mode(mode_insert)
mode_command.restart = function()
local text = state.last_insert_string
end_undo()
state.last_action = function(new_rpt)
local rpt = (new_rpt and new_rpt > 0) and new_rpt or cmdrpt
local movement = movdesc_get_range_ex(movdesc, rpt, 1)
begin_undo()
handler(movement)
buffer:add_text(text)
end_undo()
end
end
end
wrapped_handler = function(movdesc)
if movdesc[1] == MOV_LATER then
-- Special case - we don't get the action until later.
return function()
local mov_f = movdesc[2]
mov_f(function (mdesc)
apply_action(vi_motion.movf_to_self(mdesc))
end)
end
else
return function()
apply_action(movdesc)
end
end
end
return vi_motion.bind_motions(actions, wrapped_handler)
end
-- Ask the user for some text, and return the text or nil.
function ask_string(prompt)
local idx, res
idx, res = ui.dialogs.inputbox{title=prompt}
if idx == 1 then return res end
end
-- Filename characters
FILENAME_CHARS = "abcdefghijklmnopqrstuvwxyz" ..
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" ..
"0123456789" ..
"_.-#,/"
-- Find a filename under the cursor and try to open that file.
-- If the filename is followed by :number, then go to that line in the file.
function find_filename_at_pos(pos)
local mypos = pos or buffer.current_pos
local s, e, filename = vi_ta_util.find_word_at(mypos, FILENAME_CHARS)
local lineno = nil
local colno = nil
if buffer:text_range(e, e+1) == ":" then
local _
_, _, linenostr = vi_ta_util.find_word_at(e+1, "0123456789")
if linenostr ~= nil then
lineno = tonumber(linenostr)
local ee = e + 1 + linenostr:len()
if buffer:text_range(ee, ee+1) == ":" then
_, _, colnostr = vi_ta_util.find_word_at(ee+1, "0123456789")
if colnostr ~= nil then
colno = tonumber(colnostr)
end
end
end
end
if filename:sub(1,1) == '/' or filename:sub(1,2) == "./" then
-- Absolute path: keep as is
elseif lfs.attributes(filename) then
-- The file exists right here, don't waste time searching.
else
-- Relative - find one
local paths = vi_find_files.find_matching_files(filename)
if paths and #paths >= 1 then
filename = paths[1]
else
filename = nil
end
end
if filename then
io.open_file(filename)
if lineno ~= nil then
buffer:goto_line(lineno)
if colno ~= nil and buffer:line_length(lineno) >= colno then
buffer.goto_pos(buffer.current_pos + (colno - 1))
end
end
return true
end
return false
end
M.find_filename_at_pos = find_filename_at_pos
-- Key binding which takes a motion, then prompts for two strings for
-- before and after, and wraps the region with that text.
surround_keys = vi_motion.bind_motions({
w = vi_motion.movf_to_self({ MOV_INC, vi_motion.r(vi_motions.word_end), 1}),
s = { MOV_LINE, vi_motions.el_line, 1 },
},
function(movdesc)
return function()
local cmdrpt = get_numarg()
local start, end_ = movdesc_get_range(movdesc, nil, cmdrpt)
local pre = ask_string('Pre text')
local post = ask_string('Post text')
if movdesc[1] == MOV_LINE then
pre = pre .. "\n"