-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcd_fi_in_fi.py
3061 lines (2866 loc) · 156 KB
/
cd_fi_in_fi.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
''' Plugin for CudaText editor
Authors:
Andrey Kvichansky (kvichans on github.com)
Version:
'3.1.26 2023-12-28'
ToDo: (see end of file)
'''
import re, os, sys, time, itertools, locale, json, collections, copy
import cudatext as app
from cudatext import ed
import cudatext_cmd as cmds
from cudatext_keys import *
import cudax_lib as apx
from .cd_plug_lib import *
from .cd_fif_api import *
from chardet.universaldetector import UniversalDetector
from .encodings import *
odict = collections.OrderedDict
d = dict
def first_true(iterable, default=False, pred=None):return next(filter(pred, iterable), default) # 10.1.2. Itertools Recipes
MIN_API_VER = '1.0.178'
MIN_API_VER = '1.0.180' # panel group p
MIN_API_VER = '1.0.183' # on_change
MIN_API_VER = '1.0.216' # STATUSBAR_SET_AUTOSTRETCH
MIN_API_VER = '1.0.246' # events for control 'editor'
#MIN_API_VER = '1.0.249' # on_menu in 'editor', 'val' in 'pages'
pass; #Tr.tr = Tr(get_opt('fif_log_file', '')) if get_opt('fif_log_file', '') else Tr.tr
pass; #LOG = (-9== 9) or get_opt('fif_LOG' , False) # Do or dont logging.
pass; #from pprint import pformat
pass; #pf=lambda d:pformat(d,width=150)
pass; ##!! "waits correction"
pass; #log('ok',())
_ = get_translation(__file__) # I18N
VERSION = re.split('Version:', __doc__)[1].split("'")[1]
VERSION_V, \
VERSION_D = VERSION.split(' ')
MAX_HIST= apx.get_opt('ui_max_history_edits', 20)
MENU_CENTERED = app.DMENU_CENTERED if app.app_api_version()>='1.0.27' else 0
CFG_PATH= app.app_path(app.APP_DIR_SETTINGS)+os.sep+CFG_FILE
CLOSE_AFTER_GOOD= get_opt('fif_hide_if_success' , False)
USE_EDFIND_OPS = get_opt('fif_use_edfind_opt_on_start' , False)
DEF_LOC_ENCO = 'cp1252' if sys.platform=='linux' else locale.getpreferredencoding()
loc_enco = get_opt('fif_locale_encoding', DEF_LOC_ENCO)
totb_l = [TOTB_NEW_TAB, TOTB_USED_TAB]
shtp_l = [SHTP_SHORT_R, SHTP_SHORT_RCL
,SHTP_MIDDL_R, SHTP_MIDDL_RCL
,SHTP_SPARS_R, SHTP_SPARS_RCL
,SHTP_SHRTS_R, SHTP_SHRTS_RCL
]
dept_l = [_('+All'), _('Only'), _('+1 level'), _('+2 levels'), _('+3 levels'), _('+4 levels'), _('+5 levels')]
skip_l = [_("Don't skip"), _('-Hidden'), _('-Binary'), _('-Hidden, -Binary')]
sort_l = [_("Don't sort"), _('By date, from newest'), _('By date, from oldest')]
enco_l = ['{}, UTF-8, '+ENCO_DETD
,'UTF-8, {}, '+ENCO_DETD
,'{}, ' +ENCO_DETD
,'UTF-8, ' +ENCO_DETD
,'{}, UTF-8'
,'UTF-8, {}'
,'{}'
,'UTF-8'
, ENCO_DETD
] \
if loc_enco!='UTF-8' else \
['{}, ' +ENCO_DETD
,'{}'
, ENCO_DETD
]
enco_l = [f(enco, loc_enco) for enco in enco_l]
TOTB_L = totb_l
SHTP_L = shtp_l
DEPT_L = dept_l
SKIP_L = skip_l
SORT_L = sort_l
ENCO_L = enco_l
def reload_opts():
api_reload_opts()
global CLOSE_AFTER_GOOD,USE_EDFIND_OPS, loc_enco, enco_l
CLOSE_AFTER_GOOD= get_opt('fif_hide_if_success' , False)
USE_EDFIND_OPS = get_opt('fif_use_edfind_opt_on_start' , False)
loc_enco = get_opt('fif_locale_encoding', DEF_LOC_ENCO)
enco_l = ['{}, UTF-8, '+ENCO_DETD
,'UTF-8, {}, '+ENCO_DETD
,'{}, ' +ENCO_DETD
,'UTF-8, ' +ENCO_DETD
,'{}, UTF-8'
,'UTF-8, {}'
,'{}'
,'UTF-8'
, ENCO_DETD
] \
if loc_enco!='UTF-8' else \
['{}, ' +ENCO_DETD
,'{}'
, ENCO_DETD
]
enco_l = [f(enco, loc_enco) for enco in enco_l]
#def reload_opts()
def limit_len(text, max_len, div='..'):
if len(text)<=max_len: return text
part_len = int((max_len-2)/2)
return text[:part_len] + div + text[-part_len:]
class Command:
def find_in_ed(self):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
filename= ed.get_filename()
incl_s = os.path.basename(filename) if filename else ed.get_prop(app.PROP_TAB_TITLE)
incl_s = '"'+incl_s+'"' if ' ' in incl_s else incl_s
return dlg_fif(what='', opts=dict(
incl = incl_s
,fold = IN_OPEN_FILES
))
#def find_in_ed
def find_in_tabs(self):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
return dlg_fif(what='', opts=dict(
incl = '*'
,fold = IN_OPEN_FILES
))
#def find_in_ed
def repeat_find_by_rpt(self):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
if ed.get_prop(app.PROP_LEXER_FILE).upper() not in lexers_l:
return app.msg_status(_('The command works only with reports of FindInFiles plugin'))
req_opts = report_extract_request(ed)
if not req_opts:
return app.msg_status(_('No info to repeat search'))
req_opts= json.loads(req_opts)
what = req_opts.pop('what', '')
return dlg_fif(what=what, opts=req_opts)
#def repeat_find_by_rpt
def show_dlg(self, what='', opts={}):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
return dlg_fif(what, opts)
def _nav_to_src(self, where:str, how_act='move'):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
return nav_to_src(where, how_act)
def _jump_to(self, drct:str, what:str):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
return jump_to(drct, what)
def on_goto_def(self, ed_self):
if app.app_api_version()<MIN_API_VER: return app.msg_status(_('Must update the application'))
if ed_self.get_prop(app.PROP_LEXER_FILE).upper() in lexers_l:
self._nav_to_src('same', 'move')
return True
def on_click_dbl(self, ed_self, scam):
dcls = Command.get_dcls()
dcl = dcls.get(scam, '')
pass; #LOG and log('scam, dcl={}',(scam, dcl))
if not dcl:
return
if ed_self.get_prop(app.PROP_LEXER_FILE).upper() not in lexers_l:
return
return not self._nav_to_src(*dcl.split(','))
#def on_click_dbl
dcls = None
dcls_def= {'':'same,stay'}
@staticmethod
def get_dcls():
if Command.dcls is None:
stores = json.loads(re.sub(r',\s*}', r'}', open(CFG_PATH).read()), object_pairs_hook=odict) \
if os.path.exists(CFG_PATH) and os.path.getsize(CFG_PATH) != 0 else \
odict()
Command.dcls = stores.get('dcls', Command.dcls_def)
return Command.dcls
#def get_dcls
def dlg_nav_by_dclick(self):
dlg_nav_by_dclick()
def dlg_fif_opts(self):
return dlg_fif_opts()
#class Command
FIF_META_OPTS=[
{ "cmt": re.sub(r' +', r'', _(
"""Option allows to save separate search settings
(search text, source folder, files mask etc)
per each mentioned session or project.
Each item in the option is RegEx,
which is compared with the full path of session (project).
First matched item is used.""")),
"def": [],
"frm": "json",
"opt": "fif_sep_hist_for_sess_proj",
"chp": _("History"),
"tgs": []
},
{ "cmt": _("Copy options [.*], [aA], [\"w\"] from CudaText dialog to plugin's dialog."),
"def": False,
"frm": "bool",
"opt": "fif_use_edfind_opt_on_start",
"chp": _("Start"),
"tgs": ["start", "settings"]
},
{ "cmt": _("Use selection text from current file when dialog opens."),
"def": False,
"frm": "bool",
"opt": "fif_use_selection_on_start",
"chp": _("Start"),
"tgs": ["start"]
},
{ "cmt": _("Store Results between dialog call if setting is \"[ ]Send\"."),
"def": True,
"frm": "bool",
"opt": "fif_store_prev_results",
"chp": _("Start"),
"tgs": ["start"]
},
{ "cmt": re.sub(r' +', r'', _(
"""List of lexer names to use for report file.
First available lexer is used.""")),
"def": [
"Search results",
"FiF"
],
"frm": "json",
"opt": "fif_lexers",
"chp": _("Report"),
"tgs": ["lexer", "report"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Auto-write 'tab_size' to report's lexer-specific config,
if no such setting. Use 0 to skip.""")),
"def": 2,
"frm": "int",
"opt": "fif_lexer_auto_tab_size",
"chp": _("Report"),
"tgs": ["lexer", "report"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Allows Esc key to stop all stages of current search.
If false, Esc stops only the current stage.""")),
"def": False,
"frm": "bool",
"opt": "fif_esc_full_stop",
"chp": _("Searching"),
"tgs": ["searching", "stop"]
},
{ "cmt": _("Show report even if nothing found."),
"def": False,
"frm": "bool",
"opt": "fif_report_no_matches",
"chp": _("Report"),
"tgs": ["report", "comfort"]
},
{ "cmt": _("[x]Append: Need to fold previous results."),
"def": False,
"frm": "bool",
"opt": "fif_fold_prev_res",
"chp": _("Report"),
"tgs": ["report", "append", "comfort"]
},
{ "cmt": _("Close dialog if search has found matches."),
"def": False,
"frm": "bool",
"opt": "fif_hide_if_success",
"chp": "",
"tgs": ["comfort"]
},
{ "cmt": _("Length of substring (from field \"Find\"), which appears in the report document title."),
"def": 10,
"frm": "int",
"opt": "fif_len_target_in_title",
"chp": _("Report"),
"tgs": ["report", "comfort"]
},
{ "cmt": _("If report document has a filename, save report after filling it."),
"def": False,
"frm": "bool",
"opt": "fif_auto_save_if_file",
"chp": _("Report"),
"tgs": ["report", "file"]
},
{ "cmt": _("Activate document with report after filling it."),
"def": True,
"frm": "bool",
"opt": "fif_focus_to_rpt",
"chp": _("Report"),
"tgs": ["report", "comfort"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Save search details (\"Find\", \"In folder\", …) in the first line of report.
The info will be used in command \"Repeat search for this report-tab\".""")),
"def": False,
"frm": "bool",
"opt": "fif_save_request_to_rpt",
"chp": _("Report"),
"tgs": ["report", "comfort"]
},
{ "cmt": _("Append specified string to the field 'Not in files'."),
"def": "/.svn /.git /.hg /.idea",
"frm": "str",
"opt": "fif_always_not_in_files",
"chp": _("Searching"),
"tgs": ["searching"]
},
{ "cmt": _("Size of buffer (at file start) to detect binary files."),
"def": 1024,
"frm": "int",
"opt": "fif_read_head_size(bytes)",
"chp": _("Searching"),
"tgs": ["searching", "internal"]
},
{ "cmt": _("If value>0, skip all files, which sizes are bigger than this value (in Kb)."),
"def": 0,
"frm": "int",
"opt": "fif_skip_file_size_more_Kb",
"chp": _("Searching"),
"tgs": ["searching", "scope"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Default encoding to read files.
If value is empty, then the following is used:
cp1252 for Linux,
preferred encoding from locale for others (Win, macOS, …).""")), #! Shift uses chr(160)
"def": "",
"frm": "str",
"opt": "fif_locale_encoding",
"chp": _("Searching"),
"tgs": ["searching", "internal", "encoding"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Style to mark found fragment in report.
Full form:
"fif_mark_style":{
"color_back":"",
"color_font":"",
"font_bold":false,
"font_italic":false,
"color_border":"",
"borders":{"left":"","right":"","bottom":"","top":""}
},
Color values: "" - skip, "#RRGGBB" - hex-digits
Values for border sides: "solid", "dash", "2px", "dotted", "rounded", "wave" """)), #! Shift uses chr(160)
"def": {"borders": {"bottom": "dotted"}},
"frm": "json",
"opt": "fif_mark_style",
"chp": _("Report"),
"tgs": ["report", "mark"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Style to mark replaced fragment in report (unique in line).
Full form:
"fif_mark_true_replace_style":{
"color_back":"",
"color_font":"",
"font_bold":false,
"font_italic":false,
"color_border":"",
"borders":{"left":"","right":"","bottom":"","top":""}
},
Color values: "" - skip, "#RRGGBB" - hex-digits
Values for border sides: "solid", "dash", "2px", "dotted", "rounded", "wave" """)), #! Shift uses chr(160)
"def": {"borders": {"bottom": "solid"}},
"frm": "json",
"opt": "fif_mark_true_replace_style",
"chp": _("Report"),
"tgs": ["report", "mark"]
},
{ "cmt": re.sub(r' +', r'', _(
"""Style to mark replaced fragment in report (not unique in line).
Full form:
"fif_mark_false_replace_style":{
"color_back":"",
"color_font":"",
"font_bold":false,
"font_italic":false,
"color_border":"",
"borders":{"left":"","right":"","bottom":"","top":""}
},
Color values: "" - skip, "#RRGGBB" - hex-digits
Values for border sides: "solid", "dash", "2px", "dotted", "rounded", "wave" """)), #! Shift uses chr(160)
"def": {"borders": {"bottom":"wave"},"color_border":"#777"},
"frm": "json",
"opt": "fif_mark_false_replace_style",
"chp": _("Report"),
"tgs": ["report", "mark"]
},
{ "cmt": "Allows logging for all search stages.",
"def": False,
"frm": "bool",
"opt": "fif_LOG",
"chp": "Logging",
"tgs": ["log", "internal"]
},
{ "cmt": "Allows logging for searching stage.",
"def": False,
"frm": "bool",
"opt": "fif_FNDLOG",
"chp": "Logging",
"tgs": ["log", "internal"]
},
{ "cmt": "Allows logging for reporting stage.",
"def": False,
"frm": "bool",
"opt": "fif_RPTLOG",
"chp": "Logging",
"tgs": ["log", "internal"]
},
{ "cmt": "Allows logging for navigation stage.",
"def": False,
"frm": "bool",
"opt": "fif_NAVLOG",
"chp": "Logging",
"tgs": ["log", "internal"]
},
{ "cmt": "Append internal debug data to report.",
"def": False,
"frm": "bool",
"opt": "fif_DBG_data_to_report",
"chp": "Logging",
"tgs": ["log", "internal"]
},
{ "cmt": "Specifies filename of log file.",
"def": "",
"frm": "file",
"opt": "fif_log_file",
"chp": "Logging",
"tgs": ["log", "internal"]
},
{ "cmt": "Allows logging about failed file reads (encoding errors).",
"def": False,
"frm": "bool",
"opt": "fif_log_encoding_fail",
"chp": "Logging",
"tgs": ["log", "internal", "encoding"]
}
]
#] + ([] if app.app_api_version()<'1.0.289' else[ # Editor.action() with EDACTION_CODETREE_FILL and EDACTION_LEXER_SCAN
# { "cmt": re.sub(r' +', r'', _(
# """For these lexers to show in dialog statusbar
# path into CodeTree to current fragment in Source panel.""")),
# "def": [
# "Python",
# ],
# "frm": "json",
# "opt": "fif_codetree_path_in_status",
# "chp": _("Report"),
# "tgs": ["lexer", "report"]
# }
# ])
def dlg_fif_opts(dlg=None):
try:
import cuda_options_editor as op_ed
except:
return app.msg_box(_('To view/edit options install plugin "Options Editor"'),app.MB_OK)
dlg.store(what='save') if dlg else 0
# Transfer options from "user.json" to CFG_FILE
for opt_d in FIF_META_OPTS:
opt = opt_d['opt']
if 'no-no-no'!=apx.get_opt(opt, 'no-no-no', user_json=CFG_FILE): continue # Already transfered
opt_val_user = apx.get_opt(opt)
if opt_val_user is None: continue # Nothing to transfer
pass; #log("trans: opt,opt_val_user={}",(opt,opt_val_user))
apx.set_opt(opt, opt_val_user, user_json=CFG_FILE)
try:
op_ed.OptEdD(
path_keys_info=FIF_META_OPTS
# path_keys_info=os.path.dirname(__file__)+os.sep+'fif_opts_def.json'
, subset ='fif-df.'
# , how =dict(only_for_ul=True, only_with_def=True)
# , how =dict(only_for_ul=True, only_with_def=True, hide_fil=True)
, how =dict(only_for_ul=True, only_with_def=True, hide_fil=True, stor_json=CFG_FILE)
).show(_('"Find in Files" options'))
except Exception as ex:
pass; log('ex={}',(ex))
# FIF_OPTS = os.path.dirname(__file__)+os.sep+'fif_options.json'
# fif_opts = json.loads(open(FIF_OPTS).read())
# op_ed.dlg_opt_editor('FiF options', fif_opts, subset='fif.')
dlg.store(what='load') if dlg else 0
reload_opts()
#def dlg_fif_opts
class PresetD:
keys_l = ['reex','case','word'
,'incl','excl'
,'fold','dept'
,'skip','sort','olde','frst','enco'
,'send'
,'totb','join','shtp','algn'
,'cntx','cntb','cnta']
caps_l = ['.*','aA','"w"'
,'In files','Not in files'
,'In folder','Subfolders'
,'Skip files','Sort file list','Age','Firsts','Encodings'
,'[Report] Send to tab/file'
,'[Report] Show in','[Report] Append results','[Report] Tree type','[Report] Align'
,'[Report] Show context','[Report] Context "before"','[Report] Context "after"']
yn01 = {'0':_('No'), '1':_('Yes'), _('No'):'0', _('Yes'):'1'}
@staticmethod
def desc_fif_val(fifkey, val=None):
pass; #LOG and log('fifkey, val={}',(fifkey, val))
if val is None: return ''
if False:pass
elif fifkey in ('incl','excl','fold','frst','cntb','cnta'): return val
elif fifkey in ('reex','case','word'
,'send','join','algn','cntx'): return PresetD.yn01[val] #_('Yes') if val=='1' else _('No')
elif fifkey=='totb': return totb_l[int(val)] if val in ('0', '1') else val
elif fifkey=='olde': return ('<'+val).replace('<<', '<').replace('<>', '>').replace('/', '')
pass; #log('fifkey, val={}',(fifkey, val))
val = int(val)
if False:pass
elif fifkey=='dept': return dept_l[val] if 0<=val<len(dept_l) else ''
elif fifkey=='skip': return skip_l[val] if 0<=val<len(skip_l) else ''
elif fifkey=='sort': return sort_l[val] if 0<=val<len(sort_l) else ''
elif fifkey=='enco': return enco_l[val] if 0<=val<len(enco_l) else ''
elif fifkey=='shtp': return shtp_l[val] if 0<=val<len(shtp_l) else ''
#def desc_fif_val
def __init__(self, fif):
self.fif = fif
#def PresetD.__init__
def config(self):
M,m = self.__class__,self
pset_l = copy.deepcopy(m.fif.stores.get('pset', []))
if not pset_l: return msg_status(_('No preset to config'))
for ps in pset_l:
M.upgrd(ps)
def save_close(cid, ag, data=''):
if pset_l:
ps_ind = ag.cval('prss')
ps = pset_l[ps_ind]
ps['name'] = ag.cval('name')
self._restore(ps)
msg_status(_('Options is restored from preset')+': '+ps['name'])
m.fif.stores['pset'] = pset_l #stores_main.update(stores)
open(CFG_PATH, 'w').write(json.dumps(m.fif.stores, indent=4))
return None
#def save_close
def acts(cid, ag, data=''):
if not pset_l: return {}
ps_ind = ag.cval('prss')
ps = pset_l[ps_ind]
new_name = ag.cval('name')
prss_nms = []
if ps['name'] != new_name:
ps['name'] = new_name
if False:pass
elif cid=='what':
pass; #log('ps={}',(ps))
pass; #log('what.val={}',(ag.cval('what')))
ps_vls = ag.cval('what')[1]
pass; #log('ps_vls={}',(ps_vls))
for i,k in enumerate(M.keys_l):
ps['_'+k] = 'x' if ps_vls[i]=='1' else '-'
pass; #log('ps={}',(ps))
elif cid=='mvup' and ps_ind>0 \
or cid=='mvdn' and ps_ind<len(pset_l)-1:
mv_ind = ps_ind + (-1 if cid=='mvup' else 1)
pset_l[mv_ind], \
pset_l[ps_ind] = pset_l[ps_ind], \
pset_l[mv_ind]
ps_ind = mv_ind
ps_mns = [ps['name'] for ps in pset_l]
return dict(
ctrls=[('prss',dict(items=ps_mns, val=ps_ind) )
,('mvup',dict(en=ps_ind>0) )
,('mvdn',dict(en=ps_ind<(len(pset_l)-1)) )
]
,fid='prss')
elif cid=='delt':
pset_l.pop(ps_ind)
ps_ind = min(ps_ind, len(pset_l)-1)
ps = pset_l[ps_ind] if pset_l else {}
pass; #LOG and log('ps={}',(ps))
ps_mns = [ps['name'] for ps in pset_l]
ps_its = [f('{}', M.caps_l[i] ) for i, k in enumerate(M.keys_l)] if pset_l else [' ']
ps_vas = [f('{}', M.desc_fif_val(k, ps.get(k)) ) for i, k in enumerate(M.keys_l)] if pset_l else [' ']
ps_vls = [('1' if ps['_'+k]=='x' else '0' ) for k in M.keys_l ] if pset_l else ['0']
return dict(
ctrls=[('prss',dict(items=ps_mns, val=ps_ind) )
,('name',dict( val=ps['name']) )
,('what',dict(items=ps_its, val=(-1,ps_vls)) )
,('vals',dict(items=ps_vas, val=(-1,ps_vls)) )
,('mvup',dict(en=len(pset_l)>0 and ps_ind>0) )
,('mvdn',dict(en=len(pset_l)>0 and ps_ind<(len(pset_l)-1)))
,('clon',dict(en=len(pset_l)>0) )
,('delt',dict(en=len(pset_l)>0) )
]
,fid='prss')
elif cid=='clon':
ps = pset_l[ps_ind]
psd = {k:v for k,v in ps.items()}
pset_l.insert(ps_ind, psd)
ps_mns = [ps['name'] for ps in pset_l]
return dict(
ctrls=[('prss',dict(items=ps_mns, val=ps_ind) )
,('mvup',dict(en=ps_ind>0) )
,('mvdn',dict(en=ps_ind<(len(pset_l)-1)) )
]
,fid='prss')
pass; LOG and log('no act: cid,ps_ind={}',(cid,ps_ind))
return {'fid':'prss'}
#def acts
def fill_what(cid, ag, data=''):
ps_ind = ag.cval('prss')
prss_nms= [('prss',dict(val=ps_ind))]
if pset_l:
ps_ind_p = ag.cval('prss', live=False)
pass; #LOG and log('ps_ind,ps_ind_p={}',(ps_ind,ps_ind_p))
ps_p = pset_l[ps_ind_p]
if ps_p['name']!= ag.cval('name'):
ps_p['name']= ag.cval('name')
ps_mns = [ps['name'] for ps in pset_l]
prss_nms = [('prss',dict(items=ps_mns, val=ps_ind))]
pass; #LOG and log('ps_ind={}',(ps_ind))
ps = pset_l[ps_ind] if pset_l else {}
pass; #LOG and log('ps={}',(ps))
ps_its = [f('{}', M.caps_l[i] ) for i, k in enumerate(M.keys_l)] if pset_l else [' ']
ps_vas = [f('{}', M.desc_fif_val(k, ps.get(k)) ) for i, k in enumerate(M.keys_l)] if pset_l else [' ']
ps_vls = [('1' if ps['_'+k]=='x' else '0' ) for k in M.keys_l ] if pset_l else ['0']
return dict(
ctrls=[('what',dict(items=ps_its, val=(-1,ps_vls)) )
,('vals',dict(items=ps_vas, val=(-1,ps_vls)) )
,('name',dict( val=ps['name']) )
,('mvup',dict(en=ps_ind>0) )
,('mvdn',dict(en=ps_ind<(len(pset_l)-1)) )
]+prss_nms
,fid='prss')
#def fill_what
ps_ind = 0
ps = pset_l[ps_ind] if pset_l else {}
DLG_W = 5*4+245+400
ps_mns = [ps['name'] for ps in pset_l] if pset_l else [' ']
ps_its = [f('{}', M.caps_l[i] ) for i, k in enumerate(M.keys_l)] if pset_l else [' ']
ps_vas = [f('{}', M.desc_fif_val(k, ps.get(k)) ) for i, k in enumerate(M.keys_l)] if pset_l else [' ']
ps_vls = [('1' if ps['_'+k]=='x' else '0' ) for k in M.keys_l ] if pset_l else ['0']
pass; #LOG and log('ps_mns={}',(ps_mns))
pass; #LOG and log('ps_its={}',(ps_its))
ctrls = [0
,('lprs',dict(tp='lb' ,t=5 ,l=5 ,w=245 ,cap=_('&Presets:') )) # &p
,('prss',dict(tp='lbx' ,t=5+20,h=345 ,l=5 ,w=245 ,items=ps_mns ,en=(len(pset_l)>0) ,val=ps_ind ,call=fill_what )) #
# Content
,('lnam',dict(tp='lb' ,t=5+20+345+10 ,l=5 ,w=245 ,cap=_('&Name:') )) # &n
,('name',dict(tp='ed' ,t=5+20+345+30 ,l=5 ,w=245 ,en=(len(pset_l)>0) ,val=ps.get('name', '') )) #
# Acts
,('mvup',dict(tp='bt' ,t=435 ,l=5 ,w=120 ,cap=_('Move &up') ,en=(len(pset_l)>1) and ps_ind>0 ,call=acts )) # &u
,('mvdn',dict(tp='bt' ,t=460 ,l=5 ,w=120 ,cap=_('Move &down'),en=(len(pset_l)>1) ,call=acts )) # &d
,('clon',dict(tp='bt' ,t=435 ,l=5*2+120 ,w=120 ,cap=_('Clon&e') ,en=(len(pset_l)>0) ,call=acts )) # &e
,('delt',dict(tp='bt' ,t=460 ,l=5*2+120 ,w=120 ,cap=_('Dele&te') ,en=(len(pset_l)>0) ,call=acts )) # &t
#
,('lwha',dict(tp='lb' ,t=5 ,l=260 ,w=180 ,cap=_('&What to restore:') )) # &w
,('what',dict(tp='clx' ,t=5+20,h=400 ,l=260 ,w=180 ,items=ps_its ,en=T ,val=(-1,ps_vls),call=acts ))
,('lval',dict(tp='lb' ,t=5 ,l=260+180+1,w=220-1,cap=_('With values:') )) # &
,('vals',dict(tp='clx' ,t=5+20,h=400 ,l=260+180+1,w=220-1,items=ps_vas ,en=F ,val=(-1,ps_vls) ))
#
,('!' ,dict(tp='bt' ,t=435 ,l=DLG_W-5-100,w=100,cap=_('Apply') ,def_bt=True ,call=save_close)) # &
,('-' ,dict(tp='bt' ,t=460 ,l=DLG_W-5-100,w=100,cap=_('Cancel') ,call=LMBD_HIDE ))
][1:]
DlgAgent(form =dict(cap=_('Presets'), w=DLG_W, h=490)
,ctrls =ctrls
,fid ='prss'
#,options={'gen_repro_to_file':'repro_prs_config.py'}
).show()
return None
#def config
def save(self):
M,m = self.__class__,self
m.fif.copy_vals(m.fif.ag)
pset_l = m.fif.stores.get('pset', [])
totb_i = m.fif.totb_i if 0<m.fif.totb_i<4+len(m.fif.stores.get('tofx', [])) else 1 # "tab:" skiped
totb_v = m.fif.totb_l[totb_i]
invl_l = (m.fif.reex01,m.fif.case01,m.fif.word01,
m.fif.incl_s,m.fif.excl_s,
m.fif.fold_s,m.fif.dept_n,
m.fif.skip_s,m.fif.sort_s,m.fif.olde_s,m.fif.frst_s,m.fif.enco_s,
m.fif.send_s,
totb_v,m.fif.join_s,m.fif.shtp_s,m.fif.algn_s,m.fif.cntx_s,m.fif.cntx_b,m.fif.cntx_a)
ps_its = [f('{}', M.caps_l[i] ) for i, k in enumerate(M.keys_l)]
ps_vas = [f('{}', M.desc_fif_val(k, invl_l[i]) ) for i, k in enumerate(M.keys_l)]
send_i = M.keys_l.index('send')
what_vs = ['1']*len(M.keys_l)
if m.fif.send_s=='0':
what_vs[send_i+1:] = ['0']*(len(what_vs)-send_i-1)
if not m.fif.incl_s: what_vs[M.keys_l.index('incl')] = '0'
if not m.fif.excl_s: what_vs[M.keys_l.index('excl')] = '0'
if not m.fif.fold_s: what_vs[M.keys_l.index('fold')] = '0'
if '0'==m.fif.frst_s: what_vs[M.keys_l.index('frst')] = '0'
btn,vals,*_t = dlg_wrapper(_('Save preset'), GAP+400+GAP,GAP+500+GAP, #NOTE: dlg-pres-new
[dict( tp='lb' ,t=GAP ,l=GAP ,w=300 ,cap=_('&Name:') ) # &n
,dict(cid='name',tp='ed' ,t=GAP+20 ,l=GAP ,w=400 ) #
,dict( tp='lb' ,t=GAP+55 ,l=GAP ,w=300 ,cap=_('&What to save:') ) # &w
,dict(cid='what',tp='clx' ,t=GAP+75,h=390 ,l=GAP ,w=180 ,items=ps_its )
,dict( tp='lb' ,t=GAP+55 ,l=GAP+180+1 ,w=220-1,cap=_('With values:') ) # &
,dict(cid='vals',tp='clx' ,t=GAP+75,h=390 ,l=GAP+180+1 ,w=220-1,items=ps_vas ,en=F )
,dict(cid='!' ,tp='bt' ,t=GAP+500-28 ,l=GAP+400-170 ,w=80 ,cap=_('OK') ,def_bt=True) # &
,dict(cid='-' ,tp='bt' ,t=GAP+500-28 ,l=GAP+400-80 ,w=80 ,cap=_('Cancel') )
], dict(name=f(_('#{}: "{}" in "{}"'), 1+len(pset_l), m.fif.incl_s, m.fif.fold_s)
,what=(0 ,what_vs)
,vals=(-1,what_vs)), focus_cid='name')
pass; #LOG and log('vals={}',vals)
if btn is None or btn=='-': return None
ps_name = vals['name']
sl,vals = vals['what']
pass; #LOG and log('vals={}',vals)
ps = odict([('name',ps_name)])
for i, k in enumerate(M.keys_l):
if vals[i]=='1':
ps['_'+k] = 'x'
ps[ k] = invl_l[i]
else:
ps['_'+k] = '-'
pass; #LOG and log('ps={}',(ps))
pset_l += [ps]
m.fif.stores['pset'] = pset_l #stores_main.update(stores)
open(CFG_PATH, 'w').write(json.dumps(m.fif.stores, indent=4))
msg_status(_('Options is saved to preset: ')+ps['name'])
return None
#def save
def _restore(self, ps):
M,m = self.__class__,self
for i, k in enumerate(M.keys_l):
if ps.get('_'+k, '')!='x': continue
if 0:pass
elif k=='reex': m.fif.reex01 = ps[k]
elif k=='case': m.fif.case01 = ps[k]
elif k=='word': m.fif.word01 = ps[k]
elif k=='incl': m.fif.incl_s = ps[k]
elif k=='excl': m.fif.excl_s = ps[k]
elif k=='fold': m.fif.fold_s = ps[k]
elif k=='dept': m.fif.dept_n = ps[k]
elif k=='skip': m.fif.skip_s = ps[k]
elif k=='sort': m.fif.sort_s = ps[k]
elif k=='olde': m.fif.olde_s = ps[k]
elif k=='frst': m.fif.frst_s = ps[k]
elif k=='enco': m.fif.enco_s = ps[k]
elif k=='send': m.fif.send_s = ps[k]
elif k=='join': m.fif.join_s = ps[k]
elif k=='shtp': m.fif.shtp_s = ps[k]
elif k=='algn': m.fif.algn_s = ps[k]
elif k=='cntx': m.fif.cntx_s = ps[k]
elif k=='cntb': m.fif.cntx_b = ps[k]
elif k=='cnta': m.fif.cntx_a = ps[k]
elif k=='totb':
totb_v = ps[k]
m.fif.totb_i = m.fif.totb_l.index(totb_v) if totb_v in m.fif.totb_l else \
totb_v if totb_v in (0, 1) else \
1
#def _restore
def ind4rest(self, ps_ind):
M,m = self.__class__,self
m.fif.copy_vals(m.fif.ag)
pset_l = m.fif.stores.get('pset', [])
if ps_ind>=len(pset_l): return None
ps = M.upgrd(pset_l[ps_ind])
m._restore(ps)
m.fif.store()
msg_status(_('Options is restored from preset: ')+ps['name'])
return True
#def ind4rest
@staticmethod
def upgrd(ps:list)->list:
if 'olde' not in ps:
ps['olde'] = '0/d'
ps['_olde'] = 'x'
if 'cntb' not in ps:
ps['cntb'] = 1
ps['_cntb'] = 'x'
ps['cnta'] = 1
ps['_cnta'] = 'x'
if 'send' not in ps:
ps['send'] = '1'
ps['_send'] = 'x'
if '_aa_' not in ps:
for k in ps:
if k[0]=='_' and ps[k]=='_':
ps[k] = '-'
return ps
_aa = ps.pop('_aa_', '')
_if = ps.pop('_if_', '')
_fo = ps.pop('_fo_', '')
_fn = ps.pop('_fn_', '')
_rp = ps.pop('_rp_', '')
ps['_reex'] = 'x' if _aa else '-'
ps['_case'] = 'x' if _aa else '-'
ps['_word'] = 'x' if _aa else '-'
ps['_incl'] = 'x' if _if else '-'
ps['_excl'] = 'x' if _if else '-'
ps['_fold'] = 'x' if _if else '-'
ps['_dept'] = 'x' if _if else '-'
ps['_skip'] = 'x' if _fn else '-'
ps['_sort'] = 'x' if _fn else '-'
ps['_frst'] = 'x' if _fn else '-'
ps['_enco'] = 'x' if _fn else '-'
ps['_totb'] = 'x' if _rp else '-'
ps['_join'] = 'x' if _rp else '-'
ps['_shtp'] = 'x' if _rp else '-'
ps['_algn'] = 'x' if _rp else '-'
ps['_cntx'] = 'x' if _rp else '-'
return ps
#def upgrd
#class PresetD
_TREE_BODY = _(r'''
If report will be sent to tab
[x] Send
then option "Tree type" in dialog "{morp}" allows to set:
{shtp}
''')
#_KEYS_TABLE = open(os.path.dirname(__file__)+os.sep+r'readme'+os.sep+f('help hotkeys.txt') , encoding='utf-8').read()
_KEYS_TABLE = _(r'''
┌────────────────────────────┬──────────────┬────────────────────────────┬───────────────────────────────────────────┐
│ Command │ Hotkey │ Trick │ Comment │
╞════════════════════════════╪══════════════╪════════════════════════════╪═══════════════════════════════════════════╡
│ Find │ Enter │ │ If focus not in Results/Source │
│ Count matches │ Alt+T │ │ │
│ Find filenames │ Ctrl+T │ │ │
├────────────────────────────┼──────────────┼────────────────────────────┼───────────────────────────────────────────┤
│ Focus to Results │ Ctrl+Enter │ │ If focus not in Results/Source │
│ Open found fragment │ Enter │ │ If focus in Results. Selects the fragment │
│ Close and go to found │ Ctrl+Enter │ │ If focus in Results. Selects the fragment │
│ Close and go to found │ Ctrl+Enter │ │ If focus in Source. Restores selection │
│ Fold Results branch │ Ctrl+= │ │ If focus in Results │
├────────────────────────────┼──────────────┼────────────────────────────┼───────────────────────────────────────────┤
│ In current file │ Ctrl+Shift+C │ Shift+Сlick "Current" │ │
│ In all tabs │ │ Ctrl +Сlick "Current" │ │
│ In current tab │ │ Ctrl+Shift+Сlick "Current" │ │
│ Choose file │ Ctrl+B │ Shift+Сlick "Browse" │ │
│ Depth "Only" │ Alt+Y │ Ctrl+Num0 │ │
│ Depth "+1 level" │ Alt+! │ Ctrl+Num1 │ │
│ Depth "All" │ Alt+L │ Ctrl+Num9 │ │
├────────────────────────────┼──────────────┼────────────────────────────┼───────────────────────────────────────────┤
│ Save values as preset │ Ctrl+S │ │ │
│ Presets dialog │ Ctrl+Alt+S │ │ │
│ Use Preset #1(..#5) │ Ctrl+1(..5) │ │ Others from menu/dialog │
│ Use Layout #1(..#5) │ Alt+1(..5) │ │ Others from menu │
├────────────────────────────┼──────────────┼────────────────────────────┼───────────────────────────────────────────┤
│ ±"Not in"/±"Replace" │ Alt+V │ │ 4-states loop to show/hide │
│ Engine options │ Ctrl+E │ │ │
│ Configure vert. alignments │ │ Ctrl+Сlick "=" │ │
├────────────────────────────┼──────────────┼────────────────────────────┼───────────────────────────────────────────┤
│ Call CudaText's "Find" │ Ctrl+F │ │ With transfer patern/.*/aA/"w" │
│ Call CudaText's "Replace" │ Ctrl+R │ │ With transfer paterns/.*/aA/"w" │
│ Dialog "Help" │ Alt+H │ │ │
└────────────────────────────┴──────────────┴────────────────────────────┴───────────────────────────────────────────┘
''')
#_TIPS_BODY = open(os.path.dirname(__file__)+os.sep+r'readme'+os.sep+f('help hints.txt') , encoding='utf-8').read()
_TIPS_BODY = _(r'''
• ".*" - Option "Regular Expression".
It allows to use in field "Find what" special symbols:
. any character
\d digit character (0..9)
\w word-like character (digits, letters, "_")
In field "Replace with":
\1 to insert first found group,
\2 to insert second found group, ...
See full documentation on page
docs.python.org/3/library/re.html
• "w" - {word}
——————————————————————————————————————————————
• Values in fields "{incl}" and "{excl}" can contain
? for any single char,
* for any substring (may be empty),
[seq] any character in seq,
[!seq] any character not in seq.
Note:
* matches all names,
*.* doesn't match all.
• Values in fields "{incl}" and "{excl}" can filter subfolder names
if they start with "/".
Example.
{incl:12}: /a* *.txt
{excl:12}: /ab*
{fold:12}: c:/root
Depth : All
Search will consider all *.txt files in folder c:/root
and in all subfolders a* except ab*.
• Set special value "{tags}" (in short <t> or <Tabs>) for field "{fold}" to search in opened documents.
Fields "{incl}" and "{excl}" will be used to filter tab titles, in this case.
To search in all tabs, use mask "*" in field "{incl}".
See also: menu items under button "=", "Scope".
• Set special value "{proj}" (in short <p>) for field "{fold}" to search in project files.
See also: menu items under button "=", "Scope".
——————————————————————————————————————————————
• "Age" (advanced search options).
{olde}
• "First" (advanced search options).
{frst}
——————————————————————————————————————————————
• Long-term searches can be interrupted by ESC.
Search has three stages:
picking files,
finding fragments,
reporting.
ESC stops any stage.
When picking and finding, ESC stops only this stage, so next stage begins.
——————————————————————————————————————————————
• Use right click or Context keyboard button
to see context menu over these elements
"Find", "Replace", "Current", "Browse", Depth combobox
——————————————————————————————————————————————
You are welcome to plugin forum. See bottom link.
''')
RE_DOC_URL = 'https://docs.python.org/3/library/re.html'
GH_ISU_URL = 'https://github.com/kvichans/cuda_find_in_files/issues'
def dlg_fif_help(fif, stores=None):
stores = {} if stores is None else stores
TIPS_BODY =_TIPS_BODY.strip().format(
word=word_h
, incl=fif.caps['incl']
, excl=fif.caps['excl']
, fold=fif.caps['fold']
, olde=olde_h
, frst=frst_h
, tags=IN_OPEN_FILES
, proj=IN_PROJ_FOLDS)
TREE_BODY =_TREE_BODY.strip().format(
morp=morp_h
, shtp=shtp_h)
KEYS_TABLE = _KEYS_TABLE.strip('\n\r')
c2m = 'mac'==get_desktop_environment() #or True
KEYS_TABLE = _KEYS_TABLE.strip('\n\r').replace('Ctrl+', 'Meta+') if c2m else KEYS_TABLE
page = stores.get('page', 0)
ag_hlp = DlgAgent(
form =dict( cap =_('"Find in Files" help')
,w = 960+10
,h = 580+10
,resize = True
)
, ctrls = [0
,('tabs',dict(tp='pgs' ,l=5,w=960
,t=5,h=580 ,a='lRtB' ,items=[_('Hotkeys+Tricks')
,_('Hints')
,_('Tree types')] ,val=page ))
# ,t=5,h=580 ,a='lRtB' ,items='Hotkeys+Tricks\tHints\tTree types' ,val=page ))
,('keys',dict(tp='me' ,p='tabs.0' ,ali=ALI_CL ,ro_mono_brd='1,1,1' ,val=KEYS_TABLE ))
,('tips',dict(tp='me' ,p='tabs.1' ,ali=ALI_CL ,ro_mono_brd='1,1,1' ,val=TIPS_BODY ))
# ,('porg',dict(tp='llb' ,p='tabs.1' ,ali=ALI_BT ,cap=_('Reg.ex. on python.org') ,url=RE_DOC_URL ))
,('tree',dict(tp='me' ,p='tabs.2' ,ali=ALI_CL ,ro_mono_brd='1,1,1' ,val=TREE_BODY ))
,('porg',dict(tp='llb' ,p='tabs.1' ,ali=ALI_BT ,cap=_('Plugin forum') ,url=GH_ISU_URL ))
][1:]
, fid = 'tabs'
#,options={'gen_repro_to_file':'repro_dlg_fif_help.py'}
)
def do_exit(ag):
pass
# page = 0 if ag.cattr('keys', 'vis') else 1 if ag.cattr('tips', 'vis') else 2
page = ag.cval('tabs')
stores['page'] = page