-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPakettiAutocomplete.lua
More file actions
4396 lines (3813 loc) · 157 KB
/
PakettiAutocomplete.lua
File metadata and controls
4396 lines (3813 loc) · 157 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
-- PakettiAutocomplete.lua
-- Autocomplete dialog system with real-time filtering and selection
-- Dialog width configuration
local DIALOG_WIDTH = 690
local SCROLLBAR_WIDTH = 20
local BUTTON_WIDTH = DIALOG_WIDTH - SCROLLBAR_WIDTH
local SEARCH_LABEL_WIDTH = 80
local SEARCH_FIELD_WIDTH = DIALOG_WIDTH - SEARCH_LABEL_WIDTH
-- Dialog and UI state variables
local autocomplete_dialog = nil
local autocomplete_vb = nil
local suggestion_buttons = {}
local search_display_text = nil
local status_text = nil
local current_filter = ""
local current_filtered_commands = {}
local selected_suggestion_index = 0
local create_abbrev_button = nil
local command_picker_dialog = nil
local suggestions_scrollbar = nil
local prev_page_button = nil
local next_page_button = nil
local show_only_with_shortcuts_checkbox = nil
-- Scrolling variables
local MAX_VISIBLE_BUTTONS = 40
local current_scroll_offset = 0
-- Button display tracking variables (for optimization)
local previous_suggestion_index = 0
local last_commands_count = 0
local last_commands_hash = ""
-- Real Paketti commands (dynamically loaded)
local paketti_commands = {}
local command_descriptions = {}
local user_abbreviations = {}
-- Performance optimization variables
local commands_cache = {}
local search_index = {}
local recent_commands = {}
local favorite_commands = {}
local command_usage_count = {}
local last_scan_time = 0
local current_context = "global" -- global, pattern_editor, sample_editor, mixer, etc.
-- Shortcut mapping cache
local function_shortcut_mappings = {}
local shortcut_cache_file_path = renoise.tool().bundle_path .. "autocomplete_shortcuts.txt"
-- Autocomplete state (CP-style)
local current_search_text = ""
-- Cache file paths
local cache_file_path = renoise.tool().bundle_path .. "autocomplete_cache.txt"
local usage_file_path = renoise.tool().bundle_path .. "autocomplete_usage.txt"
local favorites_file_path = renoise.tool().bundle_path .. "autocomplete_favorites.txt"
-- Helper functions for KeyBindings.xml parsing (borrowed from PakettiKeyBindings.lua)
local function detectOSAndGetKeyBindingsPath()
local os_name = os.platform()
local renoise_version = renoise.RENOISE_VERSION:match("(%d+%.%d+%.%d+)") -- This will grab just "3.5.0" from "3.5.0 b8"
local key_bindings_path
if os_name == "WINDOWS" then
local home = os.getenv("USERPROFILE") or os.getenv("HOME")
key_bindings_path = home .. "\\AppData\\Roaming\\Renoise\\V" .. renoise_version .. "\\KeyBindings.xml"
elseif os_name == "MACINTOSH" then
local home = os.getenv("HOME")
key_bindings_path = home .. "/Library/Preferences/Renoise/V" .. renoise_version .. "/KeyBindings.xml"
else -- Assume Linux
local home = os.getenv("HOME")
key_bindings_path = home .. "/.config/Renoise/V" .. renoise_version .. "/KeyBindings.xml"
end
return key_bindings_path
end
local function decodeXMLString(value)
local replacements = {
["&"] = "&",
-- Add more replacements if needed
}
return value:gsub("(&)", replacements)
end
local function convert_key_name(key)
-- Split the key combination into parts
local parts = {}
for part in key:gmatch("[^%+]+") do
-- Trim spaces
part = part:match("^%s*(.-)%s*$")
-- Convert special keys
if part == "Backslash" then part = "\\"
elseif part == "Slash" then part = "/"
elseif part == "Apostrophe" then part = "'"
elseif part == "PeakedBracket" then part = "<"
elseif part == "Capital" then part = "CapsLock"
elseif part == "Grave" then part = "§"
elseif part == "Comma" then part = ","
-- Shorten modifier keys for cleaner display
elseif part == "Command" then part = "CMD"
elseif part == "Control" then part = "CTRL"
elseif part == "Option" then part = "OPT"
end
table.insert(parts, part)
end
return table.concat(parts, " + ")
end
local function parseKeyBindingsXML(filePath, filter_type)
local fileHandle = io.open(filePath, "r")
if not fileHandle then
print("Debug: Failed to open the file - " .. filePath)
return {}
end
local content = fileHandle:read("*all")
fileHandle:close()
local keybindings = {}
local currentIdentifier = "nil"
for categorySection in content:gmatch("<Category>(.-)</Category>") do
local identifier = categorySection:match("<Identifier>(.-)</Identifier>") or "nil"
if identifier ~= "nil" then
currentIdentifier = identifier
end
for keyBindingSection in categorySection:gmatch("<KeyBinding>(.-)</KeyBinding>") do
local topic = keyBindingSection:match("<Topic>(.-)</Topic>")
-- Apply filter based on filter_type
local should_include = false
if filter_type == "paketti" then
should_include = topic and topic:find("Paketti")
elseif filter_type == "renoise" or filter_type == "all" then
should_include = topic ~= nil
end
if should_include then
local binding = keyBindingSection:match("<Binding>(.-)</Binding>") or "<No Binding>"
local key = keyBindingSection:match("<Key>(.-)</Key>") or "<Shortcut not Assigned>"
-- Decode XML entities
topic = decodeXMLString(topic)
binding = decodeXMLString(binding)
key = decodeXMLString(key)
table.insert(keybindings, { Identifier = currentIdentifier, Topic = topic, Binding = binding, Key = key })
end
end
end
return keybindings
end
-- Function to build function-shortcut mappings from KeyBindings.xml
local function build_function_shortcut_mappings()
function_shortcut_mappings = {}
shortcut_lookup_cache = {} -- Clear lookup cache when rebuilding mappings
local keyBindingsPath = detectOSAndGetKeyBindingsPath()
if not keyBindingsPath then
print("PakettiAutocomplete: Could not detect KeyBindings.xml path for shortcut mapping")
return
end
print("PakettiAutocomplete: Building function-shortcut mappings from " .. keyBindingsPath)
-- Parse both Paketti and Renoise keybindings
local pakettiBindings = parseKeyBindingsXML(keyBindingsPath, "paketti")
local renoiseBindings = parseKeyBindingsXML(keyBindingsPath, "renoise")
local mappings_added = 0
-- Add Paketti bindings using Binding as the key (this is the actual function name!)
for _, binding in ipairs(pakettiBindings) do
if binding.Key and binding.Key ~= "<Shortcut not Assigned>" and binding.Binding then
local binding_name = binding.Binding
local readableKey = convert_key_name(binding.Key)
-- Strip the "∿ " prefix from Binding
-- Binding: "∿ Impulse Tracker F2 Pattern Editor" -> "Impulse Tracker F2 Pattern Editor"
local function_name = binding_name:match("^∿ (.+)") or binding_name
-- Add "Paketti:" prefix to match autocomplete format
local autocomplete_name = "Paketti:" .. function_name
-- Debug first few bindings
if mappings_added < 5 then
print("DEBUG: Paketti binding " .. (mappings_added + 1) .. ":")
print(" Original Binding: " .. binding_name)
print(" Function name: " .. function_name)
print(" Autocomplete name: " .. autocomplete_name)
print(" Key: " .. (binding.Key or "nil"))
print(" Storing as: '" .. autocomplete_name .. "' -> '" .. readableKey .. "'")
end
-- Store the mapping using autocomplete format as key
function_shortcut_mappings[autocomplete_name] = readableKey
mappings_added = mappings_added + 1
end
end
-- Add Renoise bindings using Binding as the key (this is the actual function name!)
for _, binding in ipairs(renoiseBindings) do
if binding.Key and binding.Key ~= "<Shortcut not Assigned>" and binding.Binding then
local binding_name = binding.Binding
local readableKey = convert_key_name(binding.Key)
-- For Renoise bindings, use the Binding directly (no ∿ prefix to strip)
local function_name = binding_name
-- Debug first few bindings
if mappings_added < 10 then
print("DEBUG: Renoise binding " .. (mappings_added + 1) .. ":")
print(" Binding: " .. binding_name)
print(" Key: " .. (binding.Key or "nil"))
print(" Storing as: '" .. function_name .. "' -> '" .. readableKey .. "'")
end
-- Store the mapping using Binding as key
function_shortcut_mappings[function_name] = readableKey
mappings_added = mappings_added + 1
end
end
print("PakettiAutocomplete: Built " .. mappings_added .. " function-shortcut mappings")
end
-- Function to save shortcut mappings to cache
local function save_shortcut_mappings()
-- Count before saving
local count_before = 0
for _ in pairs(function_shortcut_mappings) do
count_before = count_before + 1
end
print("DEBUG: About to save " .. count_before .. " mappings")
local file = io.open(shortcut_cache_file_path, "w")
if file then
file:write("SHORTCUT_CACHE_VERSION=1.0\n")
local written_count = 0
local error_count = 0
for functionName, shortcut in pairs(function_shortcut_mappings) do
-- Check for problematic characters that might cause write issues
if functionName and shortcut and functionName ~= "" and shortcut ~= "" then
-- Use ||| delimiter to avoid conflicts (same as main cache)
local line = functionName .. "|||" .. shortcut .. "\n"
local success, err = pcall(function() file:write(line) end)
if success then
written_count = written_count + 1
-- Debug first few writes
if written_count <= 3 then
print("DEBUG: Writing mapping " .. written_count .. ": " .. functionName .. " -> " .. shortcut)
end
else
error_count = error_count + 1
if error_count <= 3 then
print("DEBUG: Error writing mapping: " .. (err or "unknown error"))
end
end
else
error_count = error_count + 1
if error_count <= 3 then
print("DEBUG: Skipping invalid mapping: '" .. tostring(functionName) .. "' -> '" .. tostring(shortcut) .. "'")
end
end
end
file:close()
print("PakettiAutocomplete: Saved " .. written_count .. " shortcut mappings to cache (" .. error_count .. " errors)")
else
print("PakettiAutocomplete: Failed to save shortcut mappings to cache")
end
end
-- Function to load shortcut mappings from cache
local function load_shortcut_mappings()
local file = io.open(shortcut_cache_file_path, "r")
if not file then
print("PakettiAutocomplete: No shortcut cache file found")
return false
end
function_shortcut_mappings = {}
shortcut_lookup_cache = {} -- Clear lookup cache when loading new mappings
local version = file:read("*line")
if not version or not version:match("SHORTCUT_CACHE_VERSION=1%.0") then
file:close()
print("PakettiAutocomplete: Invalid shortcut cache version")
return false
end
local count = 0
for line in file:lines() do
local pos = string.find(line, "|||")
if pos then
local functionName = string.sub(line, 1, pos - 1)
local shortcut = string.sub(line, pos + 3)
function_shortcut_mappings[functionName] = shortcut
count = count + 1
end
end
file:close()
print("PakettiAutocomplete: Loaded " .. count .. " shortcut mappings from cache")
return true
end
-- Performance cache for shortcut lookups
local shortcut_lookup_cache = {}
-- Function to get shortcut for a command (OPTIMIZED - no loops!)
local function get_command_shortcut(command)
if not command or not command.name then
return ""
end
local command_name = command.name
-- Check cache first for instant lookup
if shortcut_lookup_cache[command_name] ~= nil then
return shortcut_lookup_cache[command_name]
end
local result = ""
-- Direct O(1) lookup: check if the command name matches any mapping
local shortcut = function_shortcut_mappings[command_name]
if shortcut then
result = " [" .. shortcut .. "]"
else
-- Try without prefix (remove "Paketti:" or other prefixes)
local command_without_prefix = command_name:match("^[^:]+:(.+)") or command_name
if command_without_prefix ~= command_name then
local shortcut_without_prefix = function_shortcut_mappings[command_without_prefix]
if shortcut_without_prefix then
result = " [" .. shortcut_without_prefix .. "]"
end
end
end
-- Cache the result for future lookups
shortcut_lookup_cache[command_name] = result
return result
end
-- Dynamic file scanning using main.lua helper - finds ALL .lua files in Paketti tool
local function get_all_paketti_files()
-- Use the global helper function from main.lua for consistent file discovery
local files = PakettiGetAllLuaFiles()
-- If the helper function returns nothing, fall back to hardcoded list
if #files == 0 then
print("PakettiAutocomplete: Helper function returned no files, using fallback list")
files = {
"Paketti0G01_Loader", "PakettieSpeak", "PakettiPlayerProSuite", "PakettiChordsPlus",
"PakettiLaunchApp", "PakettiSampleLoader", "PakettiCustomization", "PakettiDeviceChains",
"base64float", "PakettiLoadDevices", "PakettiSandbox", "PakettiTupletGenerator",
"PakettiLoadPlugins", "PakettiPatternSequencer", "PakettiPatternMatrix", "PakettiInstrumentBox",
"PakettiYTDLP", "PakettiStretch", "PakettiBeatDetect", "PakettiStacker", "PakettiRecorder",
"PakettiControls", "PakettiKeyBindings", "PakettiPhraseEditor", "PakettiOctaMEDSuite",
"PakettiWavetabler", "PakettiAudioProcessing", "PakettiPatternEditorCheatSheet", "PakettiThemeSelector",
"PakettiMidiPopulator", "PakettiImpulseTracker", "PakettiGater", "PakettiAutomation",
"PakettiUnisonGenerator", "PakettiMainMenuEntries", "PakettiMidi", "PakettiDynamicViews",
"PakettiEightOneTwenty", "PakettiExperimental_Verify", "PakettiLoaders", "PakettiPatternEditor",
"PakettiTkna", "PakettiRequests", "PakettiSamples", "Paketti35", "PakettiAutocomplete", "PakettiMenuConfig",
"Research/FormulaDeviceManual", "hotelsinus_stepseq/hotelsinus_stepseq", "Sononymph/AppMain"
}
end
print(string.format("PakettiAutocomplete: Using %d .lua files for scanning", #files))
return files
end
-- Function to scan preferences.xml for dynamic plugin/device loaders
local function scan_preferences_xml()
local prefs_path = renoise.tool().bundle_path .. "preferences.xml"
local file = io.open(prefs_path, "r")
if not file then
print("PakettiAutocomplete: preferences.xml not found")
return {}
end
local content = file:read("*all")
file:close()
local dynamic_commands = {}
local plugin_count = 0
local device_count = 0
-- Extract PakettiPluginLoaders
for plugin_block in content:gmatch("<PakettiPluginLoader.-</PakettiPluginLoader>") do
local path = plugin_block:match("<path>(.-)</path>")
local name = plugin_block:match("<name>(.-)</name>")
if path and name then
plugin_count = plugin_count + 1
table.insert(dynamic_commands, {
type = "Dynamic Plugin Loader",
name = "Load Plugin " .. name,
category = "Dynamic Plugin Loaders",
invoke = string.format("loadPlugin('%s')", path),
abbreviations = {"plugin", "load", name:lower()},
source_file = "preferences.xml"
})
end
end
-- Extract PakettiDeviceLoaders
for device_block in content:gmatch("<PakettiDeviceLoader.-</PakettiDeviceLoader>") do
local path = device_block:match("<path>(.-)</path>")
local name = device_block:match("<name>(.-)</name>")
local device_type = device_block:match("<device_type>(.-)</device_type>")
if path and name then
device_count = device_count + 1
local display_name = device_type and (name .. " (" .. device_type .. ")") or name
table.insert(dynamic_commands, {
type = "Dynamic Device Loader",
name = "Load Device " .. display_name,
category = "Dynamic Device Loaders",
invoke = string.format("pakettiLoadDevice('%s')", path),
abbreviations = {"device", "load", name:lower()},
source_file = "preferences.xml"
})
end
end
print(string.format("PakettiAutocomplete: Found %d dynamic plugin loaders, %d dynamic device loaders",
plugin_count, device_count))
return dynamic_commands
end
-- Function to scan Paketti files for real commands (now uses dynamic file discovery)
local function scan_paketti_commands()
paketti_commands = {}
-- Get ALL .lua files dynamically
local paketti_files = get_all_paketti_files()
-- Helper function to extract category from menu path
local function extract_category(menu_path)
-- Remove -- prefix first
local clean_path = menu_path:gsub("^%-%-%s*", "")
-- Extract category from menu paths like "Main Menu:Tools:Paketti:Sample:..." or "Mixer:Paketti:..."
local category = clean_path:match("Paketti:([^:]+):") or clean_path:match("([^:]+):Paketti") or clean_path:match("([^:]+)") or "General"
-- Clean up the category (remove any remaining -- or extra spaces)
category = category:gsub("^%-%-%s*", ""):gsub("^%s*", ""):gsub("%s*$", "")
return category
end
-- Helper function to generate abbreviations
local function generate_abbreviations(name)
local abbrevs = {}
-- Simple acronym (first letters)
local acronym = ""
for word in name:gmatch("%w+") do
acronym = acronym .. word:sub(1,1):upper()
end
if #acronym > 1 then
table.insert(abbrevs, acronym)
end
-- Number extraction (like "+36", "-12")
for number in name:gmatch("[+-]%d+") do
table.insert(abbrevs, number)
end
-- Key words
for word in name:gmatch("%w+") do
if #word > 3 then -- Only meaningful words
table.insert(abbrevs, word:lower())
end
end
return abbrevs
end
local files_scanned = 0
local files_with_commands = 0
-- Scan each Paketti file
for _, filename in ipairs(paketti_files) do
local full_path = renoise.tool().bundle_path .. filename .. ".lua"
local file = io.open(full_path, "r")
if file then
files_scanned = files_scanned + 1
local content = file:read("*all")
file:close()
local commands_in_file = 0
-- Extract menu entries (use same pattern as PakettiActionSelector)
for entry, invoke_func in content:gmatch('add_menu_entry%s*{%s*name%s*=%s*"([^"]+)"%s*,%s*invoke%s*=%s*([^}]-)}') do
local clean_name = entry:gsub("^%-%-%s*", "")
local category = extract_category(entry)
local abbreviations = generate_abbreviations(clean_name)
local cleaned_invoke = invoke_func:match("^%s*(.-)%s*$")
table.insert(paketti_commands, {
type = "Menu Entry",
name = clean_name,
category = category,
invoke = cleaned_invoke,
abbreviations = abbreviations,
source_file = filename
})
commands_in_file = commands_in_file + 1
end
-- Extract keybindings
for binding, invoke_func in content:gmatch('add_keybinding%s*{%s*name%s*=%s*"([^"]+)"%s*,%s*invoke%s*=%s*([^}]-)}') do
local clean_name = binding:gsub("^%-%-%s*", "")
local category = extract_category(binding)
local abbreviations = generate_abbreviations(clean_name)
table.insert(paketti_commands, {
type = "Keybinding",
name = clean_name,
category = category,
invoke = invoke_func:match("^%s*(.-)%s*$"),
abbreviations = abbreviations,
source_file = filename
})
commands_in_file = commands_in_file + 1
end
-- Extract MIDI mappings too
for mapping, invoke_func in content:gmatch('add_midi_mapping%s*{%s*name%s*=%s*"([^"]+)"%s*,%s*invoke%s*=%s*([^}]-)}') do
local clean_name = mapping:gsub("^%-%-%s*", "")
local category = extract_category(mapping)
local abbreviations = generate_abbreviations(clean_name)
table.insert(paketti_commands, {
type = "MIDI Mapping",
name = clean_name,
category = category,
invoke = invoke_func:match("^%s*(.-)%s*$"),
abbreviations = abbreviations,
source_file = filename
})
commands_in_file = commands_in_file + 1
end
if commands_in_file > 0 then
files_with_commands = files_with_commands + 1
end
else
print("PakettiAutocomplete: Could not open file: " .. full_path)
end
end
-- Sort commands: Menu Entries first, then Keybindings, then MIDI, alphabetically within each type
table.sort(paketti_commands, function(a,b)
if a.type ~= b.type then
if a.type == "Menu Entry" then return true end
if b.type == "Menu Entry" then return false end
if a.type == "Keybinding" then return true end
if b.type == "Keybinding" then return false end
return a.type < b.type
else
return a.name < b.name
end
end)
-- Add dynamic commands from preferences.xml
local dynamic_commands = scan_preferences_xml()
for _, command in ipairs(dynamic_commands) do
table.insert(paketti_commands, command)
end
-- Set scan timestamp
last_scan_time = os.time()
print(string.format("PakettiAutocomplete: Scanned %d files (%d with commands), loaded %d Lua commands + %d dynamic commands = %d total",
files_scanned, files_with_commands, #paketti_commands - #dynamic_commands, #dynamic_commands, #paketti_commands))
end
-- Forward declarations for functions used before they're defined
local update_suggestions
local calculate_command_score
local get_smart_ordered_commands
local is_context_relevant
local score_flip_and_reverse
local update_scrollbar
local ensure_selection_visible
-- Helper function to get display category (show [MIDI] for MIDI mappings)
local function get_display_category(command)
if command.type == "MIDI Mapping" then
return "MIDI"
else
return command.category
end
end
-- Helper function to escape special pattern characters for safe pattern matching
local function escape_pattern(str)
return str:gsub("([%(%)%.%+%-%*%?%[%]%^%$%%])", "%%%1")
end
-- Helper function to clean up redundant category prefixes from command names
local function get_clean_command_name(command)
local name = command.name
local category = command.category
-- Remove "Main Menu:Tools:Paketti:" prefix first
local cleaned_name = name:gsub("^Main Menu:Tools:Paketti:", "")
-- Remove redundant category prefix (e.g., "Sample Editor:Paketti Gadgets:..." -> "Paketti Gadgets:...")
local pattern = "^" .. category:gsub("([%(%)%.%+%-%*%?%[%]%^%$%%])", "%%%1") .. ":(.+)$"
local cleaned = cleaned_name:match(pattern)
if cleaned then
return cleaned
else
return cleaned_name -- Return name with Main Menu prefix removed
end
end
-- Helper function to extract just the dialog name from gadget commands
local function get_gadget_dialog_name(command)
local name = command.name
-- Look for "Paketti Gadgets:" anywhere in the command name and extract what comes after
local gadget_name = name:match("Paketti Gadgets:(.+)$")
if gadget_name then
return gadget_name
end
-- Fallback to cleaned name if no gadgets pattern found
return get_clean_command_name(command)
end
-- Helper function to check if current search is gadgets-related
local function is_gadgets_search()
local search_lower = current_search_text:lower()
return search_lower:find("gadget") or search_lower:find("gad") or search_lower == "g"
end
-- Helper function to detect and fix doubled first letters (e.g., "eexpose" -> "expose")
local function detect_doubled_first_letter(text)
if not text or #text < 2 then
return nil
end
-- Check if first two characters are the same letter
local first_char = text:sub(1, 1):lower()
local second_char = text:sub(2, 2):lower()
if first_char == second_char and first_char:match("[a-z]") then
-- Return the corrected version without the doubled first letter
return text:sub(2)
end
return nil
end
-- Helper function to remove one instance of doubled substring from text
-- Returns the corrected text if a doubling is found, nil otherwise
local function remove_one_doubling(text)
if not text or #text < 2 then
return nil
end
-- Check for repeated substrings of length 1, 2, and 3 (prioritize longer matches)
for substring_length = 3, 1, -1 do
if #text >= substring_length * 2 then
for i = 1, #text - (substring_length * 2) + 1 do
local substring = text:sub(i, i + substring_length - 1)
local next_substring = text:sub(i + substring_length, i + (substring_length * 2) - 1)
-- Check if the substring is repeated immediately after itself
if substring == next_substring and substring:match("^[a-z]+$") then
-- Remove the duplicated substring and return
return text:sub(1, i - 1) .. text:sub(i + substring_length)
end
end
end
end
return nil
end
-- New function to detect and fix any doubled characters or substrings in text
-- Returns a table of all possible corrections (handles multiple typos in one word)
-- Handles both single char repetition (pparameter) and substring repetition (paparameter)
-- Can fix multiple typos: "paparameteter" -> "parameter" (fixes both "papa" and "tete")
local function detect_any_doubled_chars(text)
if not text or #text < 2 then
return {}
end
local variants = {}
local text_lower = text:lower()
local seen = {}
-- Keep removing doublings until we can't find any more
local current = text_lower
local max_iterations = 10 -- Safety limit to prevent infinite loops
local iteration = 0
while iteration < max_iterations do
local corrected = remove_one_doubling(current)
if corrected and corrected ~= current then
if not seen[corrected] then
seen[corrected] = true
table.insert(variants, corrected)
end
current = corrected
iteration = iteration + 1
else
break
end
end
return variants
end
-- Test function for doubled letter detection (can be called from console for testing)
function test_doubled_letter_detection()
local test_cases = {
{"eexpose", "expose"},
{"ssample", "sample"},
{"ttranspose", "transpose"},
{"expose", nil}, -- no doubled letter
{"12", nil}, -- numbers
{"e", nil}, -- too short
{"", nil} -- empty
}
print("Testing doubled letter detection:")
for _, case in ipairs(test_cases) do
local input, expected = case[1], case[2]
local result = detect_doubled_first_letter(input)
local status = (result == expected) and "PASS" or "FAIL"
print(string.format(" %s: '%s' -> %s (expected %s)", status, input, tostring(result), tostring(expected)))
end
print("\nTesting any doubled chars detection:")
local test_cases_any = {
{"paparameter", "parameter"}, -- "pa" is doubled
{"pparameter", "parameter"}, -- "p" is doubled
{"eexpose", "expose"}, -- "e" is doubled
{"paraameter", "parameter"}, -- "a" is doubled
{"parammeter", "parameter"}, -- "m" is doubled
{"parparameter", "parameter"}, -- "par" is doubled
{"paparameteter", "parameter"}, -- multiple typos: "pa" and "te" doubled
{"pparammeteter", "parameter"}, -- multiple typos: "p", "m", "te" doubled
{"parameter", ""}, -- no doubled chars
}
for _, case in ipairs(test_cases_any) do
local input, expected = case[1], case[2]
local results = detect_any_doubled_chars(input)
-- Get the final result (last in the list, which is most corrected)
local result_str = #results > 0 and results[#results] or ""
local status = (result_str == expected) and "PASS" or "FAIL"
print(string.format(" %s: '%s' -> '%s' (expected '%s')",
status,
input,
result_str,
expected))
if #results > 1 then
print(string.format(" intermediate steps: [%s]", table.concat(results, " -> ")))
end
end
end
-- CP-style: No autocomplete fill, just real-time filtering
-- Smart command grouping and numeric pattern detection
local function detect_numeric_pattern(search_text)
-- Detect patterns like "+36", "-12", "36", etc.
local sign, number = search_text:match("^([%+%-]?)(%d+)$")
if number then
local num = tonumber(number)
if num then
-- Return both original search and related patterns, but mark the original
local result = {
original = search_text,
related = {}
}
-- Generate related numbers (common transpose values)
local values = {12, 24, 36, 48}
for _, val in ipairs(values) do
if val ~= num then -- Don't duplicate the original number
table.insert(result.related, "+" .. val)
table.insert(result.related, "-" .. val)
if sign == "" then -- If original had no sign, include unsigned version
table.insert(result.related, tostring(val))
end
end
end
return result
end
end
return nil
end
-- Group similar commands by base function name with context-aware representative selection
local function group_similar_commands(commands)
local groups = {}
local group_representatives = {} -- Store best representative for each group
for _, command in ipairs(commands) do
-- Extract base pattern (remove numeric values and category prefixes)
local base_name = command.name
-- Remove category prefixes like "Global:Paketti:", "Sample Navigator:Paketti:", etc.
base_name = base_name:gsub("^[^:]+:Paketti:", "")
-- Replace numeric patterns with placeholder
base_name = base_name:gsub("[%+%-]?%d+", "X")
if not groups[base_name] then
groups[base_name] = {}
group_representatives[base_name] = command -- First command becomes representative
else
-- Smart representative selection: prefer context-relevant, then Global
local current_rep = group_representatives[base_name]
local should_replace = false
-- Priority 1: Context-relevant commands first
local command_context_relevant = is_context_relevant(command)
local current_context_relevant = is_context_relevant(current_rep)
if command_context_relevant and not current_context_relevant then
should_replace = true
print("Replacing with context-relevant command: " .. command.name .. " over " .. current_rep.name)
elseif not command_context_relevant and current_context_relevant then
should_replace = false -- Keep context-relevant
else
-- Priority 2: If both have same context relevance, prefer Global (works everywhere)
if command.category == "Global" and current_rep.category ~= "Global" then
should_replace = true
print("Replacing with Global command: " .. command.name .. " over " .. current_rep.name)
elseif command.category ~= "Global" and current_rep.category == "Global" then
should_replace = false -- Keep Global
else
-- Priority 3: Sample Editor in sample contexts (if both are equivalent)
if current_context:find("sample") then
if command.category:lower():find("sample editor") and not current_rep.category:lower():find("sample editor") then
should_replace = true
end
end
end
end
if should_replace then
group_representatives[base_name] = command
print("Updated representative for '" .. base_name .. "' from [" .. current_rep.category .. "] to [" .. command.category .. "] (context: " .. current_context .. ")")
end
end
table.insert(groups[base_name], command)
end
return groups, group_representatives
end
-- "Flip it And Reverse It" scoring for numeric patterns (category-consistent)
function score_flip_and_reverse(command, numeric_info, exact_match_command, template_variants)
local score = 0
-- MASSIVE bonus for the exact match command
if exact_match_command and command.name == exact_match_command.name then
score = score + 10000 -- Highest priority for exact match
-- print("Exact match bonus: " .. command.name .. " [" .. command.category .. "]")
return score
end
-- LARGE bonus for template variants (same category as exact match)
for _, variant in ipairs(template_variants) do
if command.name == variant.name then
score = score + 8000 -- Very high priority for template variants
-- print("Template variant bonus: " .. command.name .. " [" .. command.category .. "]")
return score
end
end
-- Standard bonus for other numeric matches
local name_lower = command.name:lower()
for _, pattern in ipairs(numeric_info.related) do
if string.find(name_lower, pattern:lower(), 1, true) then
score = score + 500 -- Lower score for other numeric matches
break
end
end
return score
end
-- Optimized filtering with smart ranking, context awareness, and intelligent grouping
local function filter_commands(filter_text)
print("filter_commands called with: '" .. (filter_text or "nil") .. "', context: " .. current_context)
if not filter_text or filter_text == "" then
-- Return context-filtered commands when no filter (not all commands)
local result = get_smart_ordered_commands()
print("Empty filter - returning " .. #result .. " context commands")
return result
end
-- Get the base set of commands to search from
local base_commands = paketti_commands -- Always search all commands when typing
local filtered = {}
local filter_lower = string.lower(filter_text)
local search_terms = {}
-- Check for numeric pattern and expand search if found
local numeric_info = detect_numeric_pattern(filter_text)
if numeric_info then
print("Detected numeric pattern for '" .. filter_text .. "', original: " .. numeric_info.original .. ", related: " .. table.concat(numeric_info.related, ", "))
-- Start with original search term, then add related patterns
search_terms = {numeric_info.original}
for _, related in ipairs(numeric_info.related) do
table.insert(search_terms, related)
end
else
-- Split filter text into multiple terms for AND searching
for term in filter_lower:gmatch("%S+") do
table.insert(search_terms, term)
end
end
-- Use search index for faster lookups, but only within base_commands
local candidate_indices = {}
if numeric_info then
-- For numeric patterns, use OR logic to find all related transpose commands
for _, term in ipairs(search_terms) do
for i, command in ipairs(base_commands) do
local name_lower = string.lower(command.name)
local category_lower = string.lower(command.category)
-- Direct name/category match
if string.find(name_lower, term, 1, true) or string.find(category_lower, term, 1, true) then
candidate_indices[i] = true
else
-- Try corrected version if original doesn't match (for doubled first letters)
local corrected_term = detect_doubled_first_letter(term)
if corrected_term then
if string.find(name_lower, corrected_term, 1, true) or string.find(category_lower, corrected_term, 1, true) then
candidate_indices[i] = true
end
end
-- Try variants with any doubled characters removed
if not candidate_indices[i] then
local variants = detect_any_doubled_chars(term)
for _, variant in ipairs(variants) do
if string.find(name_lower, variant, 1, true) or string.find(category_lower, variant, 1, true) then
candidate_indices[i] = true
break
end
end
end
end
-- Abbreviation match
for _, abbrev in ipairs(command.abbreviations) do
if string.find(abbrev:lower(), term, 1, true) then
candidate_indices[i] = true
break
else
-- Try corrected version for abbreviations too
local corrected_term = detect_doubled_first_letter(term)
if corrected_term and string.find(abbrev:lower(), corrected_term, 1, true) then
candidate_indices[i] = true
break
end
-- Try variants with any doubled characters removed
local variants = detect_any_doubled_chars(term)
for _, variant in ipairs(variants) do
if string.find(abbrev:lower(), variant, 1, true) then
candidate_indices[i] = true
break
end
end
end
end
end