forked from ProjectAppie/clink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclink.lua
More file actions
3420 lines (2894 loc) · 106 KB
/
clink.lua
File metadata and controls
3420 lines (2894 loc) · 106 KB
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
--
-- Copyright (c) 2012 Martin Ridgers
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
--------------------------------------------------------------------------------
clink.matches = {}
clink.generators = {}
clink.prompt = {}
clink.prompt.filters = {}
--------------------------------------------------------------------------------
function clink.compute_lcd(text, list)
local list_n = #list
if list_n < 2 then
return
end
-- Find min and max limits
local max = 100000
for i = 1, #list, 1 do
local j = #(list[i])
if max > j then
max = j
end
end
-- For each character in the search range...
local mid = #text
local lcd = ""
for i = 1, max, 1 do
local same = true
local l = list[1]:sub(i, i)
local m = l:lower()
-- Compare character at the index with each other character in the
-- other matches.
for j = 2, list_n, 1 do
local n = list[j]:sub(i, i):lower()
if m ~= n then
same = false
break
end
end
-- If all characters match then use first match's character.
if same then
lcd = lcd..l
else
-- Otherwise use what the user's typed or if we're past that then
-- bail out.
if i <= mid then
lcd = lcd..text:sub(i, i)
else
break
end
end
end
return lcd
end
--------------------------------------------------------------------------------
function clink.is_single_match(matches)
if #matches <= 1 then
return true
end
local first = matches[1]:lower()
for i = 2, #matches, 1 do
if first ~= matches[i]:lower() then
return false
end
end
return true
end
--------------------------------------------------------------------------------
function clink.is_point_in_quote(str, i)
if i > #str then
i = #str
end
local c = 1
local q = string.byte("\"")
for j = 1, i do
if string.byte(str, j) == q then
c = c * -1
end
end
if c < 0 then
return true
end
return false
end
--------------------------------------------------------------------------------
function clink.adjust_for_separator(buffer, point, first, last)
local seps = nil
if clink.get_host_process() == "cmd.exe" then
seps = "|&"
end
if seps then
-- Find any valid command separators and if found, manipulate the
-- completion state a little bit.
local leading = buffer:sub(1, first - 1)
-- regex is: <sep> <not_seps> <eol>
local regex = "["..seps.."]([^"..seps.."]*)$"
local sep_found, _, post_sep = leading:find(regex)
if sep_found and not clink.is_point_in_quote(leading, sep_found) then
local delta = #leading - #post_sep
buffer = buffer:sub(delta + 1)
first = first - delta
last = last - delta
point = point - delta
if first < 1 then
first = 1
end
end
end
return buffer, point, first, last
end
--------------------------------------------------------------------------------
function clink.generate_matches(text, first, last)
local line_buffer
local point
line_buffer, point, first, last = clink.adjust_for_separator(
rl_state.line_buffer,
rl_state.point,
first,
last
)
rl_state.line_buffer = line_buffer
rl_state.point = point
clink.matches = {}
clink.match_display_filter = nil
for _, generator in ipairs(clink.generators) do
if generator.f(text, first, last) == true then
if #clink.matches > 1 then
-- Catch instances where there's many entries of a single match
if clink.is_single_match(clink.matches) then
clink.matches = { clink.matches[1] }
return true;
end
-- First entry in the match list should be the user's input,
-- modified here to be the lowest common denominator.
local lcd = clink.compute_lcd(text, clink.matches)
table.insert(clink.matches, 1, lcd)
end
return true
end
end
return false
end
--------------------------------------------------------------------------------
function clink.add_match(match)
if type(match) == "table" then
for _, i in ipairs(match) do
table.insert(clink.matches, i)
end
return
end
table.insert(clink.matches, match)
end
--------------------------------------------------------------------------------
function clink.register_match_generator(func, priority)
if priority == nil then
priority = 999
end
table.insert(clink.generators, {f=func, p=priority})
table.sort(clink.generators, function(a, b) return a["p"] < b["p"] end)
end
--------------------------------------------------------------------------------
function clink.is_match(needle, candidate)
if needle == nil then
error("Nil needle value when calling clink.is_match()", 2)
end
if clink.lower(candidate:sub(1, #needle)) == clink.lower(needle) then
return true
end
return false
end
--------------------------------------------------------------------------------
function clink.match_count()
return #clink.matches
end
--------------------------------------------------------------------------------
function clink.set_match(i, value)
clink.matches[i] = value
end
--------------------------------------------------------------------------------
function clink.get_match(i)
return clink.matches[i]
end
--------------------------------------------------------------------------------
function clink.match_words(text, words)
local count = clink.match_count()
for _, i in ipairs(words) do
if clink.is_match(text, i) then
clink.add_match(i)
end
end
return clink.match_count() - count
end
--------------------------------------------------------------------------------
function clink.match_files(pattern, full_path, find_func)
-- Fill out default values
if type(find_func) ~= "function" then
find_func = clink.find_files
end
if full_path == nil then
full_path = true
end
if pattern == nil then
pattern = "*"
end
-- Glob files.
pattern = pattern:gsub("/", "\\")
local glob = find_func(pattern, true)
-- Get glob's base.
local base = ""
local i = pattern:find("[\\:][^\\:]*$")
if i and full_path then
base = pattern:sub(1, i)
end
-- Match them.
local count = clink.match_count()
for _, i in ipairs(glob) do
local full = base..i
clink.add_match(full)
end
return clink.match_count() - count
end
--------------------------------------------------------------------------------
function clink.split(str, sep)
local i = 1
local ret = {}
for _, j in function() return str:find(sep, i, true) end do
table.insert(ret, str:sub(i, j - 1))
i = j + 1
end
table.insert(ret, str:sub(i, j))
return ret
end
--------------------------------------------------------------------------------
function clink.quote_split(str, ql, qr)
if not qr then
qr = ql
end
-- First parse in "pre[ql]quote_string[qr]" chunks
local insert = table.insert
local i = 1
local needle = "%b"..ql..qr
local parts = {}
for l, r, quote in function() return str:find(needle, i) end do
-- "pre"
if l > 1 then
insert(parts, str:sub(i, l - 1))
end
-- "quote_string"
insert(parts, str:sub(l, r))
i = r + 1
end
-- Second parse what remains as "pre[ql]being_quoted"
local l = str:find(ql, i, true)
if l then
-- "pre"
if l > 1 then
insert(parts, str:sub(i, l - 1))
end
-- "being_quoted"
insert(parts, str:sub(l))
elseif i <= #str then
-- Finally add whatever remains...
insert(parts, str:sub(i))
end
return parts
end
--------------------------------------------------------------------------------
function clink.prompt.register_filter(filter, priority)
if priority == nil then
priority = 999
end
table.insert(clink.prompt.filters, {f=filter, p=priority})
table.sort(clink.prompt.filters, function(a, b) return a["p"] < b["p"] end)
end
--------------------------------------------------------------------------------
function clink.filter_prompt(prompt)
local function add_ansi_codes(p)
local c = tonumber(clink.get_setting_int("prompt_colour"))
if c < 0 then
return p
end
c = c % 16
--[[
<4 >=4 %2
0 0 0 Black 4 1 -3 Blue 0
1 4 3 Red 5 5 0 Magenta 1
2 2 0 Green 6 3 -3 Cyan 0
3 6 3 Yellow 7 7 0 Gray 1
--]]
-- Convert from cmd.exe colour indices to ANSI ones.
local colour_id = c % 8
if (colour_id % 2) == 1 then
if colour_id < 4 then
c = c + 3
end
elseif colour_id >= 4 then
c = c - 3
end
-- Clamp
if c > 15 then
c = 15
end
-- Build ANSI code
local code = "\x1b[0;"
if c > 7 then
c = c - 8
code = code.."1;"
end
code = code..(c + 30).."m"
return code..p.."\x1b[0m"
end
clink.prompt.value = prompt
for _, filter in ipairs(clink.prompt.filters) do
if filter.f() == true then
return add_ansi_codes(clink.prompt.value)
end
end
return add_ansi_codes(clink.prompt.value)
end
-- vim: expandtab
--
-- Copyright (c) 2012 Martin Ridgers
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
--------------------------------------------------------------------------------
clink.arg = {}
--------------------------------------------------------------------------------
local parsers = {}
local is_parser
local is_sub_parser
local new_sub_parser
local parser_go_impl
local merge_parsers
local parser_meta_table = {}
local sub_parser_meta_table = {}
--------------------------------------------------------------------------------
function parser_meta_table.__concat(lhs, rhs)
if not is_parser(rhs) then
error("Right-handside must be parser.", 2)
end
local t = type(lhs)
if t == "table" then
local ret = {}
for _, i in ipairs(lhs) do
table.insert(ret, i .. rhs)
end
return ret
elseif t ~= "string" then
error("Left-handside must be a string or a table.", 2)
end
return new_sub_parser(lhs, rhs)
end
--------------------------------------------------------------------------------
local function unfold_table(source, target)
for _, i in ipairs(source) do
if type(i) == "table" and getmetatable(i) == nil then
unfold_table(i, target)
else
table.insert(target, i)
end
end
end
--------------------------------------------------------------------------------
local function parser_is_flag(parser, part)
if part == nil then
return false
end
local prefix = part:sub(1, 1)
return prefix == "-" or prefix == "/"
end
--------------------------------------------------------------------------------
local function parser_add_arguments(parser, ...)
for _, i in ipairs({...}) do
-- Check all arguments are tables.
if type(i) ~= "table" then
error("All arguments to add_arguments() must be tables.", 2)
end
-- Only parsers are allowed to be specified without being wrapped in a
-- containing table.
if getmetatable(i) ~= nil then
if is_parser(i) then
table.insert(parser.arguments, i)
else
error("Tables can't have meta-tables.", 2)
end
else
-- Expand out nested tables and insert into object's arguments table.
local arguments = {}
unfold_table(i, arguments)
table.insert(parser.arguments, arguments)
end
end
return parser
end
--------------------------------------------------------------------------------
local function parser_set_arguments(parser, ...)
parser.arguments = {}
return parser:add_arguments(...)
end
--------------------------------------------------------------------------------
local function parser_add_flags(parser, ...)
local flags = {}
unfold_table({...}, flags)
-- Validate the specified flags.
for _, i in ipairs(flags) do
if is_sub_parser(i) then
i = i.key
end
-- Check all flags are strings.
if type(i) ~= "string" then
error("All parser flags must be strings. Found "..type(i), 2)
end
-- Check all flags start with a - or a /
if not parser:is_flag(i) then
error("Flags must begin with a '-' or a '/'", 2)
end
end
-- Append flags to parser's existing table of flags.
for _, i in ipairs(flags) do
table.insert(parser.flags, i)
end
return parser
end
--------------------------------------------------------------------------------
local function parser_set_flags(parser, ...)
parser.flags = {}
return parser:add_flags(...)
end
--------------------------------------------------------------------------------
local function parser_flatten_argument(parser, index, func_thunk)
-- Sanity check the 'index' param to make sure it's valid.
if type(index) == "number" then
if index <= 0 or index > #parser.arguments then
return parser.use_file_matching
end
end
-- index == nil is a special case that returns the parser's flags
local opts = {}
local arg_opts
if index == nil then
arg_opts = parser.flags
else
arg_opts = parser.arguments[index]
end
-- Convert each argument option into a string and collect them in a table.
for _, i in ipairs(arg_opts) do
if is_sub_parser(i) then
table.insert(opts, i.key)
else
local t = type(i)
if t == "function" then
local results = func_thunk(i)
local t = type(results)
if not results then
return parser.use_file_matching
elseif t == "boolean" then
return (results and parser.use_file_matching)
elseif t == "table" then
for _, j in ipairs(results) do
table.insert(opts, j)
end
end
elseif t == "string" or t == "number" then
table.insert(opts, tostring(i))
end
end
end
return opts
end
--------------------------------------------------------------------------------
local function parser_go_args(parser, state)
local exhausted_args = false
local exhausted_parts = false
local part = state.parts[state.part_index]
local arg_index = state.arg_index
local arg_opts = parser.arguments[arg_index]
local arg_count = #parser.arguments
-- Is the next argument a parser? Parse control directly on to it.
if is_parser(arg_opts) then
state.arg_index = 1
return parser_go_impl(arg_opts, state)
end
-- Advance parts state.
state.part_index = state.part_index + 1
if state.part_index > #state.parts then
exhausted_parts = true
end
-- Advance argument state.
state.arg_index = arg_index + 1
if arg_index > arg_count then
exhausted_args = true
end
-- We've exhausted all available arguments. We either loop or we're done.
if parser.loop_point > 0 and state.arg_index > arg_count then
state.arg_index = parser.loop_point
if state.arg_index > arg_count then
state.arg_index = arg_count
end
end
-- Is there some state to process?
if not exhausted_parts and not exhausted_args then
local exact = false
for _, arg_opt in ipairs(arg_opts) do
-- Is the argument a key to a sub-parser? If so then hand control
-- off to it.
if is_sub_parser(arg_opt) then
if arg_opt.key == part then
state.arg_index = 1
return parser_go_impl(arg_opt.parser, state)
end
end
-- Check so see if the part has an exact match in the argument. Note
-- that only string-type options are considered.
if type(arg_opt) == "string" then
exact = exact or arg_opt == part
else
exact = true
end
end
-- If the parser's required to be precise then check here.
if parser.precise and not exact then
exhausted_args = true
else
return nil
end
end
-- If we've no more arguments to traverse but there's still parts remaining
-- then we start skipping arguments but keep going so that flags still get
-- parsed (as flags have no position).
if exhausted_args then
state.part_index = state.part_index - 1
if not exhausted_parts then
if state.depth <= 1 then
state.skip_args = true
return
end
return parser.use_file_matching
end
end
-- Now we've an index into the parser's arguments that matches the line
-- state. Flatten it.
local func_thunk = function(func)
return func(part)
end
return parser:flatten_argument(arg_index, func_thunk)
end
--------------------------------------------------------------------------------
local function parser_go_flags(parser, state)
local part = state.parts[state.part_index]
-- Advance parts state.
state.part_index = state.part_index + 1
if state.part_index > #state.parts then
return parser:flatten_argument()
end
for _, arg_opt in ipairs(parser.flags) do
if is_sub_parser(arg_opt) then
if arg_opt.key == part then
local arg_index_cache = state.arg_index
local skip_args_cache = state.skip_args
state.arg_index = 1
state.skip_args = false
state.depth = state.depth + 1
local ret = parser_go_impl(arg_opt.parser, state)
if type(ret) == "table" then
return ret
end
state.depth = state.depth - 1
state.skip_args = skip_args_cache
state.arg_index = arg_index_cache
end
end
end
end
--------------------------------------------------------------------------------
function parser_go_impl(parser, state)
local has_flags = #parser.flags > 0
while state.part_index <= #state.parts do
local part = state.parts[state.part_index]
local dispatch_func
if has_flags and parser:is_flag(part) then
dispatch_func = parser_go_flags
elseif not state.skip_args then
dispatch_func = parser_go_args
end
if dispatch_func ~= nil then
local ret = dispatch_func(parser, state)
if ret ~= nil then
return ret
end
else
state.part_index = state.part_index + 1
end
end
return parser.use_file_matching
end
--------------------------------------------------------------------------------
local function parser_go(parser, parts)
-- Validate 'parts'.
if type(parts) ~= "table" then
error("'Parts' param must be a table of strings ("..type(parts)..").", 2)
else
if #parts == 0 then
part = { "" }
end
for i, j in ipairs(parts) do
local t = type(parts[i])
if t ~= "string" then
error("'Parts' table can only contain strings; "..j.."="..t, 2)
end
end
end
local state = {
arg_index = 1,
part_index = 1,
parts = parts,
skip_args = false,
depth = 1,
}
return parser_go_impl(parser, state)
end
--------------------------------------------------------------------------------
local function parser_dump(parser, depth)
if depth == nil then
depth = 0
end
function prt(depth, index, text)
local indent = string.sub(" ", 1, depth)
text = tostring(text)
print(indent..depth.."."..index.." - "..text)
end
-- Print arguments
local i = 0
for _, arg_opts in ipairs(parser.arguments) do
for _, arg_opt in ipairs(arg_opts) do
if is_sub_parser(arg_opt) then
prt(depth, i, arg_opt.key)
arg_opt.parser:dump(depth + 1)
else
prt(depth, i, arg_opt)
end
end
i = i + 1
end
-- Print flags
for _, flag in ipairs(parser.flags) do
prt(depth, "F", flag)
end
end
--------------------------------------------------------------------------------
function parser_be_precise(parser)
parser.precise = true
return parser
end
--------------------------------------------------------------------------------
function is_parser(p)
return type(p) == "table" and getmetatable(p) == parser_meta_table
end
--------------------------------------------------------------------------------
function is_sub_parser(sp)
return type(sp) == "table" and getmetatable(sp) == sub_parser_meta_table
end
--------------------------------------------------------------------------------
local function get_sub_parser(argument, str)
for _, arg in ipairs(argument) do
if is_sub_parser(arg) then
if arg.key == str then
return arg.parser
end
end
end
end
--------------------------------------------------------------------------------
function new_sub_parser(key, parser)
local sub_parser = {}
sub_parser.key = key
sub_parser.parser = parser
setmetatable(sub_parser, sub_parser_meta_table)
return sub_parser
end
--------------------------------------------------------------------------------
local function parser_disable_file_matching(parser)
parser.use_file_matching = false
return parser
end
--------------------------------------------------------------------------------
local function parser_loop(parser, loop_point)
if loop_point == nil or type(loop_point) ~= "number" or loop_point < 1 then
loop_point = 1
end
parser.loop_point = loop_point
return parser
end
--------------------------------------------------------------------------------
local function parser_initialise(parser, ...)
for _, word in ipairs({...}) do
local t = type(word)
if t == "string" then
parser:add_flags(word)
elseif t == "table" then
if is_sub_parser(word) and parser_is_flag(nil, word.key) then
parser:add_flags(word)
else
parser:add_arguments(word)
end
else
error("Additional arguments to new_parser() must be tables or strings", 2)
end
end
end
--------------------------------------------------------------------------------
function clink.arg.new_parser(...)
local parser = {}
-- Methods
parser.set_flags = parser_set_flags
parser.add_flags = parser_add_flags
parser.set_arguments = parser_set_arguments
parser.add_arguments = parser_add_arguments
parser.dump = parser_dump
parser.go = parser_go
parser.flatten_argument = parser_flatten_argument
parser.be_precise = parser_be_precise
parser.disable_file_matching = parser_disable_file_matching
parser.loop = parser_loop
parser.is_flag = parser_is_flag
-- Members.
parser.flags = {}
parser.arguments = {}
parser.precise = false
parser.use_file_matching = true
parser.loop_point = 0
setmetatable(parser, parser_meta_table)
-- If any arguments are provided treat them as parser's arguments or flags
if ... then
success, msg = pcall(parser_initialise, parser, ...)
if not success then
error(msg, 2)
end
end
return parser
end
--------------------------------------------------------------------------------
function merge_parsers(lhs, rhs)
-- Merging parsers is not a trivial matter and this implementation is far
-- from correct. It is however sufficient for the majority of cases.
-- Merge flags.
for _, rflag in ipairs(rhs.flags) do
table.insert(lhs.flags, rflag)
end
-- Remove (and save value of) the first argument in RHS.
local rhs_arg_1 = table.remove(rhs.arguments, 1)
if rhs_arg_1 == nil then
return
end
-- Get reference to the LHS's first argument table (creating it if needed).
local lhs_arg_1 = lhs.arguments[1]
if lhs_arg_1 == nil then
lhs_arg_1 = {}
table.insert(lhs.arguments, lhs_arg_1)
end
-- Link RHS to LHS through sub-parsers.
for _, rarg in ipairs(rhs_arg_1) do
local child
-- Split sub parser
if is_sub_parser(rarg) then
child = rarg.parser
rarg = rarg.key
else
child = rhs
end
-- If LHS's first argument has rarg in it which links to a sub-parser
-- then we need to recursively merge them.
local lhs_sub_parser = get_sub_parser(lhs_arg_1, rarg)
if lhs_sub_parser then
merge_parsers(lhs_sub_parser, child)
else
local to_add = rarg
if type(rarg) ~= "function" then
to_add = rarg .. child
end
table.insert(lhs_arg_1, to_add)
end
end
end
--------------------------------------------------------------------------------
function clink.arg.register_parser(cmd, parser)
if not is_parser(parser) then
local p = clink.arg.new_parser()
p:set_arguments({ parser })
parser = p
end
cmd = cmd:lower()
local prev = parsers[cmd]
if prev ~= nil then
merge_parsers(prev, parser)
else
parsers[cmd] = parser
end
end
--------------------------------------------------------------------------------
local function argument_match_generator(text, first, last)
local leading = rl_state.line_buffer:sub(1, first - 1):lower()
-- Extract the command.
local cmd_l, cmd_r
if leading:find("^%s*\"") then
-- Command appears to be surround by quotes.
cmd_l, cmd_r = leading:find("%b\"\"")
if cmd_l and cmd_r then
cmd_l = cmd_l + 1