-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk.luaedit
5307 lines (4657 loc) · 220 KB
/
k.luaedit
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
#!lua
--
-- Copyright 2015-2019 by Kevin L. Goodwin [[email protected]]; All rights reserved
--
-- This file is part of K.
--
-- K is free software: you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation, either version 3 of the License, or (at your option) any later
-- version.
--
-- K is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
-- details.
--
-- You should have received a copy of the GNU General Public License along
-- with K. If not, see <http:#www.gnu.org/licenses/>.
--
--[[
lua_intf.cpp
http://www.lua.org/pil/
http://lua-users.org/wiki/StringRecipes
http://lua-users.org/lists/lua-l/
file://c:/klg/k/lua-5.1/doc/contents.html
TODO LIST
EdFxns to write in Lua
----------------------
something that evaluates Lua expression (for simple math if nothing else!)
EdFxns to rewrite in Lua
------------------------
dif -- Do this one!!!
vrepeat
ascii2hex
lblankdel
magic
makebox
Other
-----
todo: split edfxn's between C and lua based on ArgType.
EX: emacsnewl
NOARG: old C function
TEXTARG: execute
requirement: if Lua code isn't loaded, C version should work on its own as it always did.
]]
----------------------------------------------------------------------------------------------------
-- NB: for 'strict' to work, { LUA_DBLIBNAME, luaopen_debug }, in lua_intf.cpp
-- must be compiled (costs 4KB in kx.dll)
require "strict"
require "show"
----------------------------------------------------------------------------------------------------
require "lpeg" -- http://lua-users.org/wiki/LpegTutorial
lpeg.locale(lpeg) -- adds locale entries into 'lpeg' table
local lpeg = lpeg
local lpeg_split,lp_C_compound_sep,lp_C_sh_cmd_sep
do
local lp_decint = lpeg.digit^1
assert( lp_decint:match( "20077" )==6 )
local lp_ident_1 = lpeg.alpha + lpeg.S "_" -- _1: first char
local lp_ident_s = lp_ident_1 + lpeg.digit -- _s: suffix chars
local lp_ident = lp_ident_1^1 * lp_ident_s^0
assert( lp_ident:match( "6" )==nil )
assert( lp_ident:match( "6a_bc6" )==nil )
assert( lp_ident:match( "_a_bc6" )==7 )
lp_C_compound_sep = lpeg.P "." + lpeg.P "->" + lpeg.P "::"
local lp_hexint = lpeg.xdigit^1
assert( lp_hexint:match( "2eE77" )==6 )
lpeg_split = function( st, sep ) -- sep: [lpeg] pattern or string to be converted to pattern (taken from 'split' in the lpeg manual)
sep = lpeg.P(sep) -- NB: lpeg.P(pat) == pat
local elem = lpeg.C((1 - sep)^0) -- elem: "a repetition of zero of more arbitrary characters as long as there is not a match against the separator. It also captures its match."
local p = lpeg.Ct(elem * (sep * elem)^0) -- make a table capture of "matches a list of elements separated by sep."
return lpeg.match(p, st)
end
-- for use with lpeg_split
local cmdlinesep_raw = lpeg.P ";" + lpeg.P "&"^2 + lpeg.P "|"^2
lp_C_sh_cmd_sep = lpeg.space^0 * cmdlinesep_raw * lpeg.space^0
end
----------------------------------------------------------------------------------------------------
local user -- forward
fmt = string.format
local function LuaPat_escape( s ) return s:gsub( "[%$%^%(%)%%%.%[%]%*%+%-%?]", "%%%0" ) end -- line noise!
local prog_leaf_dnm = "k_edit"
local dirsep_os = _dir.dirsep_os()
local dirsep_preferred = _dir.dirsep_preferred()
local dirsep_class = _dir.dirsep_class()
local function new_non_dirsep_class( st ) return dirsep_class:gsub("%[","[^"..st ) end
local not_dirsep_class = new_non_dirsep_class("")
local pat_dup_dirsep_pat = dirsep_class..'+'..dirsep_class
local function dedup_dirsep( st ) return st:gsub( pat_dup_dirsep_pat, dirsep_os ) end
local pathnm_wrap_class = "['\"]"
local function unwrapPathNm( nm )
local d0 = nm:match( "^("..pathnm_wrap_class..")" )
if d0 then
local rv = nm:match( "^"..d0.."([^"..d0.."]+)"..d0 )
if rv then -- DBG( fmt("uwp+: %s '%s'",rv, d0) )
return rv, d0
end
end -- DBG( fmt("uwp-: %s '%s'",nm, '') )
return nm,''
end
local norm_path_case
if dirsep_os=='/' then -- kludgy but sufficient
norm_path_case = function( st ) return st end
else
norm_path_case = function( st ) return st:lower() end
end
local function leadingDirPattern( path ) return "^"..
LuaPat_escape(
norm_path_case( StrExpandEnvVars( path ) .. dirsep_os):gsub( dirsep_class .. "+", dirsep_os )
)
end
Min = math.min
Max = math.max
local logf = FBUF.log()
function string:ary_matchseqs( classmembs )
local classmembs, rv = classmembs or "^\t ", {}
local pattern = "([" .. classmembs .. "]+)"
self:gsub( pattern, function(st) rv[1+#rv] = st end )
return rv
end
--[[ 20070807 kgoodwin BUGBUG
a strangely complex topic: doing a "printf" to a FBUF: the concern is that
since FBUF's are LINE, not STREAM, oriented, the default behavior is just to
print printf output on a new (last) line. But in many cases we want a printf
to logically start on the actual last line, perhaps to append to existing
content added by a previous printf. With the current logic, this is
impossible...
--]]
function FBUF:PutLastLines( arr )
if type(arr) == "string" then arr = split_ch_tbl( arr, "\n" ) end
for _,line in ipairs( arr ) do
self:PutLastLine( line )
end
end
function GetCurrentFBUF() return FBUF.new() end
function GetCurrentFilename() return FBUF.new():Name() end
local print = function ( s ) logf:PutLastLine( tostring(s) ) end -- log facility (override of print function)
local printf = function (...) print( fmt(...) ) end
print( "Lua calling! Current file is " .. GetCurrentFilename() .."\n" )
function Msgf(...) Msg( fmt(...) ) end
require "util"
require "tu"
require "menu"
-- NB! "ONLY nil and false are considered "false"! THE NUMBER 0 AND THE EMPTY STRING are _TRUE_
-- ifx = "IF-eXpression": like C's ?: operator
--
-- 'a and b or c' is equivalent to the C expression 'a ? b : c'
--
-- *** BUT, if b is false/nil, then c is chosen/executed, even if a is true ***
-- so the following is NOT a good impl
--
-- function ifx( expr, trueval, falseval ) return expr and trueval or falseval end
--
function ifx( expr, trueval, falseval ) if expr then return trueval end return falseval end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.ends(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
int = math.floor -- it's UN-BE-LEEEEEEEEEV-ABLE that this is not builtin!
function logBaseN(x,N) return math.log(x)/math.log(N) end
log10 = math.log10
function widthBaseN(x,N) return 1 + int( logBaseN( x, N ) ) end
function widthDecimal(x) return widthBaseN(x,10) end
function str_setlen( str, len, pad ) -- because string.format does not allow width/precision fields > 99
if #str > len then return str:sub(1,len) end
pad = pad or " "
local pl = len - #str
return str .. (pad:rep(pl)):sub(1,pl)
end
----------------------------------------------------------------------------------------------------
function arg2box( arg ) return arg.fbuf, arg.view, arg.minY, arg.maxY, arg.minX or 1, arg.maxX or MAXCOL end
do
local function HasEdFxnSignature( tbl )
return type(tbl) == "table"
and type(tbl.name) == "string"
and type(tbl.attr) == "number"
end
local s_EdFxTblsToRegister = {}
local s_AssignsToRegister = {}
local s_EdFxns = {}
local s_MenuEdFxns = {}
--[[ following 2 functions AddEdFxn and Assign are "vectored" to defer their
effect (registration of Lua EdFxn and key assignments with C++ core) until
RegisterAllLuaEdFxns is called by the C++ core only AFTER we've successfully
compiled & run this module (AND un-registered any assignments made by the
prior LuaCtxt instance of this same code). RegisterAllLuaEdFxns then
reassign AddEdFxn and Assign to functions that take immediate action ]]
function AddEdFxn( tbl ) -- re-aimed at RegisterLuaEdFxn
s_EdFxTblsToRegister[1+#s_EdFxTblsToRegister] = tbl
end
function Assign( tbl ) -- re-aimed at DoAssign
s_AssignsToRegister[1+#s_AssignsToRegister] = tbl
end
-----------------------------------------------------------------------------------------------
-- RegisterAllLuaEdFxns is called by (C++) L_edit_post_load
local function RegisterLuaEdFxn( tbl ) -- CALLED indirectly FROM C++!!! Be CAREFUL!!!
if not HasEdFxnSignature( tbl ) then return Msg( "AddEdFxn: malformed tbl param!!!" ) end
local name, help = tbl.name, tbl.help or ""
local mhs, isMf = help:gsub( '^Menu[:]? ', '' )
if isMf > 0 then
mhs = mhs:gsub( '^of ', '' )
s_MenuEdFxns[1+#s_MenuEdFxns] = { mhs, name }
end
printf( "AddEdFxn adding ArgType=%03X: '%s', '%s'", tbl.attr, name, help )
if s_EdFxns[ name ] then printf( "overriding EdFxn %s", name ) end
CmdIdxAddLuaFunc( name, tbl.attr, help ) -- <-- register name w/C++ core
s_EdFxns[ name ] = tbl
if tbl.key then SetKeyOk( name, tbl.key ) end
end
local function DoAssign( tbl )
for _,val in ipairs( tbl ) do
if not AssignStrOk( val ) then
return Msgf( "assign: '%s' failed", val )
end
end
return true
end
function RegisterAllLuaEdFxns() -- CALLED DIRECTLY FROM C++!!! Be CAREFUL!!!
if s_EdFxTblsToRegister ~= nil then
for _,tbl in ipairs(s_EdFxTblsToRegister) do
RegisterLuaEdFxn( tbl )
end
for _,tbl in ipairs( s_AssignsToRegister ) do
DoAssign( tbl )
end
s_EdFxTblsToRegister = nil
s_AssignsToRegister = nil
AddEdFxn = RegisterLuaEdFxn -- re-aim public API to immediate mode
Assign = DoAssign -- re-aim public API to immediate mode
end
end
-----------------------------------------------------------------------------------------------
AddEdFxn{ name = "mm", help = "menu of menu commands", attr = NOARG
, NOARG = function( arg )
local _,fxnm = Menu.new( { title="Menu commands", choices=s_MenuEdFxns } ):PickOne()
if fxnm then return fExecute( fxnm ) end
return false
end
}
function AddEdStringFxn( name, fxn, key, help ) -- common idiom
AddEdFxn{ name = name, attr = BOXSTR+TEXTARG, TEXTARG = function( arg ) return fxn( arg.text ) end, help=help or name, key=key }
end
AddEdFxn{ name = "mol", help = "Menu of Lua-based commands", key="alt+m", attr = NOARG
, NOARG = function( arg )
local cmdnms,len = {}, 0
printf( "mol arg.fMeta = %s", tostring(arg.fMeta) )
for nm,efx in pairs(s_EdFxns) do
if (not arg.fMeta or (efx.help and efx.help:match "^[Mm]enu")) and _bin.bitand( efx.attr, NOARG ) ~= 0 then
len = (len > #efx.name) and len or #efx.name
cmdnms[1+#cmdnms] = efx.name
end
end
if #cmdnms == 0 then return Msg( "No NOARG CMDs?" ) end
local fmts = "%-" .. len .. "s = %s"
table.sort( cmdnms )
local choices = {}
for _,nm in ipairs( cmdnms ) do
local efx = s_EdFxns[nm]
choices[1+#choices] = { fmt( fmts, efx.name, (efx.help and #efx.help>0) and efx.help or efx.name ), efx.name }
end
local _,fxnm = Menu.new( { title="Lua-based commands", choices=choices } ):PickOne()
if fxnm then return fExecute( fxnm ) end
return false
end
}
function GetEdFxn_FROM_C( nm ) -- <<<********* this is a CRITICAL function called from C++ !!! DO NOT RENAME!!! CHANGE WITH CAUTION!
local rv = s_EdFxns[ nm ]
print( "GetEdFxn_FROM_C=("..nm..")".." -> "..tostring(rv) )
return rv
end
-- these were wr with the idea of pulling the CmdIdx for Lua EdFxns into Lua
-- (s_EdFxns), so Lua EdFxns would be completely managed from Lua, avoiding
-- language/domain-boundary issues; problem is, I think the overall system of
-- CMDs and PCMDs will be severely broken if Lua EdFxns aren't bound to
-- CMDs...
--
-- function EdFxnAttrs( name ) return ifx( s_EdFxns[ name ], s_EdFxns[ name ].attr, 0 ) end
-- function ExecEdFxn( name, arg ) end
end
function SwitchToFile( fname ) FBUF.new( fname ):PutFocusOn() end
local function AllFbufs() -- factory per PiL 7.1
local iter = 0
return function()
if iter == 0 then iter = FBUF:first()
elseif iter then iter = iter:Next()
end
return iter
end
end
local function AllWins() -- factory per PiL 7.1
local state = 0
return function()
if state == nil then return end
state = state + 1
local rv = Win.getn(state)
if rv == nil then state = nil end
return state,rv
end
end
local function ViewsFbufsByHistOrder() -- factory per PiL 7.1
local fb,vw = nil,0
return function()
if vw == 0 then fb,vw = FBUF.CurView()
elseif vw then vw = vw:Next()
fb = vw and vw:FBuf()
end
return vw,fb
end
end
function PathOf ( str ) return str:match( "^(.-)"..not_dirsep_class.."*$" ) end
function Path_Name( str ) return str:match( "^(.-)("..not_dirsep_class.."*)$" ) end
function NameExtOf( str ) return str:match( dirsep_class.."("..not_dirsep_class.."*)$" ) end
function NameOf ( str ) return NameExtOf(str):gsub( "%.[^%.]*$","") end
function ExtOf ( str ) return str:match( "%.([^%.]*)$" ) end
-- WARNING: unlike PathOf, PrettyPath does not generate an ever-shrinking string
-- (because of the annoying "c:\" anomaly), so you shouldn't use it in a loop
-- where the loop terminating condition relates to the returned path string
-- shrinking to nothing! PrettyPath is only intended for use when
-- 1) generating bare directory strings for the user to look at (EX: EdFxn "dirs"), or
-- 2) generating directory strings which will become EnvVar values
function PrettyPath( path )
if path:match( "^%a:\\$" )
or path:match( "^"..dirsep_class.."$" ) then return path end
return path:gsub( dirsep_class.."$", "" )
end
do
local cwd = GetCwd()
print( "GetCwd='" .. cwd .. " PathOf='" .. PathOf( cwd ) .. "' '".. PrettyPath( PathOf( cwd ) ).."'" )
end
-- Makes a deep copy of a table. This version of DeepCopy
-- properly handles duplicate subtables, including cycles.
-- (The Seen argument is only for recursive calls.)
local function DeepCopy(Src, Seen)
local Dest
if Seen then -- This will only set Dest if Src has been seen before:
Dest = Seen[Src]
else -- Top-level call; create the Seen table:
Seen = {}
end
-- If Src is new, copy it into Dest:
if not Dest then -- Make a fresh table and record it as seen:
Dest = {}
Seen[Src] = Dest
for Key, Val in pairs(Src) do
Key = type(Key) == "table" and DeepCopy(Key, Seen) or Key
Val = type(Val) == "table" and DeepCopy(Val, Seen) or Val
Dest[Key] = Val
end
end
return Dest
end
-- array/table-related functions
function array_max_strlen( ary )
local maxlen = 0
for _,val in ipairs( ary ) do maxlen = Max( maxlen, #val ) end
return maxlen
end
-- string-related functions
function string.a_gmatches( str, pat )
local rv = {}
for token in string.gmatch( str, pat ) do rv[ #rv+1 ] = token end
return rv
end
function pat_nocase( s ) return s:gsub( "%a", function (ch) return "["..ch:upper() ..ch:lower() .."]" end ) end -- escape a string such that alpha chars match either case
function FactorOutCommonLeadingPath( fnm_ary )
local function rtn_none() return "", fnm_ary, array_max_strlen(fnm_ary) end
if #fnm_ary < 2 then return rtn_none() end
local pfxlen = 1e6
local s1 = fnm_ary[1]
for ix=2,#fnm_ary do
pfxlen = Min( pfxlen, Path_CommonPrefixLen( s1, fnm_ary[ix] ) )
end
if 0==pfxlen then return rtn_none() end
s1 = s1:sub(1,pfxlen) -- print( "pfxlen="..tostring(pfxlen).." s1="..s1 )
s1 = s1:gsub( not_dirsep_class.."*$","") -- print( "s1-partial="..s1 )
local rv = {}
local nmWMax = 0
for ix, val in ipairs( fnm_ary ) do
local ay = val:sub( #s1+1 )
rv[1+#rv] = ay
nmWMax = Max( nmWMax, #ay )
end
return s1, rv, nmWMax
end
----------------------------------------------------------------------------------------------------
local curf_prop_rdr, SetCurFName
do
local curf_fmap_ = {
-- keys MUST be lowercase!
-- curfile
curfileext = ExtOf ,
curfilename = Path_Name ,
curfilepath = PathOf ,
psscriptroot= PathOf , -- for Windows' $PSScriptRoot
}
local curfnm, curfnm_norm = "", ""
curf_prop_rdr = function( nm )
if type(nm) == "string" then
nm = nm:lower()
return curf_fmap_[nm] and curf_fmap_[nm]( curfnm )
end
end
local cf_mt = { __index = curf_prop_rdr }
SetCurFName = function ( new_curfnm ) -- <<<********* this is a CRITICAL function called from C++ !!! DO NOT RENAME!!! CHANGE WITH CAUTION!
local new_curfnm_norm = norm_path_case( new_curfnm )
if curfnm_norm ~= new_curfnm_norm then -- print( "SetCurFName ".. new_curfnm )
curfnm, curfnm_norm = new_curfnm, new_curfnm_norm
end
end
end
do
local function envReplacer( espec ) -- <<<********* this is a CRITICAL function called from C++ !!! DO NOT RENAME!!! CHANGE WITH CAUTION!
local rv = curf_prop_rdr( espec ) or GetenvOrNil( espec )
print( " envReplacer: '"..espec.."' -> '" .. (rv or "(nil)") .. "'" )
return rv
end
-- envNamePat, which is ONLY used with indefinite (open-ended) syntaxes
-- ($varname and %varname), excludes '|' and ';' since "filename grammar"
-- patterns include [^=|;] since "filename grammar" is overloaded to allow
-- "Literal lists of path components separated by VBARs ('|')"
--
-- note that technically, https://stackoverflow.com/a/2821183 says a
-- (Env)variable name may contain ANY character except '=' or NUL, however we
-- are being more restrictive (excluding dirsep and pathsep ([:;]) and VBAR)
-- since actual variables a user might referencec essentially NEVER have these
-- chars in their names.
local envNamePat = "("..new_non_dirsep_class("=|:;").."+)" -- print( "envNamePat=".. envNamePat )
local function envExpanderGen( pat )
return function( st ) return st:gsub( pat, envReplacer ) end
end
local function sh_expander(st, nest) -- expand ${VARNM}, ${VARNM:-dfltval} and ${VARNM-dfltval}
nest = nest or " " -- ${VARNM:+altval} and ${VARNM+altval}
return st:gsub( "%$%b{}", function( varx )
-- DBG( fmt( "%s+%s'", nest, varx ) )
local body = varx:sub(3,#varx-1) -- DBG( fmt( "%sbody=%s'", nest, body or "nil" ) )
-- 2 near-identical matches follow because pattern varies in TWO
-- places: envnm and nullEqUnset
local envnm,nullEqUnset,op,dflt = body:match("([^$:-+]+)(:)([-+])(.*)") -- DBG( fmt( "%s1: op=%s e=%s d=%s'", nest, op or "nil", envnm or "nil", dflt or "nil" ) )
if not dflt then
envnm,op,dflt = body:match("([^$-+]+)([-+])(.*)") -- DBG( fmt( "%s2: op=%s e=%s d=%s'", nest, op or "nil", envnm or "nil", dflt or "nil" ) )
if not dflt then
envnm = body
end
end
local rv = envReplacer( envnm )
if op then
--[[ truthiness of empty/null rv (${envnm}) value depends on whether ':' prefix (nullEqUnset) was provided:
"...use of the <colon> in the format shall result in a test for a
parameter that is unset or null; omission of the <colon> shall
result in a test for a parameter that is only unset."
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html "2.6.2 Parameter Expansion" ]]
if rv --[[is set]] and #rv==0 --[[isNull]] and nullEqUnset then rv = nil end -- demote empty/null rv to nil iff ':' provided
if op=="+" then
rv = rv and (dflt and sh_expander(dflt,nest.." ")) or ""
elseif op=="-" then
rv = (rv and sh_expander(rv,nest.." ")) or (dflt and sh_expander(dflt,nest.." ")) or ""
else
assert( nil, "unknown op="..op )
end
end
rv = rv or ""
-- kludge to implement ${strftime-%Y.%m.%dT%H:%M:%S}
-- local strftime = envnm=="strftime" and dflt and assert( os.date( dflt ) )
-- DBG( fmt( "%s-%s -> %s'", nest, varx, rv ) )
return rv
end
)
end
local envExpanders = { -- note that '%', not '\', is the Lua-pattern metachar escaper!
-- prefix/format substitutions:
function(str) return str:gsub( "^~/", "${HOME:-${USERPROFILE}}"..dirsep_os ) end,
function(str) -- on MS OS, xlat "/p/dir/to/something" to "p:\dir\to\something"
if dirsep_os=="\\" then
local drvletter = str:match( "^/([a-zA-Z])/" )
if drvletter and not IsDir(str:sub(2)) then
str = drvletter .. ":" .. str:sub(3):gsub("/",dirsep_os)
end
end
return str
end,
-- in the cmd.exe (batch) language, %~dp0 expands to "path of current [script] file[name] (%0 e.g. argv[0])"
-- in the Powershell language, $PSScriptRoot or ${PSScriptRoot} expands to "path of current [script] file[name] (%0 e.g. argv[0])"
-- %~dp0fbuf_edit.cpp
-- $PSScriptRoot\fbuf.cpp
-- ${PSScriptRoot}ed_mem.h
-- https://stackoverflow.com/a/5034119
function(str) return str:gsub( "%%~0" , "${curfile}" ) end, -- must appear BEFORE sh_expander in envExpanders[]!
function(str) return str:gsub( "%%~dp0" , "${curfilepath}" ) end, -- must appear BEFORE sh_expander in envExpanders[]!
function(str) return str:gsub( "%%~nx0" , "%~n0%~x0" ) end, -- must appear BEFORE defs of %~n0 & %~x0
function(str) return str:gsub( "%%~n0" , "${curfilename}" ) end, -- must appear BEFORE sh_expander in envExpanders[]!
function(str) return str:gsub( "%%~x0" , "${curfileext}" ) end, -- must appear BEFORE sh_expander in envExpanders[]!
-- general substitutions:
sh_expander, -- arg "${HOME:-${USERPROFILE}}" setfile -- sh (w/ {})
envExpanderGen( "%$" ..envNamePat ), -- arg "$USERPROFILE" setfile -- sh (w/o {})
envExpanderGen( "%$%(" .."([^)]-)" .. "%)"), -- arg "$(USERPROFILE)" setfile -- make
envExpanderGen( "%%" .."([^%%]-)".. "%%"), -- arg "%USERPROFILE%" setfile -- DOS-COMMAND/Windows-CMD
envExpanderGen( "%%" ..envNamePat ), -- arg "%USERPROFILE" setfile -- DOS-COMMAND/Windows-CMD
}
function StrExpandEnvVars( str ) -- <<<********* this is a CRITICAL function called from C++ !!! DO NOT RENAME!!! CHANGE WITH CAUTION!
-- print( "StrExpandEnvVars+("..str..")" )
-- DBG( "StrExpandEnvVars/SEEV:" )
for _, fxn in ipairs(envExpanders) do
local news = fxn( str )
if str ~= news then
-- DBG( " SEEV+ ".. str )
-- DBG( " SEEV- ".. news )
end
str = news
end
-- print( "StrExpandEnvVars-("..str..")" )
return str
end
--[[ -- "unit test" for StrExpandEnvVars
AddEdFxn{ name = "envx", help = "tests Lua's StrExpandEnvVars", key="alt+k", attr = TEXTARG + BOXSTR
, TEXTARG = function ( arg )
local result = StrExpandEnvVars( arg.text )
print( result )
Msg( result )
return true
end
}
--]]
end
--################### useful generators
do
function CwdToRoot() -- generator
local dir = 0 -- iterator variable
return function() -- iterator function
if dir == 0 then dir = GetCwd()
elseif dir then
dir = Path_Dirnm( dir:sub( 1, #dir-1 ) )
if not IsDir(dir) then dir = nil end
end
-- if dir then print( dir:Name() ) end
return dir
end
end
function a_CwdToRoot() -- crude, but...
local rv = {}
for dir in CwdToRoot() do rv[1+#rv] = dir end
return rv
end
--[[
print( "++++++++++ test CwdToRoot()" )
local ix = 20 -- "deadman switch"
for dir in CwdToRoot() do
ix=ix-1
if ix < 1 then break end
print( "'"..dir.."', PP='"..PrettyPath( dir ).."'" .. ", IsDir="..tostring(IsDir(dir)) )
end
print( "---------- test CwdToRoot()" )
--
]]
end
local mtFBUF = FBUF:getmetatable()
function mtFBUF:RawLines() -- generator: fastest, tabs unconverted
return function( self, lnum )
lnum = lnum + 1
if lnum <= self:LastLine() then return lnum, self:GetLineRaw( lnum ) end
end
, self
, 0
end
function mtFBUF:Lines() -- generator: a little less fast, any tabs expanded to spaces
return function( self, lnum )
lnum = lnum + 1
if lnum <= self:LastLine() then return lnum, self:GetLine( lnum ) end
end
, self
, 0
end
function FBUF.new_empty_may_create( fnm )
local rv = assert( FBUF.new_may_create( fnm ), "couldn't open \""..fnm.."\" ???" )
rv:MakeEmpty()
return rv
end
-- this is redundant to the numeric for stmt/loop
-- function range( min, max ) -- generator (assumes int params)
-- return function()
-- if min <= max then
-- local rv = min
-- min = min + 1
-- return rv
-- end
-- end
-- end
--[[
AddEdFxn{ name = "wins", help = "wins", attr = NOARG
, NOARG = function()
print( "Window-list" )
for ix,win in AllWins() do
printf( "%d H=%d: %s", ix, win:Height(), win:CurFBUF():Name() )
end
end
}
--]]
--################### end useful iterators
AddEdFxn{ name = "dirs", help = "open <dirs> buffer", key="alt+f", attr = NOARG
, NOARG = function ( arg )
local dirs = {}
local out = FBUF.new_empty_may_create( "<dirs>" )
for fbuf in AllFbufs() do
local path = PrettyPath( PathOf( fbuf:Name() ):lower() )
if #path > 0 then
if not dirs[ path ] then dirs[ path ] = true end
end
end
for dir in tu.PairsBySortedKeys( dirs ) do out:PutLastLine( dir ) end
-- out:ScrollAllCursorsToBof()
out:PutFocusOn()
return true
end
}
----------------------------------------------------------------------------------------------------
local function EditorHelpFile()
return FBUF.new( StrExpandEnvVars( "$KINIT:khelp.txt" ) )
end
AddEdFxn{ name = "edhelp", help = "goto editor help for a keyword", --[[key="F1",]] attr = NOARG+TEXTARG+BOXSTR+NULLEOW
, NOARG = function ( arg ) return EditorHelpFile():PutFocusOn() ~= nil end -- simply switch to help file
, TEXTARG = function ( arg )
local hf = EditorHelpFile() -- print( "'"..hf:Name().."'" )
if not hf then
return Msg( "no help file found" )
end
local key = "^ÄÄ"..pat_nocase( arg.text ) .. (arg.text:match"%s" and "Ä" or " ")
for lnum, line in hf:RawLines() do -- DBG( line )
if line:match( key ) then
local hv = hf:PutFocusOn()
hv:MoveCursor( lnum, 1 )
Msgf( "found help entry for '%s'", arg.text )
return true
end
end
return Msgf( "no help entry found for '%s'", arg.text )
end
}
----------------------------------------------------------------------------------------------------
function basicSerialize (o)
if type(o) == "number" then return tostring(o)
else return string.format("%q", o) end -- assume it is a string
end
function mtFBUF:serialize (name, value, saved)
saved = saved or {} -- initial value
self:cat(name .. " = ") -- cat(" = ") doesn't work cuz of automatic trailing space deletion, patched below
if type(value) == "number" or type(value) == "string" then
self:cat( basicSerialize(value) .. "\n" )
elseif type(value) == "table" then
if saved[value] then
self:cat( saved[value] .. "\n" ) -- use its previous name
else
saved[value] = name -- save name for next time
self:cat( "{}\n" ) -- create a new table
for k,v in pairs(value) do -- save its fields
local fieldname = string.format("%s[%s]", name, basicSerialize(k))
self:serialize(fieldname, v, saved)
end
end
else
-- error("cannot serialize a " .. type(value))
self:cat( "("..type(value)..")\n" )
end
-- print( "++++++++++++ _G[] dump +++++++++++++" ) for ix, val in pairs(_G) do logf:serialize( ix, val ) end
-- print( "------------ _G[] dump -------------" )
end
do
local function serializeIt( varName )
logf:KeepTrailSpcs() -- so self:cat(name .. " = ") works as desired
print( "--\n-- serializing '"..varName.."'\n--\n" )
logf:serialize( varName, valueof( varName ) )
logf:DiscardTrailSpcs()
return true
end
AddEdFxn{ name = "lser", help = "serialize named Lua object (dflt=\"G_\") to <lua>", attr = TEXTARG + NOARG
, TEXTARG = function ( arg ) return serializeIt( arg.text ) end
, NOARG = function ( arg ) return serializeIt( "_G" ) end
}
end
--
-- Note that here in Lua-land, the first line of a file is numbered _1_, not _0_ as in C++ land!!!
--
-- Msg( str..'X='..arg.cursorX..' Y='..arg.cursorY )
local function GotoFileView( fnm )
local fb = FBUF.new( fnm )
if fb then
return fb, fb:PutFocusOn()
end
end
function GotoFileLineCol( fnm, line, column )
print( " GotoFileLineCol fnm="..fnm..",line="..(line or "nil")..",column="..(column or "nil") )
local fb,vw = GotoFileView( fnm )
if vw and line and column then
vw:MoveCursor( line, column )
end
return fb,vw
end
local GotoCtagsUri, LineToTagRec, ChoiceTxtOfATag, read_tagged_files_from_tags_file
do -- local scope for private functions and data that implement EdFxn "tgs"
-- Read Exuberant Tags output file
-- My canonical Exuberant Tags command-line is:
-- tagcr.bat:
-- ctags --totals=yes --excmd=number --c-types=cdefgmnstuv --python-kinds=-i --fields=+K --extras=+f -R
-- http://www.held.org.il/blog/2011/02/configuring-ctags-for-python-and-vim/
-- tags-cache-related state:
local s_filteredTagsCache
, s_alias_to
, s_tagsFileMtime -- mtime of s_tagsFilename when <tagged-files> was last updated
, s_tagsFilename -- tags database file (one tagdef-record per line) generated by ctags program
, s_tagsFilepath -- (should be) used to de-relative'ize tags-db content (unfortunately ctags --tag-relative=yes option has NO effect)
local function invalidate_tags()
s_filteredTagsCache = nil
s_alias_to = nil
s_tagsFileMtime = nil
s_tagsFilename = nil
s_tagsFilepath = nil
end
local function get_tags_matching( tag ) -- wrap C API FindMatchingTagsLines and manage 'tags-cache-related state' variables
local ifnm, ifh, taglines
local taglines = {}
for dir in CwdToRoot() do
ifnm = dir .. "tags"
if IsFile( ifnm ) then
Msgf( "searching %s%s", ifnm, (tag and fmt(" for tag '%s'", tag ) or "" ) )
taglines = FindMatchingTagsLines( ifnm, tag )
break
end
end
if taglines.tagsfile_mtime then
if s_tagsFilename and s_tagsFilename == ifnm
and s_tagsFileMtime and s_tagsFileMtime == taglines.tagsfile_mtime
then -- no cached-info resetting necessary
else -- cached-info resetting necessary
s_filteredTagsCache = {}
s_alias_to = {}
s_tagsFilename = ifnm
s_tagsFileMtime = taglines.tagsfile_mtime
s_tagsFilepath = PathOf( s_tagsFilename )
end
end
return taglines
end
local function norm_fnm_of_tag( tfnm )
-- DBG( "tfnm "..tfnm )
local absfnm = tfnm:gsub( "\\\\", "\\" )
if tfnm:match( "^%a:"..dirsep_class )
or tfnm:match( "^"..dirsep_class ) then
-- tfnm is already abs
else
-- hack to tentatively support independent callability of LineToTagRec (which calls us)
local basepath = s_tagsFilepath
if not basepath then
get_tags_matching( 'Solzhenitsyn' ) -- force initialization
-- get_tags_matching may fail or new s_tagsFilepath value may mismatch that of tags file context from which 'line' param of LineToTagRec was taken)
basepath = s_tagsFilepath or "<no tags file in CwdToRoot>"
end
absfnm = basepath..absfnm
end
-- DBG( "absfnm "..absfnm )
return absfnm
end
local function Msg_print( msg ) Msg( msg ) print( msg ) end
read_tagged_files_from_tags_file = function( tfbuf )
-- following is ONLY to provide default mffile (mfgrep, mfreplace) buffer (oh, and to provide tfbuf:LineCount() for Msg below)
local tagged_files = get_tags_matching( '\tkind:file' )
table.sort( tagged_files )
for _,tfnm in ipairs( tagged_files ) do
local absfnm = norm_fnm_of_tag( tfnm )
if _dir.name_isfile( absfnm ) then
tfbuf:PutLastLine( absfnm )
end
end
collectgarbage( "collect" )
if not tfbuf or tfbuf:LineCount() == 0 then
Msg_print( "no tags file found in "..GetCwd().."; ctags cmdline missing --extras=+f ?" )
return false
end
AssignStrOk( 'mffile:='..(tfbuf:LineCount() > 0 and ('"'..tfbuf:Name()..'"') or "") )
Msg_print( fmt( "%d files named in %s per %s", tfbuf:LineCount(), tfbuf:Name(), s_tagsFilename ) )
return true
end
local ignored_atag = {
lang = {
-- Man = true,
-- HTML = true,
-- Markdown = true,
},
--[[
kind = {
anchor = true, -- hacky way to ignore html tags swept in by use of raw -R ctags scanning (--exclude=_wildcard_ unavail on Win32)
heading1 = true, -- hacky way to ignore html tags swept in by use of raw -R ctags scanning (--exclude=_wildcard_ unavail on Win32)
heading2 = true, -- hacky way to ignore html tags swept in by use of raw -R ctags scanning (--exclude=_wildcard_ unavail on Win32)
heading3 = true, -- hacky way to ignore html tags swept in by use of raw -R ctags scanning (--exclude=_wildcard_ unavail on Win32)
selector = true, -- hacky way to ignore html tags swept in by use of raw -R ctags scanning (--exclude=_wildcard_ unavail on Win32)
},
--]]
}
local tag_field_nm_map = {
variable = "var",
language = "lang",
enumerator = "enum",
}
local function split_extension_field( dest, fieldVal ) -- DBG( "split_extension_field+ "..fieldVal )
local nm, val = fieldVal:match( "^([%w_]+):(.*)$" ) -- DBG( "split_extension_field- nm="..(nm or "nil").." vl="..(val or "nil") )
if val then
nm = tag_field_nm_map[nm] or nm
val = val:gsub( "::__anon%x+", "" )
dest[1+#dest] = nm
dest[nm] = val
else
tu.t_append( dest, "anon", fieldVal )
end
end
LineToTagRec = function( line )
-- dice a (possible) tags file record (line) into fields
local atag = {}
local fields = split_ch_tbl( line, "\t" )
if #fields < 4 then return nil end
local shift = function() return table.remove( fields, 1 ) end
-- first 3 fields are FIXED (always present) positional: 'tag name', 'input file', 'pattern' (see --list-fields output)
local tag = shift() -- tag name
local fnm = norm_fnm_of_tag( shift() ) -- input file
local pat = shift() -- pattern ; when --excmd=number, pattern has the value 'n;"' where n is a decimal (line) number
local lnum = pat:match( '(%d+);"' ) -- PATTERN; when --excmd=number, this has the value 'n;"' where n is a decimal (line) number
-- lnum/line# info can also be obtained from Extension field 'line:' (--field=+n);
-- kind field: is an optional universal-ctags field which it can manifest into tag record in two different ways:
-- 1: as a 4th positional field (if (--field=+K OR --field=+k) AND NOT --field=+z)
-- 2: in place of a 4th positional field, as the first Extension field 'kind:' (if --field=+K+z OR --field=+k+z)
-- our code supports option 2 which is cleaner (the more self-identifying fields used, the better)
atag = { tag=tag, fnm=fnm, lnum=lnum }
-- remaining fields are "Extension fields": "key:value"
for _,field in ipairs(fields) do -- DBG( field )
split_extension_field( atag, field )
end
if atag.kind=='file' then
atag.lnum = nil
end
return atag
end
local function filterTags( taglines )
if not taglines or #taglines==0 then return end
local cands = {}
print( "filterTags: input=["..#taglines.."]" )
for ix,line in ipairs(taglines) do -- DBG( line )
local atag = LineToTagRec( line )
local function ignored( tagat )
return atag[tagat] and ignored_atag[tagat] and ignored_atag[tagat][atag[tagat]]
end
if not (ignored 'lang' or ignored 'kind') then -- TODO: move this filtering to the INPUT side (by adjusting ctags params/options)
cands[1+#cands] = atag
end
end
print( "filterTags: numtags=["..#cands.."]" )
return cands
end
local function DefinedTag( tag )
local rv = (s_filteredTagsCache and s_filteredTagsCache[tag]) or filterTags( get_tags_matching( tag ) ) or true
-- rv is either true (if NO matching tag(s) or tags file) or a table (array) containing matching tags
if rv==true then
return -- NO matching tag(s) or tags file