forked from gusano/completion-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompletion-plugin.tcl
1554 lines (1392 loc) · 68.2 KB
/
completion-plugin.tcl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2011 yvan volochine <yvan.volochine@gmail.com>
#
# This file is part of completion-plugin.
#
# completion-plugin 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
# META NAME completion plugin
# META DESCRIPTION enables completion for objects
# META AUTHOR <Yvan Volochine> yvan.volochine@gmail.com
# META VERSION 0.42
# TODO
# - add user arguments (tabread $1 ...)
# ==========================================
# The original version was developed by Yvan Volochine a long time ago (as the time of writing: 7 years ago)
# I then embraced the project and i'm willing to mantain it for as long as i can.
# Right now i'm kind of new to .tcl so i'm trying to stay true to the original code.
# When reasonable i will comment talking about changes i did and why.
#
# https://github.com/HenriAugusto/completion-plugin
#
# Henri Augusto
package require Tcl 8.5
package require pd_menucommands 0.1
namespace eval ::completion:: {
variable ::completion::config
variable external_filetype ""
}
###########################################################
# overwritten
rename pdtk_text_editing pdtk_text_editing_old
############################################################
# GLOBALS
set ::completion::plugin_version "0.47.1"
# default
set ::completion::config(save_mode) 1 ;# save keywords (s/r/array/table/...)
set ::completion::config(max_lines) 20
set ::completion::config(font) "DejaVu Sans Mono"
set ::completion::config(font_size) 8 ;# should load pd's default
set ::completion::config(bg) "#0a85fe"
set ::completion::config(skipbg) "#0ad871"
set ::completion::config(monobg) "#9832ff"
set ::completion::config(fg) white
set ::completion::config(offset) 0
set ::completion::config(max_scan_depth) 1
set ::completion::config(auto_complete_libs) 1
# some nice colors to try: #0a85fe #0ad871 #9832ff ; those are great: #ff9831 #ff00ee #012345
# private variables
set ::completion_plugin_path ""
set ::toplevel ""
set ::current_canvas ""
set ::current_tag ""
set ::current_text ""
set ::erase_text ""
set ::completions {"(empty)"}
set ::new_object false
set ::editx 0
set ::edity 0
set ::focus ""
set ::completion_text_updated 0
set ::is_shift_down 0
set ::is_ctrl_down 0
set ::is_alt_down 0
set ::waiting_trigger_keyrelease 0
# =========== [DEBUG mode on/off] ============
#1 = true 0 = false
set ::completion_debug 0 ;
# debug categories
set ::debug_loaded_externals 0 ;#prints loaded externals
set ::debug_entering_procs 1 ;#prints a message when entering a proc
set ::debug_key_event 0 ;#prints a message when a key event is processed
set ::debug_searches 0 ;#messages about the performed searches
set ::debug_popup_gui 0 ;#messages related to the popup containing the code suggestions
set ::debug_char_manipulation 0 ;#messages related to what we are doing with the text on the obj boxes (inserting/deleting chars)
set ::debug_unique_names 0 ;#messages related to storing [send/receive] names [tabread] names and alike.
set ::debug_settings 1 ;#messages related to storing [send/receive] names [tabread] names and alike.
set ::debug_prefix 0 ;#messages related to storing [send/receive] names [tabread] names and alike.
#0 = normal
#1 = skipping
#2 = monolithic
set ::current_search_mode 0
# all pd VANILLA objects
set ::all_externals {}
set ::monolithic_externals {}
set ::loaded_libs {}
#useful function for debugging
proc ::completion::debug_msg {dbgMsg {debugKey "none"}} {
switch -- $debugKey {
"none" {}
"loaded_externals" { if { !$::debug_loaded_externals } { return } }
"entering_procs" { if { !$::debug_entering_procs } { return } }
"key_event" { if { !$::debug_key_event } { return } }
"searches" { if { !$::debug_searches } { return } }
"popup_gui" { if { !$::debug_popup_gui } { return } }
"char_manipulation" { if { !$::debug_char_manipulation } { return } }
"unique_names" { if { !$::debug_unique_names } { return } }
"settings" { if { !$::debug_settings } { return } }
"prefix" { if { !$::debug_prefix } { return } }
}
if { $::completion_debug } {
::pdwindow::post "autocmpl_dbg: $dbgMsg\n"
}
}
# This function sends keydown messages to pd
# It is better to use a separate function instead of hardcoded pdsend messages like Yvan was doing because the pd tcl api might change.
# In fact when i took the project that was one of the major bugs with it. It was using pdsend "pd key 1 $keynum 0" which where not working.
# So using functions (procs) promotes mantainability because you only have to change their implementation to fix the code after api changes.
proc ::completion::sendKeyDown {keynum} {
pdsend "[winfo toplevel $::current_canvas] key 1 $keynum 0"
}
# This function sends keydown and then keyup messages to pd
proc ::completion::sendKeyDownAndUp {keynum} {
pdsend "[winfo toplevel $::current_canvas] key 1 $keynum 0"
pdsend "[winfo toplevel $::current_canvas] key 0 $keynum 0"
}
#called once upon plugin initialization
proc ::completion::init {} {
variable external_filetype
set ::completion_plugin_path "$::current_plugin_loadpath"
::pdwindow::post "\[completion-plugin\] version $::completion::plugin_version\n"
::completion::read_config
#::completion::read_extras
switch -- $::windowingsystem {
"aqua" { set external_filetype *.pd_darwin }
"win32" { set external_filetype *.dll}
"x11" { set external_filetype *.pd_linux }
}
if {[catch {bind "completion-plugin" <$completion::config(hotkey)> {::completion::trigger; break;}} err]} {
::pdwindow::post "\n---Error while trying to bind the completion plugin hotkey---\n"
::pdwindow::post " hotkey: $::completion::config(hotkey)\n"
::pdwindow::post " err: $err\n\n"
}
::completion::scan_all_completions
::completion::init_options_menu
}
proc ::completion::scan_all_completions {} {
set initTime [clock milliseconds]
set ::all_externals {hslider vslider bng cnv bang float symbol int send receive select route pack unpack trigger spigot moses until print makefilename change swap value list {list append} {list fromsybmol} {list length} {list prepend} {list split} {list store} {list tosymbol} {list trim} delay metro line timer cputime realtime \
pipe + - * / pow == != > < >= <= & && | || % << >> mtof powtodb rmstodb ftom dbtopow dbtorms mod div sin cos tan atan atan2 sqrt log exp abs random max min clip wrap notein ctlin pgmin bendin touchin polytouchin midiin sysexin midirealtimein midiclkin noteout ctlout pgmout bendout touchout polytouchout midiout makenote stripnote \
oscparse oscformat tabread tabread4 tabwrite soundfiler table array loadbang netsend netreceive glist textfile text openpanel savepanel bag poly key keyup keyname declare +~ -~ *~ /~ max~ min~ clip~ sqrt~ rsqrt~ q8_sqrt~ q8_rsqrt~ wrap~ fft~ ifft~ rfft~ rifft~ pow~ log~ exp~ abs~ framp~ mtof~ ftom~ rmstodb~ dbtorms~ dac~ adc~ sig~ line~ vline~ \
threshdold~ snapshot~ vsnapshot~ bang~ samplerate~ send~ receive~ throw~ catch~ block~ switch~ readsf~ writesf~ phasor~ cos~ osc~ tabwrite~ tabplay~ tabread~ tabread4~ tabosc4~ tabsend~ tabreceive~ vcf~ noise~ env~ hip~ lop~ bp~ biquad~ samphold~ print~ rpole~ rzero~ rzero_rev~ cpole~ czero~ czero_rev~ delwrite~ delread~ delread4~ vd~ inlet outlet inlet~ outlet~ clone \
struct drawcurve filledcurve drawpolygon filledpolygon plot drawnumber drawsymbol pointer get set element getsize setsize append scalar sigmund~ bonk~ choice hilbert~ complet-mod~ expr expr~ fexpr~ loop~ lrshift~ pd~ stdout~ rev1~ rev2~ rev3~ bob~ namecanvas savestate pdcontrol slop~}
set ::monolithic_externals {}
::completion::add_user_externals
::completion::add_user_customcompletions
::completion::add_user_monolithiclist
set ::loaded_libs {} ;#clear the loaded_libs because it was only used to scan the right objects located in multi-object distributions
set ::all_externals [lsort $::all_externals]
::completion::add_special_messages ;#AFTER sorting
set finalTime [clock milliseconds]
set delta [expr {$finalTime-$initTime}]
set count [llength $::all_externals]
set count [expr {$count+[llength $::monolithic_externals]}]
::pdwindow::post "\[completion-plugin\] loaded $count completions in $delta milliseconds\n"
}
proc ::completion::init_options_menu {} {
if {$::windowingsystem eq "aqua"} {
set mymenu .menubar.apple.preferences
} else {
set mymenu .menubar.file.preferences
}
if { [catch {
$mymenu entryconfigure [_ "Auto Complete settings"] -command {::completion::show_options_gui}
} _ ] } {
$mymenu add separator
$mymenu add command -label [_ "Auto Complete settings"] -command {::completion::show_options_gui}
}
}
#opens the plugin's help file (as called from the configuration window)
proc ::completion::open_help_file {} {
set filename [file join $::completion_plugin_path "README.pd"]
open_file "$filename"
}
proc ::completion::show_options_gui {} {
if {[winfo exists .options]} {
focus .options
return
}
toplevel .options
wm title .options "Pd AutoComplete Settings"
frame .options.f -padx 5 -pady 5
label .options.f.title_label -text "PD AutoComplete Settings"
.options.f.title_label configure -font [list $::completion::config(font) [expr {$::completion::config(font_size)+3}]]
label .options.f.status_label -text "" -foreground "#cc2222"
# COLORS
#note that we are using KeyRelease bindings because using "-validate key" would not validate in the right time.
#ex: you would type a valid string #aabbcc and it would be invalid. Then on the next keypress (whichever it was) it would process #aabbcc
#Options for background color
label .options.f.click_to_choose_label -text "click to\nchoose"
label .options.f.bg_label -text "bkg color"
entry .options.f.bg_entry -width 8
frame .options.f.bg_demo -background $::completion::config(bg) -width 40 -height 40
bind .options.f.bg_demo <ButtonRelease> { ::completion::user_select_color "bg"}
bind .options.f.bg_entry <KeyRelease> { ::completion::gui_options_update_color ".options.f.bg_entry" ".options.f.bg_demo" "bg" }
#Options for skipping mode background color
label .options.f.skip_bg_label -text "skipping bkg color"
entry .options.f.skip_bg_entry -width 8
frame .options.f.skip_bg_demo -background $::completion::config(skipbg) -width 40 -height 40
bind .options.f.skip_bg_demo <ButtonRelease> { ::completion::user_select_color "skipbg"}
bind .options.f.skip_bg_entry <KeyRelease> { ::completion::gui_options_update_color ".options.f.skip_bg_entry" ".options.f.skip_bg_demo" "skipbg" }
#Options for monolithic mode background color
label .options.f.mono_bg_label -text "mono-object bkg color"
entry .options.f.mono_bg_entry -width 8
frame .options.f.mono_bg_demo -background $::completion::config(monobg) -width 40 -height 40
bind .options.f.mono_bg_demo <ButtonRelease> { ::completion::user_select_color "monobg"}
bind .options.f.mono_bg_entry <KeyRelease> { ::completion::gui_options_update_color ".options.f.mono_bg_entry" ".options.f.mono_bg_demo" "monobg" }
#Misc
checkbutton .options.f.auto_complete_libs -variable ::completion::config(auto_complete_libs) -onvalue 1 -offvalue 0
label .options.f.auto_complete_libs_label -text "auto complete library names"
spinbox .options.f.number_of_lines -width 6 -from 3 -to 30 -textvariable ::completion::config(max_lines)
label .options.f.number_of_lines_label -text "number of lines to display"
spinbox .options.f.maximum_scan_depth -width 6 -from 0 -to 10 -textvariable ::completion::config(max_scan_depth)
label .options.f.maximum_scan_depth_label -text "maximum scan depth"
spinbox .options.f.font_size -width 6 -from 7 -to 20 -textvariable ::completion::config(font_size)
label .options.f.font_size_label -text "font size"
#Hotkey
label .options.f.hotkeylabel -text "hotkey (require save&restart)"
entry .options.f.hotkeyentry -width 22
.options.f.hotkeyentry insert 0 "$::completion::config(hotkey)"
bind .options.f.hotkeyentry <KeyRelease> {
set ::completion::config(hotkey) [.options.f.hotkeyentry get]
}
#Buttons
button .options.f.save_btn -text "save to file" -command ::completion::write_config
button .options.f.default_btn -text "default" -command ::completion::restore_default_option
button .options.f.rescan_btn -text "rescan" -command ::completion::scan_all_completions
button .options.f.help_btn -text "help" -command ::completion::open_help_file
#.options.f.help_btn configure -font {-family courier -size 12 -weight bold -slant italic}
.options.f.help_btn configure -font {-weight bold}
set padding 2
# ::::GRID::::
#setup main frame stuff
grid .options.f -column 0 -row 0
grid .options.f.title_label -column 0 -row 0 -columnspan 3 -padx $padding -pady $padding
#setup the rest
set current_row 1
#auto complete libs
grid .options.f.auto_complete_libs_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.auto_complete_libs -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
incr current_row
#number of lines
grid .options.f.number_of_lines_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.number_of_lines -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
incr current_row
#font size
grid .options.f.font_size_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.font_size -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
incr current_row
#maximum scan depth
grid .options.f.maximum_scan_depth_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.maximum_scan_depth -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
grid .options.f.click_to_choose_label -column 2 -row $current_row -padx $padding -pady $padding
incr current_row
# change background color
grid .options.f.bg_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.bg_entry -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
grid .options.f.bg_demo -column 2 -row $current_row -padx $padding -pady $padding
incr current_row
# change skip mode background color
grid .options.f.skip_bg_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.skip_bg_entry -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
grid .options.f.skip_bg_demo -column 2 -row $current_row -padx $padding -pady $padding
incr current_row
# change mono mode background color
grid .options.f.mono_bg_label -column 0 -row $current_row -padx $padding -pady $padding -sticky "e"
grid .options.f.mono_bg_entry -column 1 -row $current_row -padx $padding -pady $padding -sticky "w"
grid .options.f.mono_bg_demo -column 2 -row $current_row -padx $padding -pady $padding
incr current_row
#hotkey stuff
grid .options.f.hotkeylabel -column 0 -row $current_row -padx $padding -pady $padding
grid .options.f.hotkeyentry -column 1 -row $current_row -padx $padding -pady $padding
incr current_row
# Status labels and buttons
#Is the status label used?
#grid .options.f.status_label -column 0 -row $current_row -padx $padding -pady 8 -sticky "e"
grid .options.f.default_btn -column 1 -row $current_row -padx $padding -pady 8 -sticky "e"
grid .options.f.save_btn -column 2 -row $current_row -padx $padding -pady 8 -sticky "w"
grid .options.f.help_btn -column 0 -row $current_row -padx $padding -pady 8 -sticky "w"
incr current_row
grid .options.f.rescan_btn -column 2 -row $current_row -padx $padding -pady 4 -sticky "ew"
::completion::update_options_gui
}
proc ::completion::update_options_gui {} {
.options.f.status_label configure -text ""
.options.f.bg_demo configure -background $::completion::config(bg)
.options.f.skip_bg_demo configure -background $::completion::config(skipbg)
.options.f.mono_bg_demo configure -background $::completion::config(monobg)
.options.f.bg_entry delete 0 end
.options.f.bg_entry insert 0 $::completion::config(bg)
.options.f.skip_bg_entry delete 0 end
.options.f.skip_bg_entry insert 0 $::completion::config(skipbg)
.options.f.mono_bg_entry delete 0 end
.options.f.mono_bg_entry insert 0 $::completion::config(monobg)
.options.f.hotkeyentry delete 0 end
.options.f.hotkeyentry insert 0 $::completion::config(hotkey)
}
proc ::completion::restore_default_option {} {
set ::completion::config(hotkey) "Control-space"
set ::completion::config(max_lines) 20
set ::completion::config(font) "DejaVu Sans Mono"
set ::completion::config(font_size) 8
set ::completion::config(bg) "#0a85fe"
set ::completion::config(skipbg) "#0ad871"
set ::completion::config(monobg) "#9832ff"
set ::completion::config(fg) white
set ::completion::config(offset) 0
set ::completion::config(max_scan_depth) 1
set ::completion::config(auto_complete_libs) 1
::completion::update_options_gui
}
proc ::completion::gui_options_update_color {entryWidget frameWidget configTag} {
if { [regexp {^\#(\d|[a-f]){6}$} [$entryWidget get]] } {
set ::completion::config($configTag) [$entryWidget get]
$frameWidget configure -background $::completion::config($configTag)
# chagne color to show it's valid
$entryWidget configure -foreground #000000
} else {
# chagne color to show it's INvalid
$entryWidget configure -foreground #de2233
}
}
# taken from kiosk-plugin.tcl by Iohannes
proc ::completion::read_config {{filename completion.cfg}} {
if {[file exists $filename]} {
set fp [open $filename r]
} else {
set filename [file join $::completion_plugin_path $filename]
if {[file exists $filename]} {
set fp [open $filename r]
} else {
::completion::debug_msg "completion.cfg not found"
return False
}
}
while {![eof $fp]} {
set data [gets $fp]
if { ![regexp {^\w} $data] } {
continue ;#this line doesn't start with a char
}
# if the user provided the key value pair
::completion::debug_msg "data length = [llength $data]" "settings"
if { [llength $data ] == 2} {
set ::completion::config([lindex $data 0]) [lindex $data 1]
::completion::debug_msg "::completion::config([lindex $data 0]) = $::completion::config([lindex $data 0])" "settings"
} elseif { [llength $data ] > 2} {
set ::completion::config([lindex $data 0]) [lrange $data 1 end]
::completion::debug_msg "::completion::config([lindex $data 0]) = $::completion::config([lindex $data 0])" "settings"
} else {
::completion::debug_msg "ERROR reading ::completion::config([lindex $data 0]) => data = $data" "settings"
}
}
close $fp
return True
}
proc ::completion::write_config {{filename completion.cfg}} {
if { [file exists $filename] } {
set fp [open $filename r]
set had_to_create_file false
} else {
set filename [file join $::completion_plugin_path $filename]
if {[file exists $filename]} {
set fp [open $filename r]
set had_to_create_file false
} else {
set fp [open $filename w+]
set had_to_create_file true ;#file will get overwritten so we need to append to $lines
}
}
#read the lines from the file
set lines [split [read $fp] "\n"]
close $fp
#process the lines
set lines [::completion::write_config_variable $lines "hotkey"]
set lines [::completion::write_config_variable $lines "max_lines"]
set lines [::completion::write_config_variable $lines "font"]
set lines [::completion::write_config_variable $lines "font_size"]
set lines [::completion::write_config_variable $lines "max_scan_depth"]
set lines [::completion::write_config_variable $lines "auto_complete_libs"]
set lines [::completion::write_config_variable $lines "bg"]
set lines [::completion::write_config_variable $lines "fg"]
set lines [::completion::write_config_variable $lines "skipbg"]
set lines [::completion::write_config_variable $lines "monobg"]
set lines [::completion::write_config_variable $lines "offset"]
#write the file
set fp [open $filename w]
if { $had_to_create_file } {
set lines [linsert $lines 0 "This file was generated by PD AutoComplete in the absence of the original file that comes with the plugin.\n"]
}
puts $fp [join $lines "\n"]
close $fp
#.options.f.status_label configure -text "saved!"
#after 1000 { .options.f.status_label configure -text "" }
}
proc ::completion::write_config_variable {file_lines name} {
#https://stackoverflow.com/a/37812995/5818209 for writing to specific lines
::completion::debug_msg "Saving config($name)" "settings"
set pattern ^$name\\s ;# do NOT enclose this in brackets
::completion::debug_msg "pattern = $pattern" "settings"
set index 0
set found false
foreach line $file_lines {
#::completion::debug_msg "line = $line"
if {[regexp $pattern $line]} {
::completion::debug_msg "current variable's line = $line" "settings"
set file_lines [lreplace $file_lines $index $index "$name $::completion::config($name)"]
::completion::debug_msg "line AFTER = $line" "settings"
set found true
}
incr index
}
if { !$found } {
#if there is no line for that variable, write it
lappend file_lines "$name $::completion::config($name)"
}
return $file_lines
}
proc ::completion::user_select_color {target} {
set color [tk_chooseColor -title "AutoComplete settings: Choose a color" -initialcolor $::completion::config($target)]
if { $color eq ""} {
return
}
set ::completion::config($target) $color
::completion::update_options_gui
}
# this function looks for objects in the current folder and recursively call itself for each subfolder
# we read the subfolders because pd reads the subpatches!
proc ::completion::add_user_externalsOnFolder {{dir .} depth} {
variable external_filetype
if { [expr {$depth > $::completion::config(max_scan_depth)}] } {
return
}
#::completion::debug_msg "external_filetype = $external_filetype" ;#just for debugging
::completion::debug_msg "===add_user_externalsOnFolder $dir===" "loaded_externals"
::completion::debug_msg "depth = $depth" "loaded_externals"
# i concatenate the result of two globs because for some reason i can't use glob with two patterns. I've tried using: {$external_filetype,*.pd}
# list of pd files on the folder
set pd_files [glob -directory $dir -nocomplain -types {f} -- *.pd]
#List of system depentent (*.pd_darwin, *.dll, *.pd_linux) files on the folder
set sys_dependent_files [glob -directory $dir -nocomplain -types {f} -- $external_filetype]
set all_files [concat $pd_files $sys_dependent_files]
# for both types of files
foreach filepath $all_files {
::completion::debug_msg " external = $filepath" "loaded_externals"
set file_tail [file tail $filepath] ;#this one contains the file extension
set name_without_extension [file rootname $file_tail]
set dir_name [file dirname $filepath]
set how_many_folders_to_get [expr {$depth+0}]
set folder_name [lrange [file split $filepath] end-$how_many_folders_to_get end-1 ]
set extension_path [join $folder_name \/]
if {$extension_path ne ""} {
set extension_path $extension_path\/
}
::completion::debug_msg " depth = $depth" "loaded_externals"
::completion::debug_msg " filepath = $filepath" "loaded_externals"
::completion::debug_msg " dir_name = $dir_name" "loaded_externals"
::completion::debug_msg " folder_name = $folder_name" "loaded_externals"
::completion::debug_msg " extension_path = $extension_path" "loaded_externals"
::completion::debug_msg " file_tail = $file_tail" "loaded_externals"
::completion::debug_msg " name_without_extension = $name_without_extension" "loaded_externals"
if {[string range $name_without_extension end-4 end] ne "-help"} {
lappend ::all_externals $extension_path$name_without_extension
lappend ::loaded_libs $extension_path
}
}
#do the same for each subfolder (recursively)
set depth [expr {$depth+1}]
foreach subdir [glob -nocomplain -directory $dir -type d *] {
::completion::add_user_externalsOnFolder $subdir $depth
}
}
# this proc runs the main search ::completion::add_user_externalsOnFolder into each main folder
proc ::completion::add_user_externals {} {
::completion::debug_msg "-----searching externals on the following directories:-----" "loaded_externals"
foreach DIR $::sys_searchpath {
::completion::debug_msg "$DIR" "loaded_externals"
}
foreach DIR $::sys_staticpath {
::completion::debug_msg "static path $DIR" "loaded_externals"
}
#for each directory the user set in edit->preferences->path
set dynamic_and_static_paths [concat $::sys_searchpath $::sys_staticpath]
set pathlist $::sys_staticpath
set pathlist $dynamic_and_static_paths
foreach pathdir $pathlist {
set dir [file normalize $pathdir]
if { ! [file isdirectory $dir]} { ;#why Yvan was doing this check?
continue
}
::completion::add_user_externalsOnFolder $pathdir 0
#foreach subdir [glob -directory $dir -nocomplain -types {d} *] {
# ::completion::add_user_externalsOnFolder $subdir 1
#}
}
#remove duplicates from the loaded_libs
set ::loaded_libs [lsort -unique $::loaded_libs]
}
#adds any completion set in any txt file under "custom_completions"
proc ::completion::add_user_customcompletions {} {
::completion::debug_msg "entering add user object list" "entering_procs"
set userdir [file join $::completion_plugin_path "custom_completions"]
foreach filename [glob -directory $userdir -nocomplain -types {f} -- \
*.txt] {
::completion::read_completionslist_file $filename
}
}
#reads objects stored into monolithic files (*.pd_darwin, *.dll, *.pd_linux)
proc ::completion::add_user_monolithiclist {} {
::completion::debug_msg "entering add user monolithic list" "entering_procs"
::completion::debug_msg "::loaded_libs = $::loaded_libs" "loaded_externals"
set userdir [file join $::completion_plugin_path "monolithic_objects"]
# for each .txt file in /monolithic_objects
foreach filename [glob -directory $userdir -nocomplain -types {f} -- \
*.txt] {
# Slurp up the data file
set fp [open $filename r]
set file_data [read $fp]
foreach line $file_data {
# gets the lib name from the string
set lib [lindex [split $line /] 0]
set lib ${lib}/ ;# turns libName into libName/
# only if the user actually have that library installed
if { [expr [lsearch -nocase $::loaded_libs $lib] >= 0 ] } {
lappend ::monolithic_externals [split $line /]
}
}
close $fp
::completion::debug_msg "======monolithic externals=======\n$::monolithic_externals" "loaded_externals"
}
}
# Reads anything located in the .txt files in the subfolders
proc ::completion::read_completionslist_file {afile} {
if {[file exists $afile]
&& [file readable $afile]
} {
set fl [open $afile r]
while {[gets $fl line] >= 0} {
if {[string index $line 0] ne ";"
&& [string index $line 0] ne " "
&& [string index $line 0] ne ""
&& [lsearch -exact $::all_externals $line] == -1} {
lappend ::all_externals $line
}
}
close $fl
}
}
###########################################################
# overwritten #
###########################################################
proc pdtk_text_editing {mytoplevel tag editing} {
::completion::debug_msg "entering overwritten pdtk text editing" "entering_procs"
#::completion::debug_msg " mytoplevel = $mytoplevel"
#::completion::debug_msg " tag = $tag"
#::completion::debug_msg " editing = $editing"
set ::toplevel $mytoplevel
set tkcanvas [tkcanvas_name $mytoplevel]
set rectcoords [$tkcanvas bbox $tag]
if {$rectcoords ne ""} {
set ::editx [expr {int([lindex $rectcoords 0])}]
set ::edity [expr {int([lindex $rectcoords 3])}]
}
if {$editing == 0} {
selection clear $tkcanvas
# completion
# Henri: Yvan originally called set_empty_listbox. Doens't seem to make sense. It wouldn't even reset ::current_text
::completion::popup_destroy
set ::completion_text_updated 0
# store keywords. Henri: i'm disabling that. See developmentGuide.md
#if {$::completion::config(save_mode)} {
# set text [$tkcanvas itemcget $::current_tag -text]
# ::completion_store $text
#}
} {
set ::editingtext($mytoplevel) $editing
# completion
set ::current_canvas $tkcanvas
if {$tag ne ""} {
# unbind Keys if new object
if {$tag ne $::current_tag} {
bind $::current_canvas <KeyRelease> {}
}
set ::current_tag $tag
}
if {[string first "completion-plugin" [bindtags $::current_canvas] ] eq -1} {
bindtags $::current_canvas "completion-plugin [bindtags $::current_canvas]"
}
#delete_if {[string first [bindtags $::current_canvas] "test"] eq -1} {
#delete_ bindtags $::current_canvas "test [bindtags $::current_canvas]"
#delete_}
#delete_#bind $::current_canvas <$completion::config(hotkey)> {+::completion::trigger;break;}
#delete_::pdwindow::post "-----EDITING------\n"
#delete_::pdwindow::post "current_canvas: $::current_canvas\n"
#delete_set dbg [bindtags $::current_canvas]
#delete_::pdwindow::post "bindtags: $dbg\n"
}
set ::new_object $editing
$tkcanvas focus $tag
set ::focus "tag"
}
# this is called when the user enters the auto completion mode
proc ::completion::trigger {} {
::completion::debug_msg "===entering trigger===" "entering_procs"
set ::waiting_trigger_keyrelease 1
set ::is_shift_down 0
set ::is_ctrl_down 0
set ::is_alt_down 0
if {$::current_canvas ne ""
&& $::current_text eq ""
&& ! $::completion_text_updated
} {
#this code is responsible for reading any text already present in the object when you enter the autocomplete mode
set ::current_text [$::current_canvas itemcget $::current_tag -text]
::completion::trimspaces
::completion::debug_msg "Text that was already in the box = $::current_text\n" "searches"
}
::completion::debug_msg "-----TRIGGER------\n"
::completion::debug_msg "current_canvas: $::current_canvas\n"
set dbg [bindtags $::current_canvas]
::completion::debug_msg "bindtags: $dbg\n"
#if the user is typing into an object box
if {$::new_object} {
# detect if the user is typing on an object, message or comment
set ::tags_on_object_being_edited [$::current_canvas itemcget $::current_tag -tags]
::completion::debug_msg "\[$::current_canvas itemcget $::current_tag -tags\] = $::tags_on_object_being_edited"
set ::type_of_object_being_edited [lindex $::tags_on_object_being_edited 1]
::completion::debug_msg "------>::type_of_object_being_edited = $::type_of_object_being_edited \n"
if { ($::type_of_object_being_edited ne "obj") && ($::type_of_object_being_edited ne "msg") } {
::completion::debug_msg "the completion-plugin does not trigger for objects of type $::type_of_object_being_edited"
return
}
bind $::current_canvas <KeyRelease> {::completion::text_keys %K}
set completed_because_was_unique 0
if {![winfo exists .pop]} {
::completion::popup_draw
::completion::search $::current_text
::completion::try_common_prefix
::completion::update_completions_gui
if {[::completion::unique] } {
::completion::choose_selected ;#Henri: was replace_text. This is needed for the three modes
::completion::popup_destroy
::completion::set_empty_listbox
set completed_because_was_unique 1
}
} else {
if {[::completion::unique]} {
::completion::choose_selected
set completed_because_was_unique 1
} elseif { [llength $::completions] > 1 } {
if {![::completion::try_common_prefix]} {
::completion::debug_msg "IF not common prefix\n"
#::completion::increment ;#Henri: this would allow to cycle through the completions with Tab. I'm disabling that in favor of the arrow keys
} else {
::completion::debug_msg "IF INDEED common prefix\n"
}
}
}
# if the unique completion was used there will be no .pop to bind!
if { !$completed_because_was_unique } {
# work in progress
# bind .pop <FocusOut> {::completion::debug_msg "the user has unfocused the popup"; ::completion::popup_destroy }
# bind $::current_canvas <FocusOut> {::completion::debug_msg "the user has unfocused the canvas"}
}
} else {
::completion::debug_msg "the user is NOT typing into an object box" "key_event"
}
# this should be time enough for the user to release the keys (so we don't capture the release keys of the plugin hotkey)
after 200 {
::completion::debug_msg "accepting keys\n"
set ::waiting_trigger_keyrelease 0
}
}
proc ::completion::monolithic_search {{text ""}} {
#set variables related to monolithic_search
::completion::debug_msg "::completion::monolithic_search($text)" "searches"
set ::current_search_mode 2
if {[winfo exists .pop]} {
.pop.f.lb configure -selectbackground $::completion::config(monobg)
}
#do the search
set text [string range $text 1 end]
set results {}
::completion::debug_msg "::completion::monolithic_search($text)" "searches"
foreach elem $::monolithic_externals {
#those are stored into a {libName objName} fashion
set libraryName [lindex $elem 0]
set objName [lindex $elem 1]
::completion::debug_msg "::completion::monolithic_search\[$libraryName\/$objName\]" "searches"
lappend results "$libraryName\/$objName"
}
#::completion::debug_msg "----------results=\[$results"
set pattern "$text"
set pattern [::completion::fix_pattern $pattern]
set ::completions [lsearch -all -inline -regexp -nocase $results $pattern]
}
proc ::completion::skipping_search {{text ""}} {
#set variables related to skipping_search
::completion::debug_msg "::completion::skipping_search($text)" "searches"
set ::current_search_mode 1
# do we really need to check if the popup exists?
if {[winfo exists .pop]} {
.pop.f.lb configure -selectbackground $::completion::config(skipbg)
}
#do the search
set text [string range $text 1 end]
set text [::completion::fix_pattern $text]
set chars [split $text {}]
set pattern ""
foreach char $chars {
::completion::debug_msg "--------------char = $char"
set pattern "$pattern$char.*"
}
::completion::debug_msg "RegExp pattern = $pattern" "searches"
::completion::debug_msg "--------------chars = $chars" "searches"
set ::completions [lsearch -all -inline -regexp -nocase $::all_externals $pattern]
}
# Searches for matches.
# (this method detects the current search mode and returns after calling the right one it it happens to be monolithic or skipping.)
proc ::completion::search {{text ""}} {
::completion::debug_msg "::completion::search($text)" "searches"
::completion::debug_msg "::completion_text_updated = $::completion_text_updated" "searches"
# without the arg there are some bugs when keys come from listbox ;# what Yvan meant?
set ::erase_text $::current_text
#if starts with a . it is a skipping search
#if starts with a , it is a monolithic search
if {[string range $text 0 0] eq ","} {
::completion::monolithic_search $text
return
} elseif {[string range $text 0 0] eq "."} {
::completion::skipping_search $text
return
}
# Else just do the normal search
if {[winfo exists .pop.f.lb]} {
.pop.f.lb configure -selectbackground $::completion::config(bg)
}
set ::current_search_mode 0
if {$text ne ""} {
::completion::debug_msg "=searching for $text=" "searches"
set ::current_text $text
set ::erase_text $text
set ::should_restore False
} elseif { !$::completion_text_updated } {
::completion::debug_msg "searching for empty string" "searches"
#set ::current_text \
[$::current_canvas itemcget $::current_tag -text]
set ::previous_current_text $::current_text ;# saves the current text
::completion::debug_msg "original current_text: $::current_text" "searches"
set ::current_text ""
::completion::debug_msg "replaced current_text is $::current_text" "searches"
set ::should_restore True
}
::completion::trimspaces
# Now this part will always run so you can perform "empty searchs" which will return all objects. In Yvan's code it would clear completions on an "empty search"
#Yvan was using -glob patterns but they wouldn't match stuff with forward slashes (/)
#for example if you type "freq" it wouldn't match cyclone/freqshift~
#using -regexp now allows for that
#Also i've added case insensitive searching (since PD object creation IS case-insensitive).
set pattern "$::current_text"
set pattern [::completion::fix_pattern $pattern]
set ::completions [lsearch -all -inline -regexp -nocase $::all_externals $pattern]
if {$::should_restore} {
set ::current_text $::previous_current_text ;# restores the current text
::completion::debug_msg "restored current_text: $::current_text" "searches"
}
::completion::update_completions_gui
::completion::debug_msg "SEARCH END! Current text is $::current_text" "searches"
}
# This is a method that edits a string used as a regex pattern escaping chars in order to correcly compile the regexp;
# example: we must escape "++" to "\\+\\+".
proc ::completion::fix_pattern {pattern} {
::completion::debug_msg "================== - pattern = $pattern" "searches"
set pattern [string map {"+" "\\+"} $pattern]
::completion::debug_msg "+ - pattern = $pattern" "searches"
set pattern [string map {"*" "\\*"} $pattern]
::completion::debug_msg "* - pattern = $pattern" "searches"
set skippingPrefix [string range $pattern 0 0]
::completion::debug_msg "skippingPrefix = $skippingPrefix" "searches"
set skippingString [string range $pattern 1 end]
::completion::debug_msg "skippingString = $skippingString" "searches"
set skippingString [string map {"." "\\."} $skippingString]
::completion::debug_msg ". skippingString = $skippingString" "searches"
set pattern "$skippingPrefix$skippingString"
::completion::debug_msg ". - pattern = $pattern" "searches"
return $pattern
}
proc ::completion::update_completions_gui {} {
::completion::debug_msg "entering update_completions_gui" "entering_procs"
if {[winfo exists .pop.f.lb]} {
::completion::scrollbar_check
if {$::completions == {}} { ::completion::set_empty_listbox }
if {[llength $::completions] > 1} {
.pop.f.lb configure -state normal
.pop.f.lb select clear 0 end
.pop.f.lb select set 0 0
.pop.f.lb yview scroll -100 page
}
}
}
proc ::completion::unique {} {
::completion::debug_msg "entering unique" "entering_procs"
return [expr {[llength $::completions] == 1
&& [::completion::valid]}]
}
proc ::completion::valid {} {
::completion::debug_msg "entering valid" "entering_procs"
return [expr {[lindex $::completions 0] ne "(empty)"}]
}
# this is run when there are no results to display
proc ::completion::set_empty_listbox {} {
::completion::debug_msg "entering set_empty_listbox" "entering_procs"
if {[winfo exists .pop.f.lb]} {
::completion::scrollbar_check
.pop.f.lb configure -state disabled
}
set ::completions {"(empty)"}
}
#this proc moves the selection down (incrementing the index)
proc ::completion::increment {{amount 1}} {
::completion::debug_msg "entering increment" "entering_procs"
::completion::debug_msg "amount = $amount" "popup_gui"
if {$::focus != "pop"} {
focus .pop.f.lb
set ::focus "pop"
}
::completion::debug_msg "bindtags = [bindtags .pop.f.lb]" "popup_gui"
::completion::debug_msg "bindings on .pop.f.lb = [bind .pop.f.lb]" "popup_gui"
set selected [.pop.f.lb curselection]
::completion::debug_msg "selected = $selected" "popup_gui"
#if completion list is empty then "selected" will be empty
if { ![ string is integer -strict $selected] } {
return
}
set updated [expr {($selected + $amount) % [llength $::completions]}]
::completion::debug_msg "updated = $updated" "popup_gui"
.pop.f.lb selection clear 0 end
.pop.f.lb selection set $updated
::completion::debug_msg "curselection after selection set = [.pop.f.lb curselection]" "popup_gui"
.pop.f.lb see $updated
}
# store keywords (send/receive or array)
proc ::completion_store {tag} {
# I'm disabling the unique names completion for now because i don't think it is desireable.
# While it does detects when the user type a new name it **doesn't** when those names are not
# used any more (user closed their containing patch, deleted their objects, etc).
# Also it doesn't detect those names when the user loads an patch.
# In future versions we should be able to do that communicating with PD directly.
return
::completion::debug_msg "entering completion store" "entering_procs"
::completion::debug_msg " tag = $tag" "unique_names"
set name 0
set kind(sr) {s r send receive}
set kind(sra) {send~ receive~}
set kind(tc) {throw~ catch~}
set kind(arr) {tabosc4~ tabplay~ tabread tabread4 \
tabread4~ tabread~ tabwrite tabwrite~}
set kind(del) {delread~ delwrite~}
if {[regexp {^(s|r|send|receive)\s(\S+)$} $tag -> do_not_matter name]} {
set which sr
}
if {[regexp {^(send\~|receive\~)\s(\S+)$} $tag -> do_not_matter name]} {
set which sra
}
if {[regexp {^(throw\~|catch\~)\s(\S+)$} $tag -> do_not_matter name]} {
set which tc
}
if {[regexp {^tab\S+\s(\S+)$} $tag -> name]} {
set which arr
}
if {[regexp {^(delread\~|delwrite\~)\s(\S+)\s*\S*$} $tag -> do_not_matter name]} {
set which del
::completion::debug_msg "4 do_not_matter = $do_not_matter" "unique_names"
::completion::debug_msg "4 name = $name" "unique_names"
}
::completion::debug_msg "Unique name = $name" "unique_names"
if {$name != 0} {
foreach key $kind($which) {
::completion::debug_msg "key = $key" "unique_names"
if {[lsearch -all -inline -glob $::all_externals [list $key $name]] eq ""} {
lappend ::all_externals [list $key $name]
set ::all_externals [lsort $::all_externals]
}
}
}
}
#this is called when the user selects the desired external
proc ::completion::choose_selected {} {