-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdlg_snip_manage.py
1218 lines (1034 loc) · 48.9 KB
/
dlg_snip_manage.py
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
import os
import json
import re
import datetime
import cudatext as ct
from cuda_snippets import vs
from cuda_snippets.snip.utils import load_json
from cudax_lib import get_translation
_ = get_translation(__file__) # I18N
DATA_DIR = ct.app_path(ct.APP_DIR_DATA)
MAIN_SNIP_DIR = os.path.join(DATA_DIR, 'snippets_ct')
SNIP_DIRS = [
MAIN_SNIP_DIR,
os.path.join(DATA_DIR, 'snippets_vs'),
]
TYPE_PKG = 101
TYPE_GROUP = 102
HELP_TEXT = _("""Tab-stop markers:
${NN}
or:
${NN:default_text}
where NN is a number.
Macros:
${sel} - Text selected before snippet insertion (if snippet called with Tab key, it's empty string)
${cp} - Current clipboard contents
${cmt_start} - Current lexer's "block comment" start symbols (or empty string)
${cmt_end} - Current lexer's "block comment" end symbols (or empty string)
${cmt_line} - Current lexer's "line comment" symbols (or empty string)
${fname} - File name only, without path
${fpath} - Full file name, with path
${fdir} - Directory of file
${fext} - Extension of file
${psep} - OS path separator: backslash on Windows, slash on Unix
${date:nnnn} - Current date/time formatted by string "nnnn"; see Python docs
${env:nnnn} - Value of OS environment variable "nnnn"
${cmd:nnnn} - Output of OS shell command "nnnn"
Macros like in Sublime Text, $NAME or ${NAME}:
$TM_SELECTED_TEXT - The currently selected text or the empty string
$TM_CURRENT_LINE - The contents of the current line
$TM_CURRENT_WORD - The contents of the word under cursor or the empty string
$TM_LINE_INDEX - The zero-based line number
$TM_LINE_NUMBER - The one-based line number
$TM_FILEPATH - The full file path of the current document
$TM_DIRECTORY - The directory of the current document
$TM_FILENAME - The filename of the current document
$TM_FILENAME_BASE - The filename of the current document without its extensions
$CLIPBOARD - The contents of your clipboard
$WORKSPACE_NAME - The name of the opened workspace or folder
$BLOCK_COMMENT_START - Current lexer's "block comment" start symbols (or empty string)
$BLOCK_COMMENT_END - Current lexer's "block comment" end symbols (or empty string)
$LINE_COMMENT - Current lexer's "line comment" symbols (or empty string)
Date/time:
$CURRENT_YEAR - The current year
$CURRENT_YEAR_SHORT - The current year's last two digits
$CURRENT_MONTH - The month as two digits (e.g. '02')
$CURRENT_MONTH_NAME - The full name of the month (e.g. 'July')
$CURRENT_MONTH_NAME_SHORT - The short name of the month (e.g. 'Jul')
$CURRENT_DATE - The day of the month
$CURRENT_DAY_NAME - The name of day (e.g. 'Monday')
$CURRENT_DAY_NAME_SHORT - The short name of the day (e.g. 'Mon')
$CURRENT_HOUR - The current hour in 24-hour clock format
$CURRENT_MINUTE - The current minute
$CURRENT_SECOND - The current second
$CURRENT_SECONDS_UNIX - The number of seconds since the Unix epoch
""")
class DlgSnipMan:
# save/restore combobox values
_package_val = None
_groups_val = None
_snippets_val = None
def __init__(self, select_lex=None):
self.select_lex = select_lex # select first group with this lexer, mark in menus
self.current_pkg_readonly = False
self.last_selected_pkg_grp = None
self.last_selected_snippet = None
self.snippets_changed = False
self.skip_asking_to_save = False
self.packages = self._load_packages()
self._sort_pkgs()
self.file_snippets = {} # tuple (<pkg path>,<group>) : snippet dict
self.modified = [] # (type, name)
w, h = 530, 400 # w=500 is too small for translations
bw, lw = 90, 80 # button width, label width
self.h = ct.dlg_proc(0, ct.DLG_CREATE)
ct.dlg_proc(self.h, ct.DLG_PROP_SET,
prop={'cap': _('Manage snippets'),
'w_min': 5 * bw,
'w': w,
'h': h,
'border': ct.DBORDER_SIZE,
'on_close_query': self._ask_save_changes,
}
)
### Controls
# Cancel | Ok | Help
n_ed_lexer = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n_ed_lexer,
prop={
'name': 'ed_lex',
'w_min': bw,
'sp_a': 6,
'autosize': True,
'cap': _('&Editor\'s Lexer'),
'on_change': self._menu_ed_lex,
}
)
n_help = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n_help,
prop={
'name': 'help',
'w_min': bw,
'sp_a': 6,
'sp_l': 10,
'autosize': True,
'cap': _('Macros &Help'),
'on_change': self._dlg_help,
}
)
self.n_cancel = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_cancel,
prop={
'name': 'cancel',
'w_min': bw,
'sp_a': 6,
'autosize': True,
'cap': _('&Cancel'),
'on_change': self._dismiss_dlg,
}
)
self.n_ok = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_ok,
prop={
'name': 'ok',
'a_l': None,
'a_t': None,
'a_r': ('', ']'),
'a_b': ('',']'),
'w_min': bw,
'sp_a': 6,
'autosize': True,
'cap': _('&OK'),
'on_change': self._save_changes_and_close,
}
)
### Main
n = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'group')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n,
prop={
'name': 'parent',
'a_l': ('','['),
'a_t': ('','['),
'a_r': ('',']'),
'a_b': ('cancel','['),
'sp_a': 3,
}
)
# package
n = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'label')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n,
prop={
'name': 'pkg_label',
'p': 'parent',
'a_l': ('', '['),
'a_t': ('','['),
'w_min': lw,
'sp_a': 3,
'sp_t': 6,
'cap': _('&Package: '),
}
)
self.n_package = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'combo_ro')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_package,
prop={
'name': 'packages',
'p': 'parent',
'sp_a': 3,
'act': True,
'on_change': self._on_package_selected,
}
)
self.n_add_pkg = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_pkg,
prop={
'name': 'add_pkg',
'p': 'parent',
'w_min': bw,
'sp_a': 3,
'cap': _('Add...'),
'en': True,
'on_change': self._create_pkg,
}
)
self.n_del_pkg = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_del_pkg,
prop={
'name': 'del_pkg',
'p': 'parent',
'a_l': None,
'a_t': ('pkg_label','-'),
'a_r': ('',']'),
'w_min': bw,
'sp_a': 3,
'cap': _('Delete...'),
'en': False,
'on_change': self._dlg_del_pkg,
}
)
# group
n = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'label')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n,
prop={
'name': 'grp_label',
'p': 'parent',
'a_l': ('', '['),
'a_t': ('packages',']'),
'w_min': lw,
'sp_a': 3,
'sp_t': 6,
'cap': _('&Group: '),
}
)
self.n_groups = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'combo_ro')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_groups,
prop={
'name': 'groups',
'p': 'parent',
'sp_a': 3,
'act': True,
'on_change': self._on_group_selected,
'en': False,
}
)
self.n_add_group = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_group,
prop={
'name': 'add_group',
'p': 'parent',
'w_min': bw,
'sp_a': 3,
'cap': _('Add...'),
'en': False,
'on_change': self._create_group,
}
)
self.n_del_group = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_del_group,
prop={
'name': 'del_group',
'p': 'parent',
'a_l': None,
'a_t': ('grp_label','-'),
'a_r': ('',']'),
'w_min': bw,
'sp_a': 3,
'cap': _('Delete...'),
'en': False,
'on_change': self._dlg_del_group,
}
)
# lexer
n = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'label')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n,
prop={
'name': 'lex_label',
'p': 'parent',
'a_l': ('', '['),
'a_t': ('groups',']'),
'w_min': lw,
'sp_a': 3,
'sp_t': 6,
'sp_l': 30,
'cap': _('Group\'s &lexers: '),
}
)
self.n_lex = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'edit')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_lex,
prop={
'name': 'lexers',
'p': 'parent',
'sp_a': 3,
'en': False,
}
)
self.n_add_lex = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_lex,
prop={
'name': 'add_lex',
'p': 'parent',
'a_l': None,
'a_t': ('lex_label','-'),
'a_r': ('',']'),
'w_min': 2*bw + 3,
'sp_a': 3,
'cap': _('Add Lexer...'),
'en': False,
'on_change': self._menu_add_lex,
}
)
# snippet
n = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'label')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n,
prop={
'name': 'snip_label',
'p': 'parent',
'a_l': ('', '['),
'a_t': ('lexers',']'),
'w_min': lw,
'sp_a': 3,
'sp_t': 6,
'cap': _('&Snippet: '),
}
)
self.n_snippets = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'combo_ro')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_snippets,
prop={
'name': 'snippets',
'p': 'parent',
'sp_a': 3,
'on_change': self._on_snippet_selected,
'act': True,
'en': False,
}
)
self.n_add_snip = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_snip,
prop={
'name': 'add_snip',
'p': 'parent',
'w_min': bw,
'sp_a': 3,
'cap': _('Add...'),
'en': False,
'on_change': self._create_snip,
}
)
self.n_del_snip = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_del_snip,
prop={
'name': 'del_snip',
'p': 'parent',
'a_l': None,
'a_t': ('snip_label','-'),
'a_r': ('',']'),
'w_min': bw,
'sp_a': 3,
'cap': _('Delete...'),
'en': False,
'on_change': self._dlg_del_snip,
}
)
self.n_rename_snip = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'button')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_rename_snip,
prop={
'name': 'rename_snip',
'p': 'parent',
'a_l': None,
'a_t': ('add_snip',']'),
'a_r': ('',']'),
'w_min': 2*bw + 3,
'sp_a': 3,
'cap': _('&Rename snippet...'),
'en': False,
'on_change': self._dlg_rename_snip,
}
)
# alias
n = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'label')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n,
prop={
'name': 'alias_label',
'p': 'parent',
'a_l': ('', '['),
'a_t': ('rename_snip',']'),
'w_min': lw,
'sp_a': 3,
'sp_t': 6,
'sp_l': 30,
'cap': _('Snippet\'s &alias: '),
}
)
self.n_alias = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'edit')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_alias,
prop={
'name': 'alias',
'p': 'parent',
'a_l': ('alias_label', ']'),
'a_t': ('alias_label','-'),
'a_r': ('',']'),
'sp_a': 3,
'en': False,
}
)
self.n_edit = ct.dlg_proc(self.h, ct.DLG_CTL_ADD, 'editor')
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_edit,
prop={
'name': 'editor',
'p': 'parent',
'a_l': ('', '['),
'a_t': ('alias',']'),
'a_r': ('',']'),
'a_b': ('',']'),
'sp_a': 3,
'sp_t': 6,
}
)
# align the following controls only after all of them have been created
# so correct tab order is possible
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_package,
prop={ 'a_l': ('pkg_label', ']'),
'a_t': ('pkg_label','-'),
'a_r': ('add_pkg','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_pkg,
prop={ 'a_l': None,
'a_t': ('pkg_label','-'),
'a_r': ('del_pkg','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_groups,
prop={ 'a_l': ('grp_label', ']'),
'a_t': ('grp_label','-'),
'a_r': ('add_group','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_group,
prop={ 'a_l': None,
'a_t': ('grp_label','-'),
'a_r': ('del_group','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_lex,
prop={ 'a_l': ('lex_label', ']'),
'a_t': ('lex_label','-'),
'a_r': ('add_lex','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_snippets,
prop={ 'a_l': ('snip_label', ']'),
'a_t': ('snip_label','-'),
'a_r': ('add_snip','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_add_snip,
prop={ 'a_l': None,
'a_t': ('snip_label','-'),
'a_r': ('del_snip','[')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_cancel,
prop={ 'a_l': None,
'a_t': ('ok', '-'),
'a_r': ('ok', '['),
'a_b': ('',']')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n_ed_lexer,
prop={ 'a_l': ('', '['),
'a_t': ('ok', '-'),
'a_r': None,
'a_b': ('',']')})
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n_help,
prop={ 'a_l': ('ed_lex', ']'),
'a_t': ('ok', '-'),
'a_r': None,
'a_b': ('',']')})
ct.dlg_proc(self.h, ct.DLG_CTL_FOCUS, name='ok')
h_ed = ct.dlg_proc(self.h, ct.DLG_CTL_HANDLE, index=self.n_edit)
self.ed = ct.Editor(h_ed)
self.ed.set_prop(ct.PROP_NEWLINE, 'lf') # for ease of splitting to lines
self.ed.set_prop(ct.PROP_UNPRINTED_SHOW, True)
self.ed.set_prop(ct.PROP_UNPRINTED_SPACES, True)
self.ed.set_prop(ct.PROP_TAB_SPACES, False)
self.ed.set_prop(ct.PROP_GUTTER_BM, False)
self.ed.set_prop(ct.PROP_MODERN_SCROLLBAR, False)
self._fill_forms(init_lex_sel=self.select_lex) # select first group with specified lexer if any
# if comboboxes selections was saved -> restore them
if self._package_val is not None:
if self._package_val >= 0:
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_package, prop={'val': self._package_val})
self._on_package_selected(-1, -1)
if self._groups_val >= 0:
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_groups, prop={'val': self._groups_val})
self._on_group_selected(-1, -1)
if self._snippets_val >= 0:
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_snippets, prop={'val': self._snippets_val})
self._on_snippet_selected(-1, -1)
def _fill_forms(self, init_lex_sel=None, sel_pkg_path=None, sel_group=None, sel_snip=None, reason=''):
if reason in ('rename','delete'):
# on "rename" or "delete": prevent current prefix/snippet changes from being stashed
self.last_selected_snippet = None
self.ed.set_prop(ct.PROP_MODIFIED, False)
# fill packages
items = [pkg.get('name') for pkg in self.packages]
# select first group with <lexer>
if init_lex_sel:
found = False
for pkg in self.packages:
for fn,lexs in pkg.get('files', {}).items():
if init_lex_sel in lexs:
if not found:
found = True
sel_pkg_path = pkg['path']
sel_group = fn
break
if found:
break
# mark packages with specified lexer
if self.select_lex:
for i,pkg in enumerate(self.packages):
for fn,lexs in pkg.get('files', {}).items():
if self.select_lex in lexs:
items[i] += ' (*{0})'.format(self.select_lex)
break
items = '\t'.join(items)
props = {'items': items,}
sel_pkg_ind = -1
sel_pkg = None
# select package, if specified
if sel_pkg_path: # select new package:
# find selected package
for i,pkg in enumerate(self.packages):
if pkg['path'] == sel_pkg_path:
sel_pkg_ind = i
sel_pkg = pkg
props['val'] = sel_pkg_ind
break
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_package, prop=props)
self._on_package_selected(-1,-1)
# select group
if sel_pkg is not None and sel_group and sel_group in sel_pkg.get('files', {}):
sel_group_ind = self._groups_items.index(sel_group)
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_groups, prop={'val': sel_group_ind})
self._on_group_selected(-1,-1)
# select snippet
if sel_snip is not None and sel_snip in self.snip_items:
sel_snip_ind = self.snip_items.index(sel_snip)
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_snippets, prop={'val': sel_snip_ind})
self._on_snippet_selected(-1,-1)
def show_add_snip(self):
ct.dlg_proc(self.h, ct.DLG_SCALE)
ct.dlg_proc(self.h, ct.DLG_SHOW_MODAL)
ct.dlg_proc(self.h, ct.DLG_FREE)
return self.snippets_changed
def _save_changes(self, *args, **vargs):
#pass; print('saving changes: {0}'.format(self.modified))
pkg = self._get_sel_pkg()
if pkg:
snips_fn,lexers = self._get_sel_group(pkg)
snip_name,snip = self._get_sel_snip(pkg, snips_fn) if lexers is not None else (None,None)
#_pkg_name = pkg["name"] if pkg else "<no_pkg>"
#pass; print(' + {} # {}, [{}] # <{}>:<{}>'.format(_pkg_name, snips_fn, lexers, snip_name, snip))
### load data from form
# check if modified group's lexers
if snips_fn is not None and lexers is not None:
oldlexes = pkg["files"][snips_fn]
p = ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_lex)
newlexs = [lex.strip() for lex in p['val'].split(',') if lex.strip()]
if oldlexes != newlexs:
#print(_('* Group\'s lexers changed: [{0}] => [{1}]').format(oldlexes, newlexs))
pkg['files'][snips_fn] = newlexs
self.modified.append((TYPE_PKG, pkg['path']))
# check if modified snippet (alias|body) (only if group is selected)
if snip_name is not None and snip is not None:
oldalias = snip.get('prefix')
if isinstance(oldalias, list):
oldalias = oldalias[0] # it seems that multiple prefixes are not supported by this plugin
p = ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_alias)
newalias = p['val']
if oldalias != newalias:
#print(_('* snippet\'s alias changed: [{0}] => [{1}]').format(oldalias, newalias))
snip['prefix'] = newalias
self.modified.append((TYPE_GROUP, pkg['path'], snips_fn, snip_name))
# check if modified snippet body
oldbody = snip['body']
newbody = self.ed.get_text_all().split('\n') # line end is always 'lf'
if oldbody != newbody:
#print(_('* snippet\'s body changed:\n{0}\n ==>>\n{1}').format('\n'.join(oldbody), '\n'.join(newbody)))
snip['body'] = newbody
self.modified.append((TYPE_GROUP, pkg['path'], snips_fn, snip_name))
# save modified
if self.modified:
print(_('Saving changes'))
saved_files = set() # save each file only once
for mod in self.modified:
# lexers changed, created group, created package, deleted group
# -> save package config file
if mod[0] == TYPE_PKG:
type_,package_dir = mod
path2pkg = {p['path']:p for p in self.packages if p['path'] == package_dir}
if not path2pkg: # bugfix
continue
pkg_copy = {**path2pkg[package_dir]}
del pkg_copy['path']
data = pkg_copy
file_dst = os.path.join(package_dir, 'config.json')
# snippet changed (alias, body), snippet created, deleted; created group
# -> save snippets file
elif mod[0] == TYPE_GROUP:
type_, package_dir, snips_fn, snip_name = [*mod, None][0:4] # fourth item is optional : None
snips = self.file_snippets.get((package_dir, snips_fn))
if snips is None:
print(_('! ERROR: trying to save snippets for unloaded group: {0}').format((package_dir, snips_fn)))
continue
data = snips
file_dst = os.path.join(package_dir, 'snippets', snips_fn)
else:
raise Exception('Invalid Modified type: {mod}')
if file_dst in saved_files:
#pass; print('* already saved, skipping: {0}'.format(file_dst))
continue
saved_files.add(file_dst)
#pass; print('*** saving data: {0}'.format(file_dst))
self.snippets_changed = True
folder = os.path.dirname(file_dst)
if not os.path.exists(folder):
os.makedirs(folder)
with open(file_dst, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
if self.modified:
print(' '+_('Saved.'))
def _save_changes_and_close(self, *args, **vargs):
self._save_changes()
self.skip_asking_to_save = True
ct.dlg_proc(self.h, ct.DLG_HIDE)
def _ask_save_changes(self, *args, **vargs):
# save comboboxes selections
DlgSnipMan._package_val = int(ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_package)['val'])
DlgSnipMan._groups_val = int(ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_groups)['val'])
DlgSnipMan._snippets_val = int(ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_snippets)['val'])
if self.skip_asking_to_save:
return
self._put_unsaved_changes_to_dict(also_put_lexers=True)
if not self.modified:
return True
else:
res = ct.msg_box(_("Save changes?"), ct.MB_YESNOCANCEL + ct.MB_ICONWARNING)
if res == ct.ID_YES:
self._save_changes()
return True
elif res == ct.ID_NO:
return True
else:
return False
def _dismiss_dlg(self, *args, **vargs):
self.skip_asking_to_save = True
ct.dlg_proc(self.h, ct.DLG_HIDE)
def _set_editor_text(self, text):
self._enable_ctls(True, self.n_edit)
self.ed.set_text_all(text)
self.ed.set_prop(ct.PROP_MODIFIED, False) # mark as not-modified
self._enable_ctls(not self.current_pkg_readonly, self.n_edit)
def _put_unsaved_changes_to_dict(self, also_put_lexers=False):
'''
if snippet editor is modified we put new changes into `self.file_snippets` dict,
essentially remembering them, so they don't get lost while switching to another snippet/package/group.
'''
if also_put_lexers and self.last_selected_pkg_grp:
pkg, snips_fn, oldlexes = self.last_selected_pkg_grp
p = ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_lex)
newlexs = [lex.strip() for lex in p['val'].split(',') if lex.strip()]
if oldlexes != newlexs:
#print("newlexs", newlexs, 'for: ',snips_fn)
pkg['files'][snips_fn] = newlexs
self.modified.append((TYPE_PKG, pkg['path']))
if not self.last_selected_snippet:
return
pkg, snips_fn, name, snip = self.last_selected_snippet
self.last_selected_snippet = None # clear now
ed_modified = self.ed.get_prop(ct.PROP_MODIFIED)
self.ed.set_prop(ct.PROP_MODIFIED, False) # clear now
oldalias = snip.get('prefix')
if isinstance(oldalias, list):
oldalias = oldalias[0] # it seems that multiple prefixes are not supported by this plugin
p = ct.dlg_proc(self.h, ct.DLG_CTL_PROP_GET, index=self.n_alias)
newalias = p['val']
#print("ed_modified:{} oldalias:{} newalias:{}".format(ed_modified,oldalias,newalias))
if ed_modified or (oldalias != newalias):
#print('NOTE: Storing "{}" snippet in dict'.format(name))
snip_text = self.ed.get_text_all().split('\n')
snips = self.file_snippets.get((pkg['path'], snips_fn)) # snippets of last selected group will be loaded
if snips is not None:
snips[name] = {'prefix':newalias, 'body':snip_text}
self.modified.append((TYPE_GROUP, pkg['path'], snips_fn, name))
def _on_snippet_selected(self, id_dlg, id_ctl, data='', info=''):
#pass; print('snip sel')
self._put_unsaved_changes_to_dict()
pkg = self._get_sel_pkg()
snips_fn,lexers = self._get_sel_group(pkg)
snip_name,snip = self._get_sel_snip(pkg, snips_fn)
self.last_selected_snippet = (pkg, snips_fn, snip_name, snip)
#pass; print(' snip sel:{0}: {1}'.format(snip_name, snip))
if not all((pkg, snips_fn, snip_name, snip)):
self.last_selected_snippet = None # clear
return
if not self.current_pkg_readonly:
self._enable_ctls(True, self.n_alias, self.n_add_snip, self.n_del_snip,
self.n_rename_snip)
prefix = snip.get('prefix', '')
if isinstance(prefix, list):
prefix = prefix[0] # it seems that multiple prefixes are not supported by this plugin
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_alias, prop={
'val': prefix,
})
body = snip.get('body', [])
txt = '\n'.join(body) if type(body) == list else body
self._set_editor_text(txt)
def _on_group_selected(self, id_dlg, id_ctl, data='', info=''):
#pass; print('group sel')
called_by_event = id_dlg!=-1
self._put_unsaved_changes_to_dict(also_put_lexers=called_by_event) # put_lexers only if called by event
self._set_editor_text('')
# disable all below 'group'
self._enable_ctls(False, self.n_alias, self.n_add_snip, self.n_del_snip,
self.n_rename_snip, self.n_add_group, self.n_edit)
pkg = self._get_sel_pkg()
snips_fn,lexers = self._get_sel_group(pkg)
#pass; print(' * selected B:group: {0}, lexers:{1}'.format(snips_fn, lexers))
if not pkg or not snips_fn:
return
self.last_selected_pkg_grp = pkg, snips_fn, lexers
if self.file_snippets.get((pkg['path'],snips_fn)) is None:
self._load_package_snippets(pkg['path'])
#pass; print(' + loaded group snips')
# enable stuff
if not self.current_pkg_readonly:
self._enable_ctls(True, self.n_lex, self.n_snippets, self.n_del_pkg,
self.n_add_group, self.n_del_group, self.n_add_lex, self.n_add_snip)
else:
self._enable_ctls(True, self.n_snippets)
### fill groups
# lexers
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_lex, prop={
'val': ', '.join(lexers),
})
# snippet names
snip_items = [name for name,val in self.file_snippets.get((pkg['path'],snips_fn)).items()
if 'body' in val and 'prefix' in val]
snip_items.sort()
self.snip_items = [*snip_items]
snip_items = '\t'.join(snip_items)
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_snippets, prop={
'val': None, # selected item
'items': snip_items,
})
# set editor lexer to first existing lexer of snippet group
if lexers:
ed_lex = self.ed.get_prop(ct.PROP_LEXER_FILE)
if not ed_lex or ed_lex not in lexers: # dont change if current editor lex is in group
app_lexs = set(ct.lexer_proc(ct.LEXER_GET_LEXERS, ''))
# ignore several lexers
app_lexs.discard('Markdown')
app_lexs.discard('reStructuredText')
app_lexs.discard('Textile')
app_lexs.discard('MediaWiki')
for lex in lexers:
if lex in app_lexs:
self.ed.set_prop(ct.PROP_LEXER_FILE, lex)
break
def _on_package_selected(self, id_dlg, id_ctl, data='', info=''):
#pass; print('pkg sel')
self._put_unsaved_changes_to_dict(also_put_lexers=True)
# disable all below 'group'
disable_btns = [self.n_add_group, self.n_del_group, self.n_add_lex, self.n_add_snip,
self.n_del_snip, self.n_rename_snip]
self._enable_ctls(False, self.n_lex, self.n_snippets, self.n_alias, self.n_edit, *disable_btns)
pkg = self._get_sel_pkg()
if pkg is None: # no package selected
for n in [self.n_groups, self.n_del_pkg]:
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=n, prop={'en': False,})
self._groups_items = None
self._set_editor_text('')
self._enable_ctls(False, self.n_edit)
self.last_selected_pkg_grp = None
return
_name = pkg['name'].lower()
self.current_pkg_readonly = _name.startswith('std.') or _name.startswith('snippets.')
self._set_editor_text('')
#pass; print(' * selected pkg: {0}'.format(pkg["name"]))
# fill groups
items = list(pkg['files'])
items.sort()
self._groups_items = [*items]
# select package with specified lexer
if self.select_lex and items:
for i,lexs in enumerate(pkg.get('files', {}).values()):
if self.select_lex in lexs:
items[i] += ' (*{0})'.format(self.select_lex)
items = '\t'.join(items)
self._enable_ctls(True, self.n_groups, self.n_add_pkg, self.n_del_pkg, self.n_add_group)
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_groups, prop={
'val': None,
'en': True,
'items': items,
})
# if have only one snip file - select it
file_cnt = len(pkg.get('files', {}))
if id_dlg != -1 and file_cnt == 1: # -1 - called manually (from fill_forms())
ct.dlg_proc(self.h, ct.DLG_CTL_PROP_SET, index=self.n_groups, prop={'val': 0})
self._on_group_selected(-1,-1)
else:
self._enable_ctls(False, self.n_edit)
self.last_selected_pkg_grp = None
#def _create_snip(self, pkg, snips_fn):
def _create_snip(self, id_dlg, id_ctl, data='', info=''):
pkg = self._get_sel_pkg()
snips_fn,lexers = self._get_sel_group(pkg)
if not pkg or not snips_fn:
return
#pass; print(' ~~~ new C:snip ~~~: {0}; group:{1}'.format(pkg["path"], snips_fn))
name = ct.dlg_input(_('New snippet name:'), '')
#pass; print(' snip name: {0}'.format(name))
if name:
snips = self.file_snippets.get((pkg['path'], snips_fn)) # snippets of selected group will be loaded
if snips is not None:
if name not in snips:
snips[name] = {'prefix':name, 'body':''}
self.modified.append((TYPE_GROUP, pkg['path'], snips_fn, name))
# select new snip
self._fill_forms(sel_pkg_path=pkg['path'], sel_group=snips_fn, sel_snip=name)
else:
print(_('"{0}" - snippet already exists.').format(name))
#def _create_group(self, pkg):
def _create_group(self, id_dlg, id_ctl, data='', info=''):
pkg = self._get_sel_pkg()
if not pkg:
return
#pass; print(' ~~~ create new B:Group ===')
lex = ct.ed.get_prop(ct.PROP_LEXER_FILE)
name = lex if lex else 'snippets'
name = ct.dlg_input(_('New snippet group filename:'), name)
#pass; print('new group name:{0}'.format(name))
if name:
if not name.endswith('.json'):
name += '.json'
# checking for file in case of case-insensitive filesystem
if os.path.exists(os.path.join(pkg['path'], 'snippets', name)):
print(_('"{0}" - group already exists.').format(name))
return
pkg['files'][name] = [lex]
self.file_snippets[(pkg['path'], name)] = {}
self.modified.append((TYPE_PKG, pkg['path']))
self.modified.append((TYPE_GROUP, pkg['path'], name))
# select new group
self._fill_forms(sel_pkg_path=pkg['path'], sel_group=name)
def _create_pkg(self, id_dlg, id_ctl, data='', info=''):
#pass; print(' ~~~ create new package ===')
lex = ct.ed.get_prop(ct.PROP_LEXER_FILE)
name = 'New_'+lex if lex else 'NewPackage'
name = ct.dlg_input(_('New package name (should be a valid directory name):'), name)
#pass; print('new pkg name:{0}'.format(name))
if name:
newpkg = {'name': name,
'files': {},
'path': os.path.join(MAIN_SNIP_DIR, name)}
if os.path.exists(os.path.join(MAIN_SNIP_DIR, name, 'config.json')):
print(_('"{0}" - package already exists.').format(os.path.join(MAIN_SNIP_DIR, name, 'config.json')))
return
self.packages.append(newpkg) # update packages and select new
self._sort_pkgs()
self.modified.append((TYPE_PKG, newpkg['path']))
# select new package
self._fill_forms(sel_pkg_path=newpkg['path'])
def _dlg_del_pkg(self, *args, **vargs):
''' show directory path to delete with OK|Cancel
+ remove from 'self.packages' if confirmed
'''
#pass; print('del pkg {0};; {1}'.format(args, vargs))