-
Notifications
You must be signed in to change notification settings - Fork 5
/
vi_mode_ex.lua
993 lines (905 loc) · 30.2 KB
/
vi_mode_ex.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
-- Handle the ex buffer emulation
-- Modeled on textadept's command_entry.lua
local M = {}
local vi_tags = require('textadept-vi.vi_tags')
local vi_quickfix = require('textadept-vi.vi_quickfix')
local vi_regex = require('textadept-vi.regex.pegex')
local vi_entry
local vi_views = require('textadept-vi.vi_views')
local lpeg = require 'lpeg'
local vi_find_files = require 'textadept-vi.vi_find_files'
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local C, Cc, Cf, Cp, Ct, Carg, Cg = lpeg.C, lpeg.Cc, lpeg.Cf, lpeg.Cp, lpeg.Ct, lpeg.Carg, lpeg.Cg
-- Support for saving state over reset
local state = {
history = {},
histidx = 1,
clists = {}, -- Stack of { list=items, idx=n } for :clist etc.
clistidx = 0,
last_cmd = nil,
entry_state = nil, -- vi_entry state
cur_buf = nil, -- The current buffer before starting the entry
}
M.state = state
-- Save over a reset
events.connect(events.RESET_BEFORE, function()
-- stash state in the arg table. arg isn't available during reset,
-- but is restored afterwards.
_G.arg.vi_saved_state_ex = state
end)
events.connect(events.RESET_AFTER, function()
-- Restore saved state
local saved = _G.arg.vi_saved_state_ex
if saved then
state.history = saved.history
state.histidx = saved.histidx
state.clists = saved.clists or {}
state.clistidx = saved.clistidx or 0
_G.arg.vi_saved_state_ex = nil
end
end)
local ui_ce = ui.command_entry
local function relpath(path)
local curdir = lfs.abspath(lfs.currentdir())
local curlen = #curdir
if path:sub(1, curlen) == curdir then
return path:sub(curlen+2)
else
return path
end
end
-- Local wrapper which handles special expansions ("%" -> current filename)
local function get_matching_files(text, doescape)
-- Special case - a bare % becomes the current file's path.
if text == "%" then
local result = relpath(state.cur_buf.filename)
if doescape then
result = vi_find_files.glob_escape(result)
end
return { result }
end
return vi_find_files.matching_files(text, doescape)
end
local do_debug = false
local function dbg(...)
if do_debug then ui._print("ex", ...) end
end
-- Helper functions for parsing addresses
local function _curline()
return buffer:line_from_position(buffer.current_pos)
end
local function _lastline()
return buffer.line_count
end
local function _mark(m)
local markpos = vi_mode.state.marks[m:sub(2,2)]
if markpos ~= nil then
return buffer:line_from_position(markpos)
end
end
local function _tolinenum(a)
return tonumber(a)
end
local function _searchfwd(re)
local pat = vi_regex.compile(re)
local lineno = _curline()
for i=lineno,_lastline() do
local line = buffer:get_line(i)
if pat:match(line) then
return i
end
end
error("Pattern '"..re.."' not found from "..tostring(buffer.filename)..":"..lineno.." (lastline=".._lastline()..")")
end
-- Take two numbers and produce a range.
local function _mk_range(a, b)
return { a, b }
end
-- Take a single address and make a range
local function _mk_range_single(a)
return { a, a }
end
local function neg(a) return -a end
local function add(a,b) return a+b end
-- Pattern for matching an address. Returns a line number.
local ex_addr_num = (R"09" ^ 1) / _tolinenum
local ex_addr_here = (P".") / _curline
local ex_addr_end = (P"$") / _lastline
local ex_addr_mark = (P"'" * R"az") / _mark
-- A regular expressions.
local ex_quoted_slash = (P"\\/" + (1 - P"/"))
local ex_pattern_nonempty = ex_quoted_slash ^ 1
local ex_pattern = ex_pattern_nonempty + P(0)
local ex_addr_fwd = (P"/" * C(ex_pattern_nonempty ^ 1) * P"/") / _searchfwd
local ex_addr_base = ex_addr_num + ex_addr_here + ex_addr_end + ex_addr_mark + ex_addr_fwd
local addr_adder = (P"+" * ex_addr_num)
local addr_subber = (P"-" * ex_addr_num) / neg
local ex_addr = Cf(ex_addr_base * (addr_adder + addr_subber)^0, add) + Cf((P(0) / _curline) * (addr_adder + addr_subber)^1, add)
-- A range of '%' means the whole file
local ex_range_pct = P'%' / function() return _mk_range(1, _lastline()) end
-- And a range returns a pair of line numbers { start, end }
local ex_range = ((((ex_addr + P(0)/_curline) * "," * ex_addr)/_mk_range) + (ex_addr / _mk_range_single) + ex_range_pct + (P(0) * Cc(nil)))
local ex_ws = S" \t"
-- A simple command (plain words). TODO: add quoting.
local ex_cmd_simple = (C((1 - ex_ws) ^ 1) * (ex_ws ^ 0)) ^ 1
local function unquote_slash(s)
-- In () to lose the second return value
return (s:gsub("\\/", "/"))
end
-- The s command
local ex_cmd_s = C(P("s")) * P("/") * (ex_pattern/unquote_slash) * P("/") *
((ex_quoted_slash ^ 0)/unquote_slash) * P("/") * C(R("az")^0)
-- Shell command: !ls
-- Very basic word splitting - add quoting later.
local ex_cmd_shell = C(P("!")) * (C((1 - ex_ws) ^ 1) * (ex_ws ^ 0)) ^ 1
local ex_cmd = Ct(ex_cmd_s + ex_cmd_shell + ex_cmd_simple)
local ex_cmdline = ex_range * (ex_ws ^ 0) * ex_cmd
-- Parse an ex command, including optional range and command
function M.parse_ex_cmd(s)
local range, args = ex_cmdline:match(s)
return args, range
end
local function ex_error(msg)
vi_mode.err(msg)
end
local find_matching_files = vi_find_files.find_matching_files
-- Given a list of items, prompt the user to choose one.
local function choose_list(title, items, cb)
local list = textredux.core.list.new(title)
list.items = items
list.on_selection = function(l, item, shift, ctrl, alt, meta)
cb(item)
end
list.keys.esc = function() list:close() end
list:show()
end
local function get_buffer_by_type(buftype)
for n,buf in ipairs(_BUFFERS) do
if buf._type == buftype then
return buf
end
end
local buf = buffer.new()
buf._type = buftype
return buf
end
-- Given a list of items, prompt the user to choose one.
local function choose_list_lexed(buftype, lexer, clist)
local buf = get_buffer_by_type(buftype)
buf.read_only = false
buf.vi_data = {
clist = clist,
idx_to_pos = {}
}
buf:clear_all()
for i, item in ipairs(clist.list) do
buf.vi_data.idx_to_pos[i] = buf.length + 1
buf:append_text(item[1] .. "\n")
end
buf.read_only = true
buf:set_lexer(lexer)
view:goto_buffer(buf)
buf:goto_pos(buf.vi_data.idx_to_pos[clist.idx])
end
-- Jump to an item in a clist ({ text, path=filename, lineno=lineno, idx=idx })
-- Jump to a quickfix item
local function clist_go(item)
-- If no file/line, don't do anything.
if item.path and item.lineno then
io.open_file(item.path)
buffer.goto_line(item.lineno)
state.clists[state.clistidx].idx = item.idx
end
end
--- Expand a filename:
-- ~/foo -> $HOME/foo
local function expand_filename(s)
if s:sub(1,2) == "~/" then
s = os.getenv("HOME") .. s:sub(2)
end
local files = get_matching_files(s, false)
if #files >= 1 then return files[1] end
return s
end
-- Parse the replacement string
local repl_chars = C((P(1) - S'&\\')^1)
-- Relies on the table of groups being the first extra parameter to lpeg.match.
local repl_ref = P"\\" * (C(R"09") * Carg(1)) / function(ref, groups) return groups[ref] or "" end
local amp_ref = P"&" * Carg(1) /function(groups) return groups["&"] end
local repl_special = P"\\n" * Cc('\n')
local repl_quoted = P"\\" * C(P(1))
local repl_pat = Cf(Cc("")*((repl_chars + repl_ref + amp_ref + repl_special + repl_quoted) ^ 0), function(a,b) return a..b end)
local function command_substitute(args, range)
local searchpat = args[2]
local replace = args[3]
local flagstring = args[4]
local flags = {}
-- cme_log('subst: pat=[['..searchpat..']], repl=[['..replace..']], flags=[['..flagstring..']]')
for i=1,#flagstring do
flags[flagstring:sub(i,i)] = true
end
if range == nil then
local lineno = buffer:line_from_position(buffer.current_pos)
range = { lineno, lineno }
end
local pat = vi_regex.compile(searchpat)
if pat == nil then
ex_error("Bad pattern.")
return
end
buffer:begin_undo_action()
local lineno = range[1] -- Start or current line
local lastline = range[2] -- Finish line (may change if newlines inserted)
while lineno <= lastline do
local line = buffer:get_line(lineno)
line = line:gsub("\n", "") -- Remove any newline from the end.
local m = pat:match(line)
while m do
local groups = {}
if m.groups then
for k,v in pairs(m.groups or {}) do
local grp = line:sub(v[1], v[2])
groups[tostring(k)] = grp
end
end
groups["&"] = line:sub(m._start, m._end)
local repl = repl_pat:match(replace, 1, groups)
line = line:sub(1,m._start-1) .. repl .. line:sub(m._end+1)
-- Keep looking?
if flags.g then
m = pat:match(line, m._start + #repl)
else
break
end
end
-- Do the replace
local linepos = buffer:position_from_line(lineno)
local linelength = buffer.line_end_position[lineno] - buffer.position_from_line(lineno)
buffer:set_selection(linepos+linelength, linepos)
buffer:replace_sel(line)
local _, nlcount = line:gsub("\n", "")
-- Account for any inserted newlines.
lineno = lineno + 1 + nlcount
lastline = lastline + nlcount
end
buffer:end_undo_action()
end
-- Take a buffer with error messages, and turn it into a quickfix list,
-- which is activated.
-- Returns true if it created a quickfix list.
local function choose_errors_from_buf(buf)
local results = vi_quickfix.quickfix_from_buffer(buf)
if results then
-- Push the results list to the stack
state.clistidx = #state.clists+1
state.clists[state.clistidx] = { list=results, idx=1 }
-- choose_list('Errors', results, cb)
return true
end
end
-- Wrapper around clist_go which also annotates the destination buffer.
local function clist_go_annotate(item)
if item.path and item.lineno then
io.open_file(item.path)
buffer:goto_line(item.lineno-1)
buffer:annotation_clear_all()
buffer.annotation_visible = buffer.ANNOTATION_STANDARD
for _,erritem in ipairs(state.clists[state.clistidx].list) do
if erritem.path == item.path then
local msg = erritem.message
local prevmsg = buffer.annotation_text[erritem.lineno-1]
if prevmsg and #prevmsg > 0 then
msg = prevmsg .. "\n" .. msg
end
buffer.annotation_text[erritem.lineno-1] = msg
buffer.annotation_style[erritem.lineno-1] = 8 -- error style
end
end
state.clists[state.clistidx].idx = item.idx
end
end
-- As choose_errors_from_buf, but with a callback which also annotates
-- the destination buffer with errors.
local function choose_errors_annotated_from_buf(buf)
if choose_errors_from_buf(buf) then
local clist = state.clists[state.clistidx]
-- Annotate any open buffers with matching filenames
local path_to_buffer = {}
for _, error in ipairs(clist.list) do
local buf = path_to_buffer[error.path]
if buf == nil then
buf = false -- If we don't find it
for _, b in ipairs(_G._BUFFERS) do
if b.filename == error.path then
buf = b
break
end
end
-- Cache it as we expect to see the same file again
path_to_buffer[error.path] = buf
if buf then
-- The first time we've found this buffer, so clear any annotations
buf:annotation_clear_all()
end
end
if buf then
buf.annotation_visible = buffer.ANNOTATION_STANDARD
local msg = error.message
local prevmsg = buf.annotation_text[error.lineno]
if prevmsg and #prevmsg > 0 then
msg = prevmsg .. "\n" .. msg
end
buf.annotation_text[error.lineno] = msg
buf.annotation_style[error.lineno] = 8 -- error style
end
end
end
end
-- Spawn a command, which will write its output to a buffer in the
-- background, and call a function when finished.
--
-- command: a table of the command line
-- workdir: The working directory the command should run in.
-- buftype: the buffer type (eg "*make*"), which will be created or cleared.
-- when_finished: a function called with the buffer when the process
-- exits.
function command_to_buffer(command, workdir, buftype, lexer, when_finished, read_only)
local msgbuf = get_buffer_by_type(buftype)
-- Clear the buffer
msgbuf.read_only = false
msgbuf:clear_all()
if lexer then
msgbuf:set_lexer(lexer)
end
ui._print(buftype, "Running: " .. table.concat(command, " "))
local function getoutput(s)
local cur_view = view
local cur_buf
local my_view
-- Search for a view with this buffer
for i,v in ipairs(_VIEWS) do
if v.buffer == msgbuf then
my_view = v
break
end
end
if my_view then
if cur_view ~= my_view then
ui.goto_view(my_view)
end
msgbuf:append_text(s)
--msgbuf:goto_pos(msgbuf.length)
msgbuf:set_save_point()
if my_view ~= cur_view then
ui.goto_view(cur_view)
end
end
end
local function endproc(status)
msgbuf:append_text('Finished:' .. table.concat(command, " ") .. ' with status ' .. tostring(status))
msgbuf:set_save_point()
if read_only then
msgbuf.read_only = true
end
if when_finished ~= nil then
when_finished(msgbuf)
end
end
msgbuf.ta_data = {}
msgbuf.ta_data.proc = spawn(table.concat(command, " "), workdir, getoutput, getoutput, endproc)
end
M.ex_commands = {
e = function(args)
-- dbg("In e handler")
if args[2] ~= nil then
local filename = expand_filename(args[2])
io.open_file(filename)
else
ex_error("No filename to open")
end
end,
find = function(args)
local files = find_matching_files(args[2])
if #files == 1 then
io.open_file(files[1])
elseif #files == 0 then
ex_error("No files found: " .. #files)
else
choose_list('Choose file', files, io.open_file)
end
end,
w = function(args)
--dbg("Fn:" .. tostring(_G.buffer.filename))
if #args == 2 then
buffer:save_as(args[2])
elseif #args == 1 then
buffer:save()
else
ex_error("Too many arguments to :"..args[1])
end
end,
wn = function(args)
if #args ~= 1 then ex_error("Too many arguments to :"..args[1]); return end
M.ex_commands.w(args)
M.ex_commands.n(args)
end,
wN = function(args)
if #args ~= 1 then ex_error("Too many arguments to :"..args[1]); return end
M.ex_commands.w(args)
M.ex_commands.N(args)
end,
wq = function(args)
if #args ~= 1 then ex_error("Too many arguments to :"..args[1]); return end
M.ex_commands.w(args)
M.ex_commands.q(args)
end,
x = function(args)
if #args ~= 1 then ex_error("Too many arguments to :"..args[1]); return end
if buffer.modify then
M.ex_commands.w(args)
end
M.ex_commands.q(args)
end,
n = function(args)
if #args ~= 1 then ex_error("Too many arguments to :"..args[1]); return end
view:goto_buffer(1)
end,
['ne'] = function(args) M.ex_commands.n(args) end,
['nex'] = function(args) M.ex_commands.n(args) end,
['next'] = function(args) M.ex_commands.n(args) end,
['n!'] = function(args) M.ex_commands.n(args) end,
['ne!'] = function(args) M.ex_commands.n(args) end,
['nex!'] = function(args) M.ex_commands.n(args) end,
['next!'] = function(args) M.ex_commands.n(args) end,
N = function(args)
if #args ~= 1 then ex_error("Too many arguments to :"..args[1]); return end
view:goto_buffer(-1)
end,
['N!'] = function(args) M.ex_commands.N(args) end,
b = function(args)
if #args > 1 then
local bufname = args[2]
-- Try as a regular expression too.
local bufpat = vi_regex.compile(bufname)
for i, buf in ipairs(_BUFFERS) do
if buf and buf.filename and ((bufpat and bufpat:match(buf.filename)) or buf.filename:find(bufname, 1, true)) then
-- TODO: handle more than one matching
view:goto_buffer(buf)
return
end
end
end
end,
buffers = function(args)
ui.switch_buffer()
end,
bdelete = function(args)
if #args > 1 then
ex_error("Arguments to bdelete not supported yet.")
else
buffer:close()
end
end,
q = function(args)
-- Quit
dbg("in q")
if #_VIEWS == 1 then
-- Only one view, so quit.
quit()
else
-- there are split views. view.unsplit closes the *other*
-- splits to leave the current view; we want :q to do the
-- opposite and close this one.
vi_views.close_siblings_of(view)
end
end,
['q!'] = function(args)
-- force quit
events.connect(events.QUIT, function() return false end, 1)
quit()
end,
only = function(args)
-- Quit
if #_VIEWS > 1 then
view.unsplit(view)
end
end,
split = function(args)
view.split(view, false)
if args[2] then
local filename = expand_filename(args[2])
io.open_file(filename)
end
end,
vsplit = function(args)
view.split(view, true)
if args[2] then
local filename = expand_filename(args[2])
io.open_file(filename)
end
end,
ds = function(args)
local st = ui.get_split_table()
local function dumpsplit(t, indent)
if t.split then
ui.print(indent.."View:", tostring(t))
else
ui.print(indent.."Split: ver=".. tostring(t.vertical))
dumpsplit(t[1], indent.." ")
dumpsplit(t[2], indent.." ")
end
end
dumpsplit(st, "")
end,
reset = function(args)
reset()
end,
-- Build things
make = function(args)
local command = {"make"}
for i=2,#args do
command[#command+1] = args[i]
end
-- Remove existing annotations on all buffers
for _,b in ipairs(_BUFFERS) do
b:annotation_clear_all()
end
M.run_compile_command(command)
end,
-- Search files
grep = function(args)
local pat = args[2]
if not pat then return end
local cmd = {}
local grepprg = vi_mode.state.variables.grepprg
if type(grepprg) == 'string' then
cmd[#cmd+1] = grepprg
else
-- Assume a table
for _,arg in ipairs(grepprg) do
cmd[#cmd+1] = arg
end
end
-- Append arguments
for i = 2,#args do
cmd[#cmd+1] = args[i]
end
if #args <= 2 then
-- Append an implicit '.' path
cmd[#cmd+1] = '.'
end
command_to_buffer(cmd, ".", "*grep*", "tavi_grep", choose_errors_from_buf, true)
end,
['!'] = function(args, range)
local command = {}
for i=2,#args do
command[#command+1] = args[i]
end
if range == nil then
ui.print("Running: " .. table.concat(command, " "))
command_to_buffer(command, "./", "*shell*")
else
buffer:set_selection(buffer:position_from_line(range[2]+1),
buffer:position_from_line(range[1]))
textadept.editing.filter_through(table.concat(command, " "))
end
end,
cb = function(args)
choose_errors_from_buf(buffer)
end,
cn = function(args)
local clist = state.clists[state.clistidx]
if not clist then
ex_error("No clist")
return
end
local idx = clist.idx
if idx >= #clist.list then
ex_error("End of list")
else
clist_go(clist.list[idx+1])
end
end,
cp = function(args)
local clist = state.clists[state.clistidx]
if not clist then
ex_error("No clist")
return
end
local idx = clist.idx
if idx <= 1 then
ex_error("Start of list")
else
clist_go(clist.list[idx-1])
end
end,
clist = function(args)
local clist = state.clists[state.clistidx]
if not clist then
ex_error("No clist")
return
end
choose_list_lexed('*grep*', 'tavi_grep', clist)
end,
colder = function(args)
if state.clistidx > 1 then
state.clistidx = state.clistidx - 1
end
ex_error("List " .. tostring(state.clistidx) .. " of "
.. tostring(#state.clists))
end,
cnewer = function(args)
if state.clistidx < #state.clists then
state.clistidx = state.clistidx + 1
end
ex_error("List " .. tostring(state.clistidx) .. " of "
.. tostring(#state.clists))
end,
-- Tags
tag = function(args)
local tname = args[2]
local loc = vi_tags.find_tag_exact(tname)
if loc then
vi_tags.goto_tag(loc)
else
ex_error("Tag not found")
end
end,
tn = function(args)
local loc = vi_tags.tag_next()
if loc then
vi_tags.goto_tag(loc)
else
ex_error("No more tags")
end
end,
tp = function(args)
local loc = vi_tags.tag_prev()
if loc then
vi_tags.goto_tag(loc)
else
ex_error("No more tags")
end
end,
tsel = function(args)
local tname = args[2]
local loc1
if tname then
loc1 = vi_tags.find_tag_exact(tname)
if not loc1 then
ex_error("Tag not found")
return
end
end
-- We know there's at least one match
local tags = vi_tags.get_all()
if not tags then
ex_error("No tags")
return
end
if #tags == 1 then
-- Only one, just jump to it.
vi_tags.goto_tag(tags[1])
else
local items = {}
for i,t in ipairs(tags) do
items[#items+1] = { t.filename, t.excmd, tag=t }
end
choose_list('Choose tag', items, function(item)
vi_tags.goto_tag(item.tag)
end)
end
end,
s = command_substitute,
-- Some commands for textadept functionality.
compile = textadept.run.compile,
build = function()
for _,buf in ipairs(_BUFFERS) do
if buf._type == _L['[Message Buffer]'] then
buf:clear_all()
break
end
end
textadept.run.build()
end,
run = textadept.run.run,
}
keys.tavi_grep = {
['\n'] = function()
if buffer.vi_data and buffer.vi_data.idx_to_pos and buffer.vi_data.clist then
local cpos = buffer.current_pos
local idx = 0
-- Linear search. Could do a binary search if this gets
-- too slow.
for i, pos in ipairs(buffer.vi_data.idx_to_pos) do
if pos <= cpos then
idx = i
else
-- Overshot
break
end
end
if idx > 0 then
buffer.vi_data.clist.idx = idx
end
clist_go(buffer.vi_data.clist.list[idx])
else
-- We haven't got the list data, so see if we can find some.
buffer:home()
vi_mode.find_filename_at_pos()
end
end,
['ctrl+c'] = function()
-- Kill the process if possible
if buffer and buffer.ta_data and buffer.ta_data.proc then
buffer.ta_data.proc:kill()
end
end
}
keys.tavi_make = {
['\n'] = function()
buffer:home()
local lineno = buffer:line_from_position(buffer.current_pos)
local clist = state.clists[state.clistidx]
if clist then
clist.idx = lineno
end
local errmsg = buffer:get_line(lineno)
local errline = lineno + 1
while errline < buffer.line_count do
local line = buffer:get_line(errline)
local matchlen = line:match("^[ %d]* | ()")
if matchlen then
errmsg = errmsg .. line:sub(matchlen)
else
break
end
errline = errline + 1
end
if vi_mode.find_filename_at_pos() then
-- Succeeded
local lineno = buffer:line_from_position(buffer.current_pos)
buffer.annotation_text[lineno] = errmsg
buffer.annotation_style[lineno] = 9
view.annotation_visible = view.ANNOTATION_STANDARD
end
end,
['ctrl+c'] = function()
-- Kill the process if possible
if buffer and buffer.ta_data and buffer.ta_data.proc then
buffer.ta_data.proc:kill()
end
end
}
local function errhandler(msg)
local fullmsg = debug.traceback(msg)
return fullmsg
end
local function debugwrap(f)
local function wrapped(...)
ok, rest = xpcall(f, errhandler, ...)
if ok then
return rest
else
ui._print("lua errors", rest)
end
end
return wrapped
end
local function handle_ex_command(command)
local result
if not command:match("^%s*$") then
ui.statusbar_text = "Ex: "..command
state.history[state.histidx] = command
local cmd, range = M.parse_ex_cmd(command)
-- For now, a very simple command parser
local handler = M.ex_commands[cmd[1]]
ui.command_entry.entry_text = ""
if handler ~= nil then
handler = debugwrap(handler)
state.last_cmd = command
result = handler(cmd, range)
else
ex_error("Bad command <" .. tostring(cmd[1]) .. ">")
end
end
if result ~= nil then
return result
else
return false -- make sure this isn't handled again
end
end
-- Handle a completion.
-- Given a list of completions, and a function to get the string to complete,
-- do the right thing:
-- if nil or empty, give error
-- if one option, substitute it in directly
-- otherwise, prompt with the list.
local function do_complete_simple(pos, names)
if (not names) or #names == 0 then
ex_error("No completions")
elseif #names == 1 then
-- Substitute directly
ui_ce.entry_text = string.sub(ui_ce.entry_text, 1, pos-1) .. names[1]
else
-- Several completions
ui_ce.show_completions(names)
end
end
local function matching_buffers(text)
local buffers = {}
if text == nil or text == '' then
-- Match any filename if no pattern given.
text = "."
end
local pat = vi_regex.compile(text)
for k,buf in ipairs(_BUFFERS) do
if buf.filename and pat and pat:match(buf.filename) then
buffers[#buffers+1] = buf.filename
end
end
return buffers
end
-- text_suffix is the part of the word after the cursor (if any)
local function matching_commands(text, text_suffix)
local commands = {}
local tlen = #text
for k,_ in pairs(M.ex_commands) do
if k:sub(1, tlen) == text then
commands[#commands+1] = k
end
end
return commands
end
-- Completers for the new entry method
M.completions_word = {
b = matching_buffers,
e = function(text) return get_matching_files(text, true) end,
w = vi_find_files.matching_files_nopat,
wq = vi_find_files.matching_files_nopat,
x = vi_find_files.matching_files_nopat,
split = get_matching_files,
vsplit = get_matching_files,
tag = vi_tags.match_tag,
tsel = vi_tags.match_tag,
find = find_matching_files,
grep = get_matching_files, -- for the search root
}
local function do_complete(word, cmd, word_suffix)
if cmd and M.completions_word[cmd] then
return M.completions_word[cmd](word, word_suffix)
elseif cmd == word then
return matching_commands(cmd, word_suffix)
else
return {}
end
end
vi_entry = require('textadept-vi.vi_ce_entry')
state.entry_state = vi_entry.new(':', handle_ex_command, do_complete)
function M.start(exitfunc)
state.exitfunc = exitfunc
state.histidx = #state.history + 1 -- new command is after the end of the history
-- If using vi_entry, the current buffer won't be easily available.
state.cur_buf = buffer
state.entry_state:start()
end
-- Run a compile command and annotate the current buffer with any errors.
function M.run_compile_command(command)
buffer:annotation_clear_all()
command_to_buffer(command, "./", "*make*", "tavi_make", choose_errors_annotated_from_buf, true)
end
--- Run an ex command that may not have come directly from the command line.
function M.run_ex_command(text)
handle_ex_command(text)
end
-- Repeat the previous command, if any.
function M.repeat_last_command()
if state.last_cmd then
handle_ex_command(state.last_cmd)
end
end
--- Add a new custom ex command.
function M.add_ex_command(name, handler, completer)
M.ex_commands[name] = handler
end
return M