/
utils.lua
1253 lines (1125 loc) · 39.1 KB
/
utils.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- coding: utf-8
local Shared = ...
local Msg, ErrMsg, pack, ExpandEnv = Shared.Msg, Shared.ErrMsg, Shared.pack, Shared.ExpandEnv
local F = far.Flags
local type = type
local string_find, string_sub = string.find, string.sub
local band, bor = bit64.band, bit64.bor
local MacroCallFar = Shared.MacroCallFar
local gmeta = { __index=_G }
local LastMessage = {}
local LoadCounter = 0
--------------------------------------------------------------------------------
local TrueAreaNames = {
[F.MACROAREA_OTHER] = "Other",
[F.MACROAREA_SHELL] = "Shell",
[F.MACROAREA_VIEWER] = "Viewer",
[F.MACROAREA_EDITOR] = "Editor",
[F.MACROAREA_DIALOG] = "Dialog",
[F.MACROAREA_SEARCH] = "Search",
[F.MACROAREA_DISKS] = "Disks",
[F.MACROAREA_MAINMENU] = "MainMenu",
[F.MACROAREA_MENU] = "Menu",
[F.MACROAREA_HELP] = "Help",
[F.MACROAREA_INFOPANEL] = "Info",
[F.MACROAREA_QVIEWPANEL] = "QView",
[F.MACROAREA_TREEPANEL] = "Tree",
[F.MACROAREA_FINDFOLDER] = "FindFolder",
[F.MACROAREA_USERMENU] = "UserMenu",
[F.MACROAREA_SHELLAUTOCOMPLETION] = "ShellAutoCompletion",
[F.MACROAREA_DIALOGAUTOCOMPLETION] = "DialogAutoCompletion",
[F.MACROAREA_GRABBER] = "Grabber",
[F.MACROAREA_DESKTOP] = "Desktop",
[F.MACROAREA_COMMON] = "Common",
}
local AllAreaNames = {}
for k,v in pairs(TrueAreaNames) do
local str = v:lower()
AllAreaNames[k] = str
AllAreaNames[str] = k
end
local SomeAreaNames = {
"other", "viewer", "editor", "dialog", "menu", "help", "dialogautocompletion",
"grabber", "desktop", "common" -- "common" должен идти последним
}
local function GetTrueAreaName(Mode) return TrueAreaNames[Mode] end
local function GetAreaName(Mode) return AllAreaNames[Mode] end
local function GetAreaCode(Area) return AllAreaNames[Area:lower()] end
--------------------------------------------------------------------------------
local MCODE_F_CHECKALL = 0x80C64
local MCODE_F_GETOPTIONS = 0x80C65
local MCODE_F_MACROSETTINGS = 0x80C6A
Shared.OnlyEditorViewerUsed = band(MacroCallFar(MCODE_F_GETOPTIONS),0x3) ~= 0
local Areas
local LoadedMacros
local LoadMacrosDone
local LoadingInProgress
local EnumState = {}
local Events
local EventGroups = {"dialogevent","editorevent","editorinput","exitfar","viewerevent", "consoleinput"}
local AddedMenuItems
local AddedPrefixes
local IdSet
local LoadedPanelModules
local ContentColumns
package.nounload = {lpeg=true}
local initial_modules = {}
local function FixInitialModules()
for k in pairs(package.loaded) do initial_modules[k]=true end
end
local function CheckFileName (mask, name)
return far.ProcessName("PN_CMPNAMELIST", mask, name, "PN_SKIPPATH")
end
local StringToFlags, FlagsToString do
local MacroFlagsByInt = {
[0x00000001] = "EnableOutput",
[0x00000002] = "NoSendKeysToPlugins",
[0x00000008] = "RunAfterFARStart",
[0x00000010] = "EmptyCommandLine",
[0x00000020] = "NotEmptyCommandLine",
[0x00000040] = "EVSelection",
[0x00000080] = "NoEVSelection",
[0x00000100] = "Selection",
[0x00000200] = "PSelection",
[0x00000400] = "NoSelection",
[0x00000800] = "NoPSelection",
[0x00001000] = "NoFilePanels",
[0x00002000] = "NoFilePPanels",
[0x00004000] = "NoPluginPanels",
[0x00008000] = "NoPluginPPanels",
[0x00010000] = "NoFolders",
[0x00020000] = "NoPFolders",
[0x00040000] = "NoFiles",
[0x00080000] = "NoPFiles",
}
local MacroFlagsByStr={}
for k,v in pairs(MacroFlagsByInt) do MacroFlagsByStr[v:lower()]=k end
function StringToFlags (str, filename)
local flags = 0
if type(str) == "string" then
for word in str:gmatch("[^ |]+") do
local f = MacroFlagsByStr[word:lower()]
if f then
flags = bor(flags, f)
else
local line1 = filename or "<not a file>"
local btn = filename and "OK;Edit" or "OK"
if 2 == ErrMsg(line1.."\nInvalid macro flag: "..word, nil, btn) then
editor.Editor(filename,nil,nil,nil,nil,nil,nil,1,nil,65001)
end
end
end
end
return flags
end
-- assume 52 bits at most
function FlagsToString (flags)
local str, bit = "", 1
while flags >= bit do
if band(flags,bit) ~= 0 then
local s = MacroFlagsByInt[bit]
if s then
if str ~= "" then str = str.." " end
str = str..s
end
end
bit = bit * 2
end
return str
end
end
local function ReadIniFile (filename)
local fp = io.open(filename)
if not fp then return nil end
local currsect = 1
local t = { [currsect]={} }
local numline = 0
if fp:read(3) ~= "\239\187\191" then fp:seek("set",0) end -- skip UTF-8 BOM
for line in fp:lines() do
numline = numline + 1
local sect = line:match("^%s*%[([^%]]+)%]%s*$")
if sect then
t[sect] = t[sect] or {}
currsect = sect
else
local id,val = line:match("^%s*(%w+)%s*=%s*(.-)%s*$")
if id then
t[currsect][id] = val
elseif not (line:match("^%s*;") or line:match("^%s*$")) then
fp:close()
return nil, (("%s:%d: invalid line in ini-file"):format(filename,numline))
end
end
end
fp:close()
return t
end
local function AddId (trg, src)
trg.id = "<no id>"
if type(src.id)=="string" then
local lstr = string.lower(src.id)
if not IdSet[lstr] then
IdSet[lstr] = true
trg.id = src.id
end
end
end
local function EV_Handler (macros, filename, ...)
-- Get current priorities.
local indexes,priorities = {},{}
for i,m in ipairs(macros) do
indexes[i],priorities[i] = i, -1
if (not m.filemask) or (filename and CheckFileName(m.filemask, filename)) then
if m.condition then
local pr = m.condition(...)
if pr then
if type(pr)=="number" then priorities[i] = pr<0 and 0 or pr>100 and 100 or pr
else priorities[i] = m.priority
end
end
else
priorities[i] = m.priority
end
end
end
-- Sort by current priorities (stable sort).
table.sort(indexes, function(i,j)
return priorities[i]>priorities[j] or priorities[i]==priorities[j] and i<j
end)
-- Execute.
for _,i in ipairs(indexes) do
if priorities[i] < 0 then break end
local ret = macros[i].action(...)
if ret then
if macros==Events.dialogevent or macros==Events.editorinput or macros==Events.commandline then
return ret
elseif macros==Events.consoleinput then
if ret ~= 0 then return ret end
end
end
end
end
local Subscriptions = {}
local SubscribeChangeEvent = editor.SubscribeChangeEvent
function editor.SubscribeChangeEvent (EditorID, Subscribe)
if not EditorID or EditorID==F.CURRENT_EDITOR then
local info = editor.GetInfo(EditorID)
if not info then return false end
EditorID = info.EditorID
end
local count = Subscriptions[EditorID]
if count then
local result = true
if Subscribe then
if count==0 then result=SubscribeChangeEvent(EditorID,true) end
if result then Subscriptions[EditorID]=count+1 end
else
if count==1 then result=SubscribeChangeEvent(EditorID,false) end
if result and count>0 then Subscriptions[EditorID]=count-1 end
end
return result
end
return false
end
function export.ProcessEditorEvent (EditorID, Event, Param)
if Event==F.EE_READ then Subscriptions[EditorID]=0
elseif Event==F.EE_CLOSE then Subscriptions[EditorID]=nil
end
return EV_Handler(Events.editorevent, editor.GetFileName(EditorID), EditorID, Event, Param)
end
local function export_ProcessViewerEvent (ViewerID, Event, Param)
return EV_Handler(Events.viewerevent, viewer.GetFileName(ViewerID), ViewerID, Event, Param)
end
local function export_ExitFAR (unload)
return EV_Handler(Events.exitfar, nil, not not unload)
end
local function export_ProcessDialogEvent (Event, Param)
return EV_Handler(Events.dialogevent, nil, Event, Param)
end
local function export_ProcessEditorInput (Rec)
return EV_Handler(Events.editorinput, editor.GetFileName(nil), Rec)
end
local function export_ProcessConsoleInput (Rec, Flags)
return EV_Handler(Events.consoleinput, nil, Rec, Flags)
end
local function export_GetContentFields (colnames)
for _,m in ipairs(ContentColumns) do
if m.GetContentFields(colnames) then return true end
end
end
local function export_GetContentData (filename, colnames)
local tOut = {}
for _,m in ipairs(ContentColumns) do
if m.filemask==nil or CheckFileName(m.filemask, filename) then
local data = m.GetContentData(filename, colnames)
if type(data) == "table" then
for i in ipairs(colnames) do
tOut[i] = tOut[i] or (type(data[i])=="string" and data[i])
end
end
end
end
return tOut
end
local ExpandKey do -- измеренное время исполнения на ключе "CtrlAltShiftF12" = ??? (Lua); 2.3uS (LuaJIT);
local t={}
ExpandKey = function (key)
local ctrl,alt,rest
key = key:lower()
local start = 1
for k=1,3 do
local from,to,word = string_find(key, "^([lr]?ctrl)", start)
if from then ctrl = ctrl or word
else
from,to,word = string_find(key, "^([lr]?alt)", start)
if from then alt = alt or word
else
from,to,word = string_find(key, "^(shift)", start)
if from then rest = rest or word
else break
end
end
end
start = to+1
end
rest = (rest or "")..string_sub(key, start)
ctrl, alt = ctrl or "", alt or ""
if ctrl=="ctrl" then
if alt=="alt" then
t[1] = "lctrllalt"..rest; t[2] = "lctrlralt"..rest
t[3] = "rctrllalt"..rest; t[4] = "rctrlralt"..rest
return t,4
else
t[1] = "lctrl"..alt..rest
t[2] = "rctrl"..alt..rest
return t,2
end
else
if alt=="alt" then
t[1] = ctrl.."lalt"..rest
t[2] = ctrl.."ralt"..rest
return t,2
else
t[1] = ctrl..alt..rest
return t,1
end
end
end
end
local function AddRegularMacro (srctable, FileName)
if not (type(srctable)=="table" and type(srctable.area)=="string") then
return
end
local macro = {}
macro.area = srctable.area
macro.key = type(srctable.key)=="string" and srctable.key or "none"
if not macro.key:find("%S") then macro.key = "none" end
local keyregex, ok = macro.key:match("^/(.+)/$"), nil
if keyregex then
ok, macro.keyregex = pcall(regex.new, "^("..keyregex..")$", "i")
if not ok then
ErrMsg("Invalid regex: "..macro.key)
return
end
end
if type(srctable.action)=="function" then
macro.action = srctable.action
elseif type(srctable.code)=="string" then
local isMoonScript = srctable.language=="moonscript"
if srctable.code:sub(1,1) == "@" then
macro.code = srctable.code
macro.language = isMoonScript and "moonscript" or "lua"
else
local f, msg = (isMoonScript and require("moonscript").loadstring or loadstring)(srctable.code)
if f then
macro.action = f
else
if FileName then ErrMsg(FileName..":\n"..msg, isMoonScript and "MoonScript"); end
return
end
end
else
return
end
local arFound = {} -- prevent multiple inclusions, i.e. area="Editor Editor"
for a in srctable.area:lower():gmatch("%S+") do
local arTable = Areas[a]
if arTable and not arFound[a] then
if macro.keyregex then
arTable[1] = arTable[1] or {}
table.insert(arTable[1], macro)
else
local keyFound = {} -- prevent multiple inclusions
for k in macro.key:lower():gmatch("%S+") do
local t,n = ExpandKey(k)
for i=1,n do
local normkey = t[i]
if not keyFound[normkey] then
arTable[normkey] = arTable[normkey] or {}
table.insert(arTable[normkey], macro)
keyFound[normkey] = true
end
end
end
end
arFound[a] = true
end
end
if next(arFound) then
macro.flags = StringToFlags(srctable.flags, FileName)
if type(srctable.description)=="string" then macro.description=srctable.description end
if type(srctable.condition)=="function" then macro.condition=srctable.condition end
if type(srctable.filemask)=="string" then macro.filemask=srctable.filemask end
local priority = srctable.priority
if type(priority)=="number" then
macro.priority = priority>100 and 100 or priority<0 and 0 or priority
end
priority = srctable.sortpriority
if type(priority)=="number" then
macro.sortpriority = priority>100 and 100 or priority<0 and 0 or priority
end
macro.selected = srctable.selected and true
AddId(macro, srctable)
if FileName then
macro.FileName = FileName
else
macro.guid = srctable.guid
macro.callback = srctable.callback
macro.callbackId = srctable.callbackId
macro.language = srctable.language
end
macro.data = {}
for k,v in pairs(srctable) do macro.data[k]=v; end
macro.index = #LoadedMacros+1
LoadedMacros[macro.index] = macro
return macro
end
end
local CharNames = { ["."]="Dot", ["<"]="Less", [">"]="More", ["|"]="Pipe", ["/"]="Slash",
[":"]="Colon", ["?"]="Question", ["*"]="Asterisk", ['"']="Quote" }
local function AddRecordedMacro (srctable, filename)
local area = srctable.area:lower()
if not (area and Areas[area]) then return end
local arTable = Areas[area]
local key = srctable.key
-- check correspondence between (a) filename and (b) area_key
if ("%s_%s"):format(area, (key:gsub(".",CharNames))):lower() ~=
filename:gsub("^.*\\",""):sub(1,-5):lower() then return
end
if srctable.code and srctable.code:sub(1,1) ~= "@" then
local f, msg = loadstring(srctable.code)
if not f then ErrMsg(msg) return end
end
local macro = { FileName=filename }
local t,n = ExpandKey(key)
for i=1,n do
local normkey = t[i]
arTable[normkey] = arTable[normkey] or {}
arTable[normkey].recorded = macro
end
for _,v in ipairs{"area","key","action","code","description"} do macro[v]=srctable[v] end
macro.flags = StringToFlags(srctable.flags, filename)
if type(macro.description)~="string" then macro.description=nil end
macro.index = #LoadedMacros+1
LoadedMacros[macro.index] = macro
end
local AddEvent_fields = {"group","action","description","priority","condition","filemask"}
local function AddEvent (srctable, FileName)
local group = type(srctable)=="table" and type(srctable.group)=="string" and srctable.group:lower()
if not (group and Events[group]) then return end
if type(srctable.action)~="function" then return end
local macro={}
table.insert(Events[group], macro)
for _,v in ipairs(AddEvent_fields) do macro[v]=srctable[v] end
macro.FileName = FileName
if type(macro.description)~="string" then macro.description=nil end
if type(macro.condition)~="function" then macro.condition=nil end
if type(macro.filemask)~="string" then macro.filemask=nil end
if type(macro.priority)~="number" then macro.priority=50
elseif macro.priority>100 then macro.priority=100 elseif macro.priority<0 then macro.priority=0
end
AddId(macro, srctable)
macro.index = #LoadedMacros+1
LoadedMacros[macro.index] = macro
return macro
end
local function AddMenuItem (srctable, FileName)
if type(srctable)=="table" and
type(srctable.menu)=="string" and
type(srctable.guid)=="string" and
(type(srctable.text)=="function" or type(srctable.text)=="string") and
type(srctable.action)=="function"
then
local item = {}
item.guid = win.Uuid(srctable.guid)
if item.guid and #item.guid==16 and not AddedMenuItems[item.guid] then
item.flags = {}
for w in srctable.menu:lower():gmatch("%S+") do
if w=="plugins" or w=="disks" or w=="config" then item.flags[w]=true end
end
if type(srctable.area)=="string" then
for w in srctable.area:lower():gmatch("%S+") do
if w == "common" then
item.flags[w]=true
else
local code = GetAreaCode(w)
if code then item.flags[code]=true end
end
end
end
local text = srctable.text
item.text = type(text)=="function" and text or function() return text end
item.action = srctable.action
item.description = type(srctable.description)=="string" and srctable.description or ""
item.FileName = FileName
item.index = #AddedMenuItems + 1
AddedMenuItems[item.index] = item
AddedMenuItems[item.guid] = item
return true
end
end
return false
end
local function AddPrefixes (srctable, FileName)
local result = 0
if type(srctable)=="table" and
type(srctable.prefixes)=="string" and
type(srctable.action)=="function"
then
for prefix in srctable.prefixes:lower():gmatch("[^:]+") do
if prefix:match("^%S+$") and not AddedPrefixes[prefix] then
local item = {
prefix = prefix,
action = srctable.action,
description = type(srctable.description)=="string" and srctable.description or "",
FileName = FileName
}
AddedPrefixes[prefix] = item
AddedPrefixes[1] = AddedPrefixes[1]..":"..prefix
result = result + 1
end
end
end
return result
end
local function AddPanelModule (srctable, FileName)
if type(srctable) == "table" and type(srctable.Info) == "table" then
local guid = srctable.Info.Guid
if type(guid) == "string" and #guid == 16 then
if not LoadedPanelModules[guid] then
if FileName then srctable.FileName=FileName; end
LoadedPanelModules[guid] = srctable
table.insert(LoadedPanelModules, srctable)
end
end
end
end
local function AddContentColumns (srctable, FileName)
if type(srctable) == "table"
and type(srctable.GetContentFields) == "function"
and type(srctable.GetContentData) == "function"
then
if type(srctable.filemask)~="string" then srctable.filemask=nil; end
table.insert(ContentColumns, srctable)
end
end
local function EnumMacros (strArea, resetEnum)
local area = strArea:lower()
if Areas[area] then
if EnumState.area ~= area or resetEnum then
EnumState.area, EnumState.index = area, 0
end
while true do
EnumState.index = EnumState.index + 1
local macro = LoadedMacros[EnumState.index]
if macro then
if not macro.disabled and macro.area and macro.area:lower():find(area) then
LastMessage = pack(macro.key, macro.description or "")
return LastMessage
end
else
EnumState.index = 0
break
end
end
end
end
local function GetMoonscriptLineNumber (filename, line)
local line_tables = require("moonscript.line_tables")
local errors = require("moonscript.errors")
local cache = {}
local table = line_tables["@"..filename]
if table then
return errors.reverse_line_number(filename, table, line, cache)
end
end
-- ...nager\unicode_far\CommonProfile\Macros\scripts\test1.lua:9:
-- attempt to perform arithmetic on a nil value
local function ErrMsgLoad (msg, filename, isMoonScript, mode)
local title = isMoonScript and mode=="compile" and "MoonScript" or "LuaMacro"
if type(msg)~="string" and type(msg)~="number" then
ErrMsg(filename..":\n<non-string error message>", title, nil, "w")
return
end
if mode=="run" then
local found = false
local fname,line = msg:match("^(.-):(%d+):")
if fname then
line = tonumber(line)
if string_sub(fname,1,3) ~= "..." then
found = true
else
fname = string_sub(fname,4)
-- for k=1,5 do
-- if fname:utf8valid() then break end
-- fname = string_sub(fname,2)
-- end
fname = fname:gsub("/", "\\")
local middle = fname:match([=[^[^\\]*\[^\\]+\]=])
if middle then
local from = string_find(filename:lower(), middle:lower(), 1, true)
if from then
fname = string_sub(filename,1,from-1) .. fname
local attr = win.GetFileAttr(fname)
found = attr and not attr:find("d")
end
end
end
end
if found then
if 2 == ErrMsg(msg, title, "OK;Edit", "wl") then
if isMoonScript then line = GetMoonscriptLineNumber(fname,line) end
editor.Editor(fname,nil,nil,nil,nil,nil,nil,line or 1,nil,65001)
end
else
ErrMsg(msg, title, "OK", "wl")
end
else
if 2 == far.Message(msg, title, "OK;Edit", "wl") then
local pattern = isMoonScript and "%[(%d+)%] >>" or "^[^\n]-:(%d+):"
local line = tonumber(msg:match(pattern))
if line and isMoonScript and mode=="run" then line = GetMoonscriptLineNumber(filename,line) end
editor.Editor(filename,nil,nil,nil,nil,nil,nil,line or 1,nil,65001)
end
end
end
local function LoadMacros (unload, paths)
if LoadingInProgress then return end
LoadingInProgress = true
if LoadMacrosDone then
local ok, msg = xpcall(function() return export_ExitFAR(true) end,
function(msg) return debug.traceback(msg,2) end)
if not ok then
msg = string.gsub(msg, "\t", " ")
ErrMsg(msg)
end
LoadMacrosDone = false
end
export.ExitFAR = nil
export.ProcessDialogEvent = nil
export.ProcessEditorInput = nil
export.ProcessViewerEvent = nil
export.ProcessConsoleInput = nil
export.GetContentFields = nil
export.GetContentData = nil
local allAreas = band(MacroCallFar(MCODE_F_GETOPTIONS),0x3) == 0
local numerrors=0
local newAreas = {}
Events = {}
EnumState = {}
LoadedMacros = {}
AddedMenuItems = {}
AddedPrefixes = { [1]="" }
IdSet = {}
LoadedPanelModules = {}
ContentColumns = {}
if Shared.panelsort then Shared.panelsort.DeleteSortModes() end
local AreaNames = allAreas and AllAreaNames or SomeAreaNames
for _,name in pairs(AreaNames) do newAreas[name]={} end
for _,name in ipairs(EventGroups) do Events[name]={} end
for k in pairs(package.loaded) do
if initial_modules[k]==nil and not package.nounload[k] then
package.loaded[k]=nil
end
end
-- Copy macros loaded by MCTL_ADDMACRO to save them from destruction.
if Areas then
local IdUpdated = {}
for a,areatable in pairs(Areas) do
for k,macroarray in pairs(areatable) do
for i,m in ipairs(macroarray) do
if m.guid and not m.disabled then
newAreas[a][k] = newAreas[a][k] or {}
table.insert(newAreas[a][k], m)
if not IdUpdated[m] then
IdUpdated[m] = true
m.index = #LoadedMacros+1
LoadedMacros[m.index] = m
end
end
end
end
end
end
Areas = newAreas
if not unload then
LoadCounter = LoadCounter + 1
local DummyFunc = function() end
local DirMacros = win.GetEnv("farprofile").."\\Macros\\"
if 0 == band(MacroCallFar(MCODE_F_GETOPTIONS),0x10) then -- not ReadOnlyConfig
for _,v in ipairs {"scripts", "modules", "lib32", "lib64"} do
win.CreateDir(DirMacros..v)
end
win.CreateDir(win.GetEnv("farprofile").."\\Menus")
end
local moonscript = require "moonscript"
local FuncList1 = {"Macro", "Event", "MenuItem", "CommandLine", "PanelModule", "ContentColumns"}
local FuncList2 = {"NoMacro","NoEvent","NoMenuItem","NoCommandLine","NoPanelModule","NoContentColumns"}
local function LoadRegularFile (FindData, FullPath, macroinit)
if FindData.FileAttributes:find("d") then return end
if macroinit and #FullPath==#macroinit and far.LStricmp(FullPath,macroinit)==0 then
return
end
local isMoonScript = string_find(FullPath, "[nN]", -1)
local f, msg = (isMoonScript and moonscript.loadfile or loadfile)(FullPath)
if not f then
numerrors=numerrors+1
ErrMsgLoad(msg,FullPath,isMoonScript,"compile")
return
end
local env = {
Macro = function(t) return not not AddRegularMacro(t,FullPath) end;
Event = function(t) return not not AddEvent(t,FullPath) end;
MenuItem = function(t) return AddMenuItem(t,FullPath) end;
CommandLine = function(t) return AddPrefixes(t,FullPath) end;
PanelModule = function(t) return AddPanelModule(t,FullPath) end;
ContentColumns = function(t) return AddContentColumns(t,FullPath) end;
}
for _,name in ipairs(FuncList2) do env[name]=DummyFunc; end
setmetatable(env,gmeta)
setfenv(f, env)
local ok, msg = xpcall(function() return f(FullPath, LoadCounter) end, debug.traceback)
if ok then
for _,name in ipairs(FuncList1) do env[name]=nil; end
for _,name in ipairs(FuncList2) do env[name]=nil; end
else
numerrors=numerrors+1
msg = string.gsub(msg,"\n\t","\n ")
ErrMsgLoad(msg,FullPath,isMoonScript,"run")
end
end
local tempRecordedMacro
local function ReadRecordedMacro (m)
if tempRecordedMacro == nil then
if type(m) == "table" then
local t_action, t_code = type(m.action), type(m.code)
tempRecordedMacro = type(m.area)=="string" and type(m.key)=="string" and
(t_action=="function" and t_code=="nil" or t_action=="nil" and t_code=="string") and m
else
tempRecordedMacro = false
end
end
end
local function LoadRecordedFile (FindData, FullPath)
if FindData.FileAttributes:find("d") then return end
local f, msg = loadfile(FullPath)
if not f then
numerrors=numerrors+1; ErrMsg(msg); return
end
local env = setmetatable({ Macro=ReadRecordedMacro }, gmeta)
setfenv(f, env)
tempRecordedMacro = nil
local ok, msg = xpcall(f, debug.traceback)
if ok then
if tempRecordedMacro then
env.Macro = nil
AddRecordedMacro(tempRecordedMacro, FullPath)
end
else
msg = msg:gsub("\n\t","\n ")
numerrors=numerrors+1; ErrMsg(msg)
end
end
if paths then
paths = ExpandEnv(paths)
else
paths = DirMacros.."scripts"
local cfg, msg = ReadIniFile(far.PluginStartupInfo().ModuleDir.."luamacro.ini")
if cfg then
if cfg.General then
local p = cfg.General.MacroPath
if p then paths = ExpandEnv(p) end
end
else
if msg then ErrMsg(msg) end
end
end
for p in paths:gmatch("[^;]+") do
p = far.ConvertPath(p, F.CPM_FULL) -- needed for relative paths
local macroinit = p:gsub("[\\/]*$", "\\_macroinit.lua")
local info = win.GetFileInfo(macroinit)
if info and not info.FileAttributes:find("d") then
LoadRegularFile(info, macroinit, nil)
else
macroinit = nil
end
far.RecursiveSearch (p, "*.lua,*.moon", LoadRegularFile, bor(F.FRS_RECUR,F.FRS_SCANSYMLINK), macroinit)
end
far.RecursiveSearch (DirMacros.."internal", "*.lua", LoadRecordedFile, 0)
export.ExitFAR = Events.exitfar[1] and export_ExitFAR
export.ProcessDialogEvent = Events.dialogevent[1] and export_ProcessDialogEvent
export.ProcessEditorInput = Events.editorinput[1] and export_ProcessEditorInput
export.ProcessViewerEvent = Events.viewerevent[1] and export_ProcessViewerEvent
export.ProcessConsoleInput = Events.consoleinput[1] and export_ProcessConsoleInput
if ContentColumns[1] then
export.GetContentFields = export_GetContentFields
export.GetContentData = export_GetContentData
end
LoadMacrosDone = true
end
LoadingInProgress = nil
return numerrors==0
end
local function InitMacroSystem()
LoadMacros(true)
end
local function WriteOneMacro (dir, macro, keyname, delete)
local fname = ("%s\\%s_%s.lua"):format(dir, macro.area, (keyname:gsub(".", CharNames)))
local attr = win.GetFileAttr(fname)
if attr then
win.SetFileAttr(fname, "")
win.DeleteFile(fname)
end
if delete then return end
-- operation "write"
local fp, msg = io.open(fname, "w")
if fp then
fp:write(([[
Macro {
description=%q;
area=%q; key=%q;
flags=%q;
code=%q;
}
]]):format(macro.description, macro.area, macro.key, FlagsToString(macro.flags), macro.code))
fp:close()
macro.FileName = fname
end
end
local function WriteMacros()
if 0 ~= band(MacroCallFar(MCODE_F_GETOPTIONS),0x10) then return end -- ReadOnlyConfig
local dir = win.GetEnv("farprofile").."\\Macros\\internal"
if not win.CreateDir(dir, true) then return end
for areaname,area in pairs(Areas) do
for keyname,macroarray in pairs(area) do
local macro = macroarray.recorded
if macro and macro.needsave then
WriteOneMacro(dir, macro, macro.key, macro.disabled)
macro.needsave = nil
if macro.disabled then
macroarray.recorded = nil
end
end
end
end
return true
end
local function GetFromMenu (menuitems, area, key)
for i,item in ipairs(menuitems) do
local descr = item.macro.description
if not descr or descr=="" then
descr = Msg.UtNoDescription_Index:format(item.macro.index)
end
item.text = descr
item.selected = item.macro.selected
end
table.sort(menuitems,
function(item1,item2)
local p1,p2 = item1.priority, item2.priority
local s1,s2 = item1.macro.sortpriority or 50, item2.macro.sortpriority or 50
return p1>p2 or p1==p2 and (s1>s2 or s1==s2 and far.LStricmp(item1.text, item2.text) < 0)
end)
local pos_sep
for i,item in ipairs(menuitems) do
if item.priority < menuitems[1].priority then
pos_sep = i; break
end
end
local bkeys = { {BreakKey="A+F4"} }
for i,item in ipairs(menuitems) do
local ch = i<10 and tostring(i) or i<36 and string.char(i+55)
if ch then
local pos = pos_sep and i>=pos_sep and i+1 or i
item.text = ch..". "..item.text
table.insert(bkeys, {BreakKey=ch, pos=pos})
if i>=10 then table.insert(bkeys, {BreakKey=ch:lower(), pos=pos}) end
end
end
if pos_sep then
table.insert(menuitems, pos_sep, {separator=true, text=Msg.UtLowPriority})
end
local props = {
Title = ("%s: %s | %s"):format(Msg.UtExecuteMacroTitle, area, key),
Bottom = Msg.UtExecuteMacroBottom,
Flags = { FMENU_WRAPMODE=1, FMENU_CHANGECONSOLETITLE=1 },
Id = win.Uuid("165AA6E3-C89B-4F82-A0C5-C309243FD21B") }
while true do
local item, pos = far.Menu(props, menuitems, bkeys)
if not item then
return
elseif item.macro then
return item.macro
elseif item.BreakKey == "A+F4" then
props.SelectIndex = pos
local m = menuitems[pos].macro
if m.FileName then
local startline = m.action and debug.getinfo(m.action,"S").linedefined
editor.Editor(m.FileName,nil,nil,nil,nil,nil,nil,startline,nil,65001)
end
elseif item.pos then
return menuitems[item.pos].macro
end
end
end
local function GetMacro (argMode, argKey, argUseCommon, argCheckOnly)
if LoadingInProgress then return end
local area = GetAreaName(argMode)
if not area then return end -- трюк используется в CheckForEscSilent() в Фаре
local key = argKey:lower()
do
local alt
local from,to,ctrl = string_find(key, "^(r?ctrl)")
if ctrl=="ctrl" then ctrl="lctrl" end
local start = to and to+1 or 1
from,to,alt = string_find(key, "^(r?alt)", start)
if alt=="alt" then alt="lalt" end
start = to and to+1 or start
key = (ctrl or "") .. (alt or "") .. string_sub(key, start)
end