-
Notifications
You must be signed in to change notification settings - Fork 7
/
cd_ext_find_repl.py
2077 lines (1855 loc) · 93.5 KB
/
cd_ext_find_repl.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)
Alexey Torgashin (CudaText)
Version:
'1.7.65 2024-07-25'
ToDo: (see end of file)
'''
import re, os, sys, webbrowser
from operator import itemgetter
import cudatext as app
from cudatext import ed
from cudatext_keys import *
import cudatext_cmd as cmds
import cudax_lib as apx
from .cd_kv_base import * # as part of this plugin
from .cd_kv_dlg import * # as part of this plugin
try:# I18N
_ = get_translation(__file__)
except:
_ = lambda p:p
pass; import cudatext_keys
pass; _log4mod = LOG_FREE # Order log in the module
#d = dict
d = dcta # To use keys as attrs: o=dcta(a=b); x=o.a; o.a=x
C1 = chr(1)
def flatten(xs):
for x in xs:
if isinstance(x, (tuple, list)):
for xx in flatten(x): yield xx
else: yield x
msg_box = lambda tx, bts_ico=app.MB_OK: app.msg_box( tx, bts_ico)
msg_box_ex = lambda cp, tx, bts=['OK'] : app.msg_box_ex(cp, tx, bts, app.MB_ICONINFO)
class RiL:
HIST_KEY= 'find.replace_in_lines'
FORM_CB = _('Replace all in Lines') # RaiL
FORM_C = FORM_CB+' '+_('(Enter in first field to find)') # RaiL
HELP_TX = _('''
• [Shift+]Enter in "Find" field to search [previous] next fragment.
• Ctlr+Down/Up to copy pattern lower/upper.
• Command "Restore initial selection" (Shift+Esc) tries to restore only first of initial carets.
• RegExp engine from CudaText is used. Names of RegEx sub-groups are $1, $2...
''').strip()
REEX_H = _('Regular expression'
'\rRegEx engine from CudaText is used')
CASE_H = _('Case sensitive')
WORD_H = _('Whole words')
SETS_H = _('Kit of pairs to replace'
'\rAlt+Left/Right - load previous/next pair'
'\rAlt+Shift+Left/Right - activate previous/next kit')
WHAT_H = _('Pattern to search'
'\rEnter - to find next'
'\rShift+Enter - to find previous')
REPL_H = _('Pattern to replace'
'\rRegExp sub-groups are $1, $2, ...')
# REPL_H = _('Pattern to replace\rEnter - to replace next')
RPLA_H = _('Replace all')
RPLS_H = _('Replace all for all pairs from the kit')
DEF_SET = _('<def>')
CL_WARN = apx.html_color_to_int('#A00000')
CL_INFO = apx.html_color_to_int('#808080')
_stus = ''
@staticmethod
def msg_d(s,t='i',a=0):
RiL._stus = RiL._stus+s if a else s
return d(cap=RiL._stus, font_color=RiL.CL_INFO if t=='i' else RiL.CL_WARN)
# msg_d = lambda s,t='i',a=0: d(cap=s, font_color=RiL.CL_INFO if t=='i' else RiL.CL_WARN)
msg_s = lambda s,t='i',a=0: d(stus=RiL.msg_d(s,t,a))
msg = lambda s,t='i',a=0: d(ctrls=RiL.msg_s(s,t,a) )
msg_f = lambda f,s,t='i',a=0: d(ctrls=RiL.msg_s(s,t,a), fid=f)
st2item = lambda n, st: f('&{}: {} (#{})', n+1, st.nm, len(st.ps))
st_pr_rc= lambda pr: ( ('r' if pr.re else '')
+ ('c' if pr.cs else '')
+ ('w' if pr.wd else '') )
st_pr_cw= lambda pr: ( ('[' if pr.re or pr.cs or pr.wd else '')
+ ('.' if pr.re else '')
+ ('c' if pr.cs else '')
+ ('w' if pr.wd else '')
+ ('] ' if pr.re or pr.cs or pr.wd else '') )
st_pr = lambda pr: f('{}"{}" -> "{}"'
, RiL.st_pr_cw(pr)
, pr.f, pr.r)
st_pr_n = lambda n, pr: f('{}: {}', n+1, RiL.st_pr(pr))
st_pr_mn= lambda n, pr: re.sub(r'^(\d*)(\d: )', r'\1&\2', RiL.st_pr_n(n, pr))
sets_items = lambda sts: [RiL.st2item(n,st).replace('&', '') for n,st in enumerate(sts)]
def __init__(self):
M,m = type(self),self
pass; log4fun=2 # Order log in the function
m.ed_crts = ed.get_carets() # Carets at start/activate
m.opts = d(reex=False,case=False,word=False
, what='' # Last value in "what"
, whtl=[] # List values in "what"
, repl='' # Last value in "repl"
, rpll=[] # List values in "repl"
, sets=[d(nm=M.DEF_SET,ps=[])] # ps=[d(f='a', r='b', re=False, cs=False, wd=False)]
, aset=0 # Last active in "sets"
, usel=False # Use ed sel
, fitn=False # Autofit Replace pattern
, anxt=False # Autoload next pair atfer ReplAll
, pfid='what') # Last fid
m.opts.update(get_hist(M.HIST_KEY, m.opts, object_pairs_hook=dcta))
pass; #log("m.opts={}",(m.opts)) if log4fun else 0
pass; #log("m.opts.sets={}",len(m.opts.sets)) if log4fun else 0
#def __init__
def on_exit(self, ag):
M,m = type(self),self
m.opts.pfid = ag.focused()
pass; #log("m.opts={}",(m.opts))
set_hist(M.HIST_KEY, deep_upd((m.opts, ag.vals(['reex','case','word','what','repl']), {'aset':ag.val('sets')})))
#def on_exit
def show(self):
M,m = type(self),self
pass; log4fun=0 # Order log in the function
# m.ed_crts = ed.get_carets() # Carets at start/activate
# m.opts = d(reex=False,case=False,word=False
# , what='' # Last value in "what"
# , whtl=[] # List values in "what"
# , repl='' # Last value in "repl"
# , rpll=[] # List values in "repl"
# , sets=[d(nm=M.DEF_SET,ps=[])] # ps=[d(f='a', r='b', re=False, cs=False, wd=False)]
# , aset=0 # Last active in "sets"
# , usel=False # Use ed sel
# , fitn=False # Autofit Replace pattern
# , anxt=False # Autoload next pair atfer ReplAll
# , pfid='what') # Last fid
# m.opts.update(get_hist(M.HIST_KEY, m.opts, object_pairs_hook=dcta))
# pass; log("m.opts={}",(m.opts)) if log4fun else 0
edsel = ed.get_text_sel()
if m.opts.usel and edsel:
m.opts.what = edsel
if '\r' in m.opts.what or '\n' in m.opts.what:
m.opts.what = ''
elif m.opts.fitn:
repl = m.work('offer_repl', m.opts.what)
pass; #log("repl={}",(repl))
if repl:
m.opts.repl = repl
bttn_h = get_gui_height('bttn')
sits = M.sets_items(m.opts.sets)
WIN_MAC = (get_desktop_environment() in ('win', 'mac'))
YG = 0 if WIN_MAC else 3
ctrls = d(
reex=d(tp='chbt',tid='menu' ,x=80+38*0 ,w=38 ,cap='&.*' ,hint=M.REEX_H # Alt+.
),case=d(tp='chbt',tid='menu' ,x=80+38*1 ,w=38 ,cap='&cC' ,hint=M.CASE_H # Alt+C
),word=d(tp='chbt',tid='menu' ,x=80+38*2 ,w=38 ,cap='"&w"' ,hint=M.WORD_H # Alt+W
),stu_=d(tp='bvel',y = 5 ,x=80+38*3+5,r=-52+4,h=bttn_h ,ex0='1' ,a='r>'
),stus=d(tp='labl',tid='menu' ,x=80+38*3+9,r=-52 ,cap='' ,a='r>'
),menu=d(tp='bttn',y = 5 ,x=-5-38 ,w=38 ,cap='&=' ,a='>>' # Alt+=
),wha_=d(tp='labl',tid='what' ,x= 5 ,w=80-10,cap='>*'+_('&Find'),hint=M.WHAT_H # Alt+F
),what=d(tp='cmbx',y =35+YG*1,x=80 ,r=-48 ,items=m.opts.whtl ,a='r>' #
),rep_=d(tp='labl',tid='repl' ,x= 5 ,w=80-10,cap='>'+_('&Replace'),hint=M.REPL_H # Alt+R
),repl=d(tp='cmbx',y =65+YG*2,x=80 ,r=-48 ,items=m.opts.rpll ,a='r>' #
),rpla=d(tp='bttn',tid='repl' ,x=-5-38 ,w=38 ,cap=_('&All') ,hint=M.RPLA_H ,a='>>' # Alt+A
),set_=d(tp='labl',tid='sets' ,x= 5 ,w=80-10,cap='>'+_('&Kits') ,hint=M.SETS_H # Alt+K
),sets=d(tp='cmbr',y =95+YG*3,x=80 ,r=-48 ,items=sits ,a='r>' #
),rpls=d(tp='bttn',tid='sets' ,x=-5-38 ,w=38 ,cap=_('A&LL') ,hint=M.RPLS_H ,a='>>' # Alt+L
))
ctrls.menu.on_menu = m.do_menu
ctrls.menu.on = m.do_menu
for ctrl in ctrls.values():
if ctrl.tp not in ('cmbx', 'cmbr'): # Tab stops only in these
ctrl.sto = False
if ctrl.tp in ('chbt', 'bttn', 'cmbr') and 'on' not in ctrl:
ctrl.on = m.do_acts
ag = DlgAg(
form =d(cap=M.FORM_C, w=500, h=125+YG*3, h_max=125+YG*3 # Only horz resize
,on_key_down=m.do_keys
,frame='resize')
, ctrls =ctrls
, fid =m.opts.pfid
, vals =d(**{k:m.opts[k] for k in ('reex','case','word')}
, what=m.opts.what
, repl=m.opts.repl
, sets=m.opts.aset)
, opts =d(negative_coords_reflect=True)
)
pass; #ag.gen_repro_code('repro_dlg_ril.py')
ag.show(on_exit=self.on_exit)
#def show
def do_menu(self, ag, aid, data=''):
M,m = type(self),self
pass; #return []
sets = m.opts.sets
cset = sets[m.opts.aset]
nm_sets=[
d( cap=M.st2item(n, st) ,key=(f'Ctrl+{n+1}' if n<9 else '') ,sub=[(
),d(tag=f'stAC{n}' ,cap=f(_('Activate kit "{}"'),st.nm) ,key=(f'Ctrl+{n+1}' if n<9 else '')
),d(tag=f'stRA{n}' ,cap=M.RPLS_H+'...' ,key=(f'Ctrl+Shift+{n+1}' if n<9 else '')
),d( cap='-'
)][1:]+[
d(tag=f'stLP{n}_{np}'
,cap=M.st_pr_mn(np, pr)) for np,pr in enumerate(st.ps)]
) for n,st in enumerate(sets)
]+[(
),d( cap='-'
),d(tag='stse' ,cap=_('Edit kits...') ,keys='Ctrl+K'
),d(tag='impt' ,cap=_('&Import from Replace history...') ,en=app.app_api_version()>='1.0.347'
),d( cap=_('Rem&ove kit') ,en=bool(sets) ,sub=[
d(tag=f'stRM{n}',cap=M.st2item(n, st)) for n,st in enumerate(sets)]
),d(tag='stsw' ,cap=_('&Change kits order...') ,en=len(sets)>1
)][1:]
rpls_c = f(_('Replace A&LL for all pairs (#{}) of the kit...'), len(cset.ps))
rpls_sel_c = _('Replace A&LL for all pairs of a selected kit...')
ag.show_menu([(
),d(tag='rpla' ,cap=_('Replace &all') ,key='Alt+A'
),d(tag='rpls' ,cap=rpls_c ,key='Alt+L'
),d(tag='arps' ,cap=rpls_sel_c ,key='Ctrl+Shift+L'
),d( cap='-'
),d(tag='stnw' ,cap=_('Create &new kit...') ,key='Ctrl+N'
),d(tag='prsv' ,cap=_('&Save pattern pair to kit') ,key='Ctrl+S'
),d(tag='sted' ,cap=_('&Edit kit...') ,key='Ctrl+E'
),d( cap=_('&Kits') ,sub=nm_sets
),d( cap='-'
),d(tag='prpr' ,cap=_('Load previous kit pair') ,key='Ctrl+Left' ,en=len(cset.ps)>0
),d(tag='prnx' ,cap=_('Load next kit pair') ,key='Ctrl+Right' ,en=len(cset.ps)>0
),d(tag='stpr' ,cap=_('Load previous kit') ,key='Ctrl+Shift+Left'
),d(tag='stnx' ,cap=_('Load next kit') ,key='Ctrl+Shift+Right'
),d( cap='-'
),d(tag='hide' ,cap=_('Hide dialog') ,key='Esc'
),d(tag='rest' ,cap=_('Hide dialog and restore selection &=') ,key='Shift+Esc'
),d(tag='help' ,cap=_('&Help...')
),d(tag='guid' ,cap=_('Help - &show guide in browser')
),d( cap='-'
),d(tag='fndp' ,cap=_('Find &previous') ,key='Shift+Enter'
),d(tag='fndn' ,cap=_('F&ind next') ,key='Enter'
# ),d(tag='rprv' ,cap=_('Replace previous')
# ),d(tag='rnxt' ,cap=_('Replace next')
),d( cap='-'
),d(tag='cpdn' ,cap=_('Copy down: Find->Replace') ,key='Ctrl+Down'
),d(tag='cpup' ,cap=_('Copy up: Replace->Find') ,key='Ctrl+Up'
),d( cap='-'
),d(tag='fapp' ,cap=_('Move to app Find dialog') ,key='Ctrl+F'
),d(tag='rapp' ,cap=_('Move to app Replace dialog') ,key='Ctrl+R'
),d( cap='-'
),d( cap=_('=== Options ===') ,en=False
),d(tag='usel' ,cap=_('Use &selection from document') ,ch=m.opts.usel
),d(tag='fitn' ,cap=_('Auto-fit Replace pattern on start and on Next pair') ,ch=m.opts.fitn
),d(tag='anxt' ,cap=_('Load next pair after "Replace all"') ,ch=m.opts.anxt
)][1:]
, aid
, cmd4all=m.do_acts
)
return d(fid='what')
#def do_menu
def do_keys(self, ag, key, data=''):
pass; log4fun=-1
M,m = type(self),self
scam = data if data else ag.scam()
fid = ag.focused()
ckey1 = str(int(chr(key))-1) if ord('1')<=key<=ord('9') else ''
skey = (scam,key)
skef = (scam,key,fid)
pass; #log("scam,key={}",(scam,get_const_name(key, module=cudatext_keys)))
into = lambda sk, scam, bgn, end: (scam, ord(bgn) if str==type(bgn) else bgn)<=sk<=(scam, ord(end) if str==type(end) else end)
upd = {}
if 0:pass #NOTE: do_keys
elif skey== ( 's',VK_ESCAPE): upd=m.do_acts(ag, 'rest') # Shift+Esc
elif skey== ( 'c',ord('F')): upd=m.do_acts(ag, 'fapp') # Ctrl+F
elif skey== ( 'c',ord('R')): upd=m.do_acts(ag, 'rapp') # Ctrl+R
elif skey== ( 'c',ord('S')): upd=m.do_acts(ag, 'prsv') # Ctrl+S
elif skey== ( 'c',ord('Ы')): upd=m.do_acts(ag, 'prsv') # Ctrl+Ы (ru)
elif skey== ( 'c',ord('E')): upd=m.do_acts(ag, 'sted') # Ctrl+E
elif skey== ( 'c',ord('У')): upd=m.do_acts(ag, 'sted') # Ctrl+У (ru)
elif skey== ( 'c',ord('K')): upd=m.do_acts(ag, 'stse') # Ctrl+K
elif skey== ( 'c',ord('N')): upd=m.do_acts(ag, 'stnw') # Ctrl+N
elif skey== ( 'c',ord('Т')): upd=m.do_acts(ag, 'stnw') # Ctrl+Т (ru)
elif skey== ('sc',ord('L')): upd=m.do_acts(ag, 'arps') # Shift+Ctrl+L
elif skey== ('sc',ord('Д')): upd=m.do_acts(ag, 'arps') # Shift+Ctrl+Д (ru)
elif into(skey, 'c', '1','9'): upd=m.do_acts(ag, 'stAC'+ckey1) # Ctrl+1..9
elif into(skey, 'sc', '1','9'): upd=m.do_acts(ag, 'stRA'+ckey1) # Ctrl+Shift+1..9
elif skey== ( 'c',VK_UP): upd=m.do_acts(ag, 'cpup') # Ctrl+Up
elif skey== ( 'c',VK_DOWN): upd=m.do_acts(ag, 'cpdn') # Ctrl+Dn
elif skey== ( 'c',VK_RIGHT): upd=m.do_acts(ag, 'prnx') # Ctrl+RT
elif skey== ( 'c',VK_LEFT): upd=m.do_acts(ag, 'prpr') # Ctrl+LF
elif skey== ('sc',VK_RIGHT): upd=m.do_acts(ag, 'stnx') # Shift+Ctrl+RT
elif skey== ('sc',VK_LEFT): upd=m.do_acts(ag, 'stpr') # Shift+Ctrl+LF
elif skef== ( '',VK_ENTER,'what'): upd=m.do_acts(ag, 'fndn') # Enter on what
elif skef== ( 's',VK_ENTER,'what'): upd=m.do_acts(ag, 'fndp') # Shift+Enter on what
# elif skef== ( '',VK_ENTER,'repl'): upd=m.do_acts(ag, 'rpln') # Enter on repl
# elif skef== ( 's',VK_ENTER,'repl'): upd=m.do_acts(ag, 'rplp') # Shift+Enter on repl
else: return []
pass; log__('upd={}',(upd) ,__=(log4fun,)) if _log4mod>=0 else 0
ag.update(upd)
pass; log__("break event",() ,__=(log4fun,)) if _log4mod>=0 else 0
return False
#def do_keys
@staticmethod
def core_hist_ps():
if app.app_api_version()<'1.0.347': return []
fnd_props = app.app_proc(app.PROC_GET_FINDER_PROP, '')
f_hist = fnd_props.get('find_h', [])
r_hist = fnd_props.get('rep_h' , [])
return [d(f=f, r=r, re=fnd_props['op_regex_d'], cs=fnd_props['op_case_d'], wd=fnd_props['op_word_d'])
for f,r in zip(f_hist, r_hist)]
def do_acts(self, ag, aid, data='', _recall=False, add_msg=False):
"""
reex case word
fapp rapp
rest hide help usel anxt
cpdn cpup
stRM stRN stAC stsw
sets stpr stnx prpr prnx sted stnw prsv impt
stRA stLP
rpla rpls
"""
M,m = type(self),self
pass; log4fun=0 # Order log in the function
pass; log("aid, data={}",(aid, data)) if log4fun else 0
# Copy values from form to m.opts
if not _recall:
m.opts.update(ag.vals(['reex','case','word','what','repl']))
m.opts.aset = ag.val('sets')
ag.update(M.msg('')) if not add_msg else 0
if aid in ('reex','case','word'): # Fit focus only
return d(fid='what')
# Hide dlg
tag = aid
if tag in ('fapp'
,'rapp'):
ag.opts['on_exit_focus_to_ed'] = None
app.app_proc(app.PROC_SET_FINDER_PROP, dict(
find_d = ag.val('what')
, rep_d = ag.val('repl')
, op_regex_d = ag.val('reex')
, op_case_d = ag.val('case')
, op_word_d = ag.val('word')
))
ag.hide()
ed.cmd(cmds.cmd_DialogFind if tag=='fapp' else cmds.cmd_DialogReplace)
return None
if tag=='rest': return (ed.set_caret(*m.ed_crts[0]) , None)[1]
if tag=='hide': return None
# Help
if tag=='guid': return (webbrowser.open_new_tab(os.path.dirname(__file__)+os.sep+'readme/batch_replacements.html'), [])[1]
if tag=='help': return (msg_box_ex(M.FORM_CB, M.HELP_TX), [])[1]
if tag in ('usel'
,'fitn'
,'anxt'): m.opts[tag] = not m.opts[tag]; return []
if tag=='cpdn' and \
ag.val('what'): return d(ctrls=d(repl=d(val=ag.val('what'))))
if tag=='cpup'and \
ag.val('repl'): return d(ctrls=d(what=d(val=ag.val('repl'))))
if tag =='arps': # Select kit to ALL
# nms = [st.nm for st in m.opts.sets]
# pass; log("ikit,nms={}",(ikit,nms))
# ikit= get_hist(M.HIST_KEY+'.prev_kit_pos', -1)
# ikit= app.dlg_menu(app.DMENU_LIST, '\n'.join([
# st.nm for st in m.opts.sets
# ]) , caption=_('Select kit to Replace ALL')
# , focused=ikit
# )
ikit= get_hist(M.HIST_KEY+'.prev_kit_pos', -1)
ikit= -1 if ikit is None else ikit
nms = [st.nm for st in m.opts.sets]
pass; #log("ikit,nms={}",(ikit,nms))
ikit= app.dlg_menu(app.DMENU_LIST
, nms
, caption=_('Select kit to Replace ALL')
, focused=ikit
)
if ikit is None: return []
set_hist(M.HIST_KEY+'.prev_kit_pos', ikit)
return m.do_acts(ag, f'stRA{ikit}', _recall=True, add_msg=True)
if(tag =='rpls' # Replace all from active kit
or tag[:4]=='stRA'): # Replace all for n-kit
return m.work(tag, ag)
# Change sets
sets = m.opts.sets
st_desc = lambda st, sti: f('{}:"{}" (#{})', sti+1, st.nm if st.nm else M.DEF_SET, len(st.ps))
if tag[:4]=='stRM': # Remove
sti = int(tag[4:])
st = sets[sti]
if st.ps \
and app.ID_YES!=msg_box(f(_('Remove kit {}'), st_desc(st, sti))
, app.MB_YESNO+app.MB_ICONQUESTION): return []
del sets[sti]
if not sets:
sets.append(d(nm=M.DEF_SET, ps=[]))
m.opts.aset = max(m.opts.aset-1, 0)
return d(ctrls=d(sets=d(items=M.sets_items(m.opts.sets), val=m.opts.aset)))
if tag=='stsw': # Change positions
ostd= {st.nm:st for st in sets}
onms= [*ostd.keys()]
rt,vs = DlgAg(
form =d(cap=_('Re-order kits'), h=300, w=155, frame='resize')
, ctrls =d(
me=d(tp='memo',y= 5,x= 5 ,r=-5 ,b=-35,val=onms ,a='b.r>' ,ro_mono_brd='0,1,1'
),ok=d(tp='bttn',y=-30,x=-75 ,w= 70 ,cap=_('Save') ,a='..--' ,on=CB_HIDE
))
, opts =d(negative_coords_reflect=True)).show()
if 'ok' != rt: return []
nnms = vs['me']
nnms = nnms[:-1] if app.API<349 else nnms # :-1 - memo BUG: it adds extra EOL
pass; log("onms={}",(onms))
pass; log("nnms={}",(nnms))
if onms==nnms: return [] # No changes
if set(onms)!=set(nnms): return M.msg(_('Skip new order - kit names were not saved'))
nsets = [ostd[nm] for nm in nnms]
naset = nnms.index(sets[m.opts.aset].nm)
m.opts.sets = nsets
m.opts.aset = naset
return d(ctrls=d(sets=d(items=M.sets_items(m.opts.sets), val=m.opts.aset)
,stus=M.msg_d(_('Kits order was changed'))))
if tag=='prsv': # Add pair to set
if not m.opts.what: return M.msg_f('what', _('Enter a non-empty Find pattern'), 'w')
st = sets[m.opts.aset]
if [pr for pr in st.ps
if pr.re==m.opts.reex
and pr.cs==m.opts.case
and pr.wd==m.opts.word
and pr.f ==m.opts.what
and pr.r ==m.opts.repl]: return M.msg(_('The pair is already in the kit'), a=add_msg)
st.ps.append(d(re=m.opts.reex, cs=m.opts.case, wd=m.opts.word, f=m.opts.what, r=m.opts.repl))
return d(ctrls=d(sets=d(items=M.sets_items(m.opts.sets), val=m.opts.aset)
,stus=M.msg_d(_('The pair was saved'), a=add_msg)))
if(tag=='impt' # Import
or tag=='stnw' # Create
or tag=='sted'): # Edit name,rcw,pairs
if app.API>=349:
mmv_list= lambda mmv: [] if ('\n'==mmv or ''==mmv) else [mmv] if str==type(mmv) else mmv
else:
mmv_list= lambda mmv: [] if ('\n'==mmv or ''==mmv) else [mmv] if str==type(mmv) else mmv[:-1] # :-1 - memo BUG: it adds extra EOL
RCWS_H = _('Search options as a string (any order):\r . - RegExp\r c - Case sensitive\r w - Whole word')
st = d(nm='kit'+str(1+len(sets)), ps=M.core_hist_ps()) \
if tag=='impt' else \
d(nm='kit'+str(1+len(sets)), ps=[]) \
if tag=='stnw' else \
sets[m.opts.aset]
rcws = [('.' if pr.re else '')+('c' if pr.cs else '')+('w' if pr.wd else '')
for pr in st.ps]
whts = [pr.f for pr in st.ps]
rpls = [pr.r for pr in st.ps]
def on_save(ag_,name,d_=''):
fs,rs = map(mmv_list, ag_.vals(['whts', 'rpls']).values())
if not len(fs)==len(rs):
return M.msg_f('whts', _('Set equal number of Find/Replace patterns'), 'w')
if whts and rpls and '' in fs:
return M.msg_f('whts', _('Enter all non-empty Find patterns'), 'w')
if ag_.val('name') in [st_.nm for st_ in sets if st_!=st]:
return M.msg_f('name', _('Set another name for kit'), 'w')
return None # Close dlg
fcap = '['+M.FORM_CB+'] '+(_('New kit') if tag in ('stnw', 'impt') else
f(_('Content of kit ({})'), 1+m.opts.aset))
ret,vals= DlgAg(
form =d(cap=fcap
,h=260, w=700, w_max=700 # Only vert resize
,frame='resize')
, ctrls =d(
rcw_=d(tp='labl',y= 5 ,x= 5 ,w= 80 ,cap=_('. c w') ,hint=RCWS_H
),rcws=d(tp='memo',y=25 ,h=200 ,x= 5 ,w= 80 ,val=rcws ,a='b.' ,ro_mono_brd='0,1,1'
),wha_=d(tp='labl',y= 5 ,x=10+80 ,w=300 ,cap=_('&Find patterns:')
),whts=d(tp='memo',y=25 ,h=200 ,x=10+80 ,w=300 ,val=whts ,a='b.' ,ro_mono_brd='0,1,1'
),rep_=d(tp='labl',y= 5 ,x=15+80+300,w=300 ,cap=_('&Replace patterns:')
),rpls=d(tp='memo',y=25 ,h=200 ,x=15+80+300,w=300 ,val=rpls ,a='b.' ,ro_mono_brd='0,1,1'
),nam_=d(tp='labl',tid='okok' ,x= 5 ,w= 80 ,cap='>'+_('&Name:') ,a='..'
),name=d(tp='edit',tid='okok' ,x= 10+80 ,w= 80 ,val=st.nm ,a='..'
),stus=d(tp='labl',tid='okok' ,x= 20+80*2 ,r=-90 ,cap=''*100 ,a='..'
),oko_=d(tp='bttn',y=-30 ,x=-65 ,w= 50 ,cap=_('&ы') ,a='..' ,on=on_save ,sto=False
),okok=d(tp='bttn',y=-30 ,x=-75 ,w= 70 ,cap=_('&Save') ,a='..' ,on=on_save
))
, fid ='name' if tag in ('stnw', 'impt') else 'whts'
, opts =d(negative_coords_reflect=True)
).show()
if ret is None: return []
ps,fs,rs,nm = vals.values()
ps,fs,rs= map(mmv_list, (ps,fs,rs))
ps = ps[:-len(fs)] if len(ps)>len(fs) else ps+['']*(len(fs)-len(ps)) if len(ps)<len(fs) else ps
st.nm = nm
st.ps = [d(re=('.' in o), cs=('c' in o), wd=('w' in o), f=f, r=r)
for o,f,r in zip(ps, fs, rs)]
if tag in ('stnw', 'impt'):
sets.append(st)
m.opts.aset = len(sets)-1
return d(ctrls=d(sets=d(items=M.sets_items(sets), val=m.opts.aset)))
if tag=='stse': # Edit kits
on_help = lambda ag,name,d='':(msg_box(_(
# on_help = lambda ag,name,d='':(msg_box_ex(_('Edit kits help'), _(
'Use 1+3*n lines for each kit.'
'\r First line for'
'\r n:kit name.'
'\r Three lines for each kit pair'
'\r a:attributes - "." "c" "w" - in any order,'
'\r f:pattern Find,'
'\r r:pattern Replace.'
'\r'
'\rFormat:'
'\r- The order of lines with "n:", "a:", "f:", "r:" is fixed.'
'\r- Feel free to use empty lines and some blanks before "n:", "a:", "f:", "r:".'
'\r'
'\rRules:'
'\r- Empty name is correct.'
'\r- Names must not be repeated.'
'\r- Pattern Find must not be empty.'
)),[])[1]
WN,WA,WF,WR = 'n:','a:','f:','r:'
def on_save_new_sets(ag_, name, dt=''):
""" If dt=='' then do control before save.
If dt!='' then build new sets
"""
chk = dt==''
kt_lns_n= (ag_.val('me') if chk else dt['me'])
kt_lns_n= kt_lns_n[:-1] if app.API<349 else kt_lns_n # :-1 - memo BUG: it adds extra EOL
if not kt_lns_n: return None if chk else []
if kt_lns_n==kt_lns_o: return None if chk else sets
stsn = []
wait,nms,st,pr = [WN], set(), None, None
for nl,ln in enumerate(kt_lns_n):
if not ln: continue
ww,ldt = ln.lstrip()[:2], ln.lstrip()[2:]
if ww not in wait: return M.msg_f('me', _('Error: order of lines - line ')+str(1+nl), 'w')
if False:pass
elif ww==WN \
and ldt in nms: return M.msg_f('me', _('Error: kit name repeated - ')+ldt, 'w')
elif ww==WN:
wait, st = [WA], d(nm=ldt, ps=[])
nms.add(st.nm)
stsn.append(st)
elif ww==WA:
wait, pr = [WF], d(re='.' in ldt, cs='c' in ldt, wd='w' in ldt, f='', r='')
st.ps.append(pr)
elif ww==WF \
and not ldt: return M.msg_f('me', _('Error: empty Find pattern for kit - ')+st.nm, 'w')
elif ww==WF:
wait, pr.f = [WR], ldt
elif ww==WR:
wait, pr.r = [WA,WN], ldt
if not pr.f: return M.msg_f('me', _('Error: empty Find pattern for kit - ')+st.nm, 'w')
if wait==[WR]: return M.msg_f('me', _('Error: no Replace pattern for kit - ')+st.nm, 'w')
return None if chk else stsn
okts = [ (WN+st.nm
,[(' '+WA+('.' if pr.re else '')+('c' if pr.cs else '')+('w' if pr.wd else '')
,' '+WF+pr.f
,' '+WR+pr.r,'') for pr in st.ps
],'') for st in sets]
kt_lns_o= [*flatten(okts)]
rt,vs = DlgAg(
form =d(cap='['+M.FORM_CB+'] '+_('Edit kits'), h=400, w=400, frame='resize')
, ctrls =d(
me =d(tp='memo',y= 5 ,x= 5 ,r=-5 ,b=-35,val=kt_lns_o ,a='b.r>' ,ro_mono_brd='0,1,1'
),stus=d(tp='labl',tid='ok' ,x= 5 ,r=-115 ,cap='' ,a='..r>'
),ok =d(tp='bttn',y=-30 ,r=-40,w= 70 ,cap=_('&Save') ,a='..>>' ,on=on_save_new_sets
),hl =d(tp='bttn',y=-30 ,r=-5 ,w= 30 ,cap=_('?') ,a='..>>' ,on=on_help
))
, opts =d(negative_coords_reflect=True)).show()
if 'ok' != rt: return []
stsn = on_save_new_sets(None, None, vs)
m.opts.sets = stsn if stsn else [d(nm=M.DEF_SET, ps=[])]
m.opts.aset = 0
return d(ctrls=d(sets=d(items=M.sets_items(m.opts.sets), val=m.opts.aset)))
# Use sets
if tag=='sets': # Changed aset
return m.do_acts(ag, 'prnx', _recall=True) # Auto-Load pair for loaded set
if tag=='stpr'\
or tag=='stnx': # Prev/Next set
if 1==len(sets): return []
m.opts.aset= (m.opts.aset + (1 if tag=='stnx' else -1)) % len(sets)
st = sets[m.opts.aset]
return [m.do_acts(ag, 'prnx', _recall=True) # Auto-Load pair for loaded set
,d(ctrls=d(sets=d(val=m.opts.aset)))]
if tag[:4]=='stAC': # Activate by index
sti = int(tag[4:])
if not 0<=sti<len(sets): return []
m.opts.aset = sti
return [m.do_acts(ag, 'prnx', _recall=True) # Auto-Load pair for loaded set
,d(ctrls=d(sets=d(val=m.opts.aset)))]
if tag[:4]=='stLP': # Load set and pair
sti,pri = map(int, tag[4:].split('_'))
if not 0<=sti<len(m.opts.sets): return []
st = sets[sti]
if not 0<=pri<len(st.ps): return []
pr = st.ps[pri]
m.opts.aset = sti
return d(ctrls=d(what=d(val=pr.f),repl=d(val=pr.r)
,reex=d(val=pr.re),case=d(val=pr.cs),word=d(val=pr.wd)
,sets=d(val=m.opts.aset)
,stus=M.msg_d(f(_('Loaded pair {}/{}'), pri+1, len(st.ps)), a=add_msg)
))
if tag=='prpr'\
or tag=='prnx': # Prev/Next pair
what, repl = ag.vals(['what', 'repl']).values()
st = sets[m.opts.aset]
if 0==len(st.ps): return []
pri, off = 0, 1 if tag=='prnx' else -1
for n,pr in enumerate(st.ps):
if pr.f==what:
pri = n # If what in pair then load repl
if pr.r==repl:
pri = n+off # If what+repl in pair then load prev/next pair
break#for n,pr
pri = pri % len(st.ps)
pr = st.ps[pri]
return d(ctrls=d(what=d(val=pr.f),repl=d(val=pr.r)
,reex=d(val=pr.re),case=d(val=pr.cs),word=d(val=pr.wd)
,stus=M.msg_d(f(_('Loaded pair {}/{}'), pri+1, len(st.ps)), a=add_msg)
))
if(tag=='fndn' or tag=='fndp'
# or tag=='rpln' or tag=='rplp'
or tag=='rpla'
): # Prev/Next find/replace, replace all
add_to_hist(m.opts.what, m.opts.whtl) # Save as use
add_to_hist(m.opts.repl, m.opts.rpll) # Save as use
return [m.work(tag, ag)
,d(ctrls=d(what=d(items=m.opts.whtl)
,repl=d(items=m.opts.rpll)))]
return []
#def do_acts
def work(self, task, par=None):
""" offer_repl fnda_locs
stRA fndn fndp rpla rpls
"""
M,m = type(self),self
pass; log4fun= 0
pass; log("task, par={}",(task, par)) if log4fun else 0
if task=='offer_repl':
what = par
st = m.opts.sets[m.opts.aset]
for pr in st.ps:
if pr.f.startswith(what):
return pr.r
return None
ag = par
if( task =='rpls' # Replace all from active kit
or task[:4]=='stRA'): # Replace all for n-kit
sti = m.opts.aset if task=='rpls' else int(task[4:])
if not 0<=sti<len(m.opts.sets): return []
st = m.opts.sets[sti]
pass; log("st={}",(st)) if log4fun else 0
if not st.ps: return M.msg(f(_('No pairs in kit "{}"'), st.nm))
vtab = lambda s:s.replace('\t', '→')
rpta,cntf = [], 0
for np,pr in enumerate(st.ps):
frgs= ed.action(app.EDACTION_FIND_ALL
, param1=pr.f
, param2='af' + M.st_pr_rc(pr)) # a - wrap, f - from caret
rpta.append(f(_('{}? {}\n {}\n {}'), len(frgs), M.st_pr_cw(pr).ljust(5), vtab(pr.f), vtab(pr.r)))
cntf+= len(frgs)
if not cntf: return M.msg(f(_('No fragments to replace with kit "{}"'), st.nm))
need_ask = '##SKIP-ASK##' not in st.nm
ag_ = DlgAg(
form =d(cap=f(_('Replace ALL for kit ("{}")'), st.nm), h=300, w=300, frame='resize')
, ctrls =d(
ok=d(tp='bttn',y=-30,x=-130 ,w= 60 ,cap=_('Yes') ,a='..>>' ,on=CB_HIDE ,def_bt=True
),ca=d(tp='bttn',y=-30,x=-65 ,w= 60 ,cap=_('No') ,a='..>>' ,on=CB_HIDE
),me=d(tp='memo',y= 5,x= 5 ,r=-5 ,b=-35,val=rpta ,a='b.r>' ,ro_mono_brd='1,1,0'
))
, opts =d(negative_coords_reflect=True))
if need_ask and \
'ok' != ag_.show(onetime=False)[0]: return []
rpta = []
for np,pr in enumerate(st.ps):
cntr= ed.action(app.EDACTION_REPLACE_ALL
, param1=pr.f
, param2=pr.r
, param3='af' + M.st_pr_rc(pr)) # a - wrap, f - from caret
rpta.append(f(_('{}! {}\n {}\n {}'), cntr, M.st_pr_cw(pr).ljust(5), vtab(pr.f), vtab(pr.r)))
ag_.update(form =d(cap=f(_('Results for kit ("{}")'), st.nm))
, ctrls=d(ok=d(vis=False)
,ca=d(cap=_('Close'))
,me=d(val=rpta)))
if need_ask:
ag_.show()
return []
if not m.opts.what: return []
fops = 'af' \
+ ('r' if m.opts.reex else '') \
+ ('c' if m.opts.case else '') \
+ ('w' if m.opts.word else '') # a - wrap, f - from caret
if task=='fnda_locs':
fnda= ed.action(app.EDACTION_FIND_ALL, param1=m.opts.what, param2=fops)
return fnda
fnda = m.work('fnda_locs', par)
if not fnda and task=='rpla' and m.opts.anxt:
return [M.msg(_('Not found. '))
,m.do_acts(ag, 'prnx', _recall=True, add_msg=True)]
elif not fnda:
return M.msg(_('Not found'))
fact = None
pars = None
if False:pass
elif task=='fndn' \
or task=='fndp':
fact= app.EDACTION_FIND_ONE
pars= d(param1=m.opts.what
,param2=fops+('b' if task=='fndp' else ''))
elif task=='rpla':
fact= app.EDACTION_REPLACE_ALL
pars= d(param1=m.opts.what, param2=m.opts.repl
,param3=fops)
pass; log(f"fact={fact} pars={pars}") if log4fun else 0
rsp = ed.action(fact, **pars)
pass; log(f"rsp={rsp}") if log4fun else 0
if False:pass
elif (task=='fndn' or task=='fndp'
# or task=='rpln' or task=='rplp'
):
ed.set_caret(*rsp)
fpos= fnda.index(rsp)
return M.msg(f'{fpos+1}({len(fnda)})')
return []
elif task=='rpla' and m.opts.anxt:
return [M.msg(f(_('Replaces made: {}. '), len(fnda)))
,m.do_acts(ag, 'prnx', _recall=True, add_msg=True)]
elif task=='rpla': # and not m.opts.anxt
return M.msg(f(_('Replaces made: {}'), len(fnda)))
#def work
#class RiL
theRiL = RiL() # Single obj
def dlg_replace_in_lines(): #NOTE: dlg_replace_in_lines
theRiL.show() # new!
#def dlg_replace_in_lines
def kit_replace_in_lines():
theRiL.do_acts(None, 'arps', _recall=True, add_msg=True)
#def kit_replace_in_lines
class FiL:
FORM_C = _('Find in Lines')
HELP_C = _('''
• Search "in Lines" starts immediately (if focus in the left edit) or on Enter or Shift+Enter (if focus in the right edit).
• A found fragment after first caret will be selected.
• All found fragments are remembered and dialog can jump over them by [Shift+]Enter or by menu commands.
• Ctlr+Right (or Alt+Right) copies text from the left edit to the right.
• Ctlr+Left (or Alt+Left) copies text from the right edit to the left.
• Option ".*" (regular expression) allows to use Python reg.ex. See "docs.python.org/3/library/re.html".
• Option "w" (whole words) is ignored if entered string contains not a word.
• If option "Instant search" (in menu) is tuned on, search result will be updated on start and after each change of pattern.
• Command "Restore initial selection" (Shift+Esc) restores only first of initial carets.
• Ctrl+F (or Ctrl+R) calls appication dialog Find (or Replace).
''').strip()
# To select found fragment
select_frag = lambda frag_inf: ed.set_caret(*frag_inf)
# To fit pattern to find
compile_pttn= lambda pttn_s, reex, case, word: re.compile(
pttn_s if reex else
r'\b'+pttn_s+r'\b' if word and re.match(r'^\w+$', pttn_s) else
re.escape(pttn_s)
, 0 if case else re.I)
ed_crts = None # Carets at start
opts = None
ag = None # Nonmodal obj
what = '' # String to search
prev_wt = '' # Prev what
ready_l = [] # [(row,col_bgn,col_end)]
ready_p = -1 # pos in ready_l
last_awht = 'what'
@staticmethod
def msg_(msg=None):
msg =(msg if msg else
f('{}/{}', 1+FiL.ready_p, len(FiL.ready_l)) if FiL.ready_l else
f(_('Left input: at least {} chars. Right input: ENTER.'), FiL.opts['insm'])
)
msg = f('{}: {}' , FiL.FORM_C, msg) if FiL.opts['dock'] else \
f('{} ({})', FiL.FORM_C, msg)
return msg
#def msg_
@staticmethod
def msg_upd(msg=None, fid='what'):
msg = FiL.msg_(msg)
return {'ctrls':{'mess':{'cap':msg}},'fid':fid} if FiL.opts['dock'] else \
{'form': {'cap':msg} ,'fid':fid}
#def msg_upd
def show(self):
M,m = type(self),self
pass; log4fun=0 # Order log in the function
FiL.ed_crts = ed.get_carets() # Carets at start/activate
pass; #log__('hist={}',(get_hist('find.find_in_lines')) ,__=(log4fun,_log4mod))
FiL.opts = d(reex=False,case=False,word=False
, hist=[]
, usel=False
, dock='',dock_ww=300
, nmdl=False
, inst=False,insm=3
, pfid='what') # Default options
FiL.opts.update(get_hist('find.find_in_lines', FiL.opts))
pass; #log("FiL.opts={}",(FiL.opts))
FiL.ag = FiL.ag if (FiL.ag and FiL.ag.islived()) else None
pass; log__("FiL.what={}",(FiL.what) ,__=(log4fun,_log4mod))
FiL.ready_l = []
FiL.ready_p = -1
FiL.prev_wt = '' # To refind
awht = FiL.opts['pfid'] if FiL.opts['pfid'] in ('whti', 'what') else 'what'
what =(ed.get_text_sel()
if FiL.opts['usel'] else #and ed.get_text_sel() else
FiL.what)
what = '' if '\r' in what or '\n' in what else what
pass; log__("FiL.ag={}",(FiL.ag) ,__=(log4fun,_log4mod))
if FiL.ag:
##??
FiL.ag.activate()
FiL.ag.update(d(vals=d(whti=what if awht=='whti' else ''
,what=what if awht=='what' else '')))
pass; log__('FiL.prev_wt, len(FiL.ready_l)={}',(FiL.prev_wt, len(FiL.ready_l)) ,__=(log4fun,_log4mod))
return FiL.ag.update(self.do_find(FiL.ag, 'find', awht)) # To refind
pass; #log__('###',() ,__=(log4fun,_log4mod))
dock = FiL.opts['dock']
wtwd = FiL.opts['dock_ww'] if dock else 105
mswd = 150 if dock else 0
menx = 5+114+5+wtwd+5+wtwd+5
# menx = 5+114+5+105 +5+wtwd+5
msg = FiL.msg_()
ag = DlgAg(
form =dict(cap=msg, w=5+114+5+wtwd+5+wtwd+39+5+5
# form =dict(cap=msg, w=5+114+5+105 +5+wtwd+39+5+5
,h=38, h_max=38 # Only horz resize
,on_key_down=m.do_key_down
,on_resize=m.on_resize
,frame='resize'
)
, ctrls =[0
,('find',d(tp='bttn' ,y=0 ,x=-99 ,w=11 ,cap='' ,sto=False ,def_bt='1' ,on=m.do_find )) # Enter
,('reex',d(tp='chbt' ,tid='what' ,x=5 ,w=38 ,cap='&.*' ,hint=_('Regular expression') ,on=m.do_attr )) # &.
,('case',d(tp='chbt' ,tid='what' ,x=5+ 38 ,w=38 ,cap='&aA' ,hint=_('Case sensitive') ,on=m.do_attr )) # &a
,('word',d(tp='chbt' ,tid='what' ,x=5+ 76 ,w=38 ,cap='"&w"' ,hint=_('Whole words') ,on=m.do_attr )) # &w
,('whti',d(tp='edit' ,tid='what' ,x=5+114+5 ,w=wtwd ,on=m.do_find )) #
# ,('whti',d(tp='edit' ,tid='what' ,x=5+114+5 ,w=105 ,on=m.do_find )) #
,('what',d(tp='cmbx' ,y =5 ,x=5+114+10+wtwd,w=wtwd ,items=FiL.opts['hist'] ,_a='' if dock else 'r>' )) #
# ,('what',d(tp='cmbx' ,y =5 ,x=5+114+115 ,w=wtwd ,items=FiL.opts['hist'] ,_a='' if dock else 'r>' )) #
,('menu',d(tp='bttn' ,tid='what' ,x=menx ,w=38 ,cap='&=' ,on_menu=m.do_menu ,on=m.do_menu ,a='' if dock else '>>' )) # &=
,('mess',d(tp='labl' ,tid='what' ,x=menx+39+5 ,w=mswd ,cap=msg ,a='r>' if dock else '' )) #
][1:]
, fid =FiL.opts['pfid']
# , fid ='what'
, vals =d(**{k:FiL.opts[k] for k in ('reex','case','word')}
, whti=what if awht=='whti' else ''
, what=what if awht=='what' else '')
#, opts ={}
)
pass; #ag.gen_repro_code('repro_dlg_fil.py')
pass; #log__("FiL.opts[inst] and what={}",(FiL.opts['inst'], what) ,__=(log4fun,_log4mod))
if FiL.opts['pfid']=='whti' and what:
# if FiL.opts['inst'] and what:
ag.update(m.do_find(ag, 'find'))
FiL.ag = ag if FiL.opts['nmdl'] or FiL.opts['dock'] else None
pass; log__("FiL.ag={}",(FiL.ag) ,__=(log4fun,_log4mod))
ag.dock(FiL.opts['dock'])
ag.show( on_exit=self.on_exit
,modal=not (FiL.opts['nmdl'] or FiL.opts['dock'])
)
#def show
def on_resize(self, ag, key, data=''):
xi, xm = ag.cattr('whti', 'x'), ag.cattr('menu', 'x')
w2 = (xm - xi - 10) // 2
FiL.opts['dock_ww'] = w2
return d(ctrls=d(whti=d(x=xi , w=w2),
what=d(x=xi+w2+5, r=xm-5)))
#def on_resize
def do_find(self, ag, aid, data=''):
pass; log4fun=0 # Order log in the function
fid = ag.focused()
pass; log__('aid, data, fid={}',(aid, data, fid) ,__=(log4fun,_log4mod))
# What/how will search
prnx = 'prev' if aid=='prev' else 'next'
crt = ed.get_carets()[0][:] # Current first caret (col,row, col?,row?)
min_rc = (crt[1], crt[0]) if crt[2]==-1 else min((crt[1], crt[0]), (crt[3], crt[2]))
max_rc = (crt[1], crt[0]) if crt[2]==-1 else max((crt[1], crt[0]), (crt[3], crt[2]))
# awht = data if data else 'whti' if aid=='whti' else 'what'
awht =(data if data else
'whti' if aid=='whti' and FiL.opts['dock'] else # fix to core bug: fid is not correct for docked form
fid if fid in ('whti', 'what') else
'whti' if aid=='whti' else
'what'
)
# awht = data if data else 'whti' if ag.focused()=='whti' else 'what'
FiL.last_awht = awht
what = ag.val(awht)
pass; log__('what, FiL.prev_wt, len(FiL.ready_l)={}',(what, FiL.prev_wt, len(FiL.ready_l)) ,__=(log4fun,_log4mod))
if FiL.prev_wt==what and FiL.ready_l: # Jump to next/prev
if 1==len(FiL.ready_l):
pass; log__('no jump for single',() ,__=(log4fun,_log4mod))
return d(fid=awht)
FiL.ready_p = (FiL.ready_p + (-1 if aid=='prev' else 1)) % len(FiL.ready_l)
pass; log__('jump to {}',(FiL.ready_p) ,__=(log4fun,_log4mod))
FiL.select_frag(FiL.ready_l[FiL.ready_p])
return FiL.msg_upd(fid=awht)
FiL.prev_wt = what
FiL.what = what
FiL.opts.update(ag.vals(['reex','case','word']))
if not what: # Nothing to show
FiL.ready_l, FiL.ready_p = [], -1
pass; log__('no what',() ,__=(log4fun,_log4mod))
return FiL.msg_upd(fid=awht)
if awht=='whti' and \
len(what)<FiL.opts['insm'] and \
not FiL.opts['reex']: # Not ready to find reex??
FiL.ready_l, FiL.ready_p = [], -1
pass; log__('not ready',() ,__=(log4fun,_log4mod))
return FiL.msg_upd(fid=awht)
up_hist = []
if awht=='what':
FiL.opts['hist']= add_to_hist(what, FiL.opts['hist'])
up_hist = [d(ctrls=d(what=d(items=FiL.opts['hist'])))]
# New search
FiL.ready_l = []
FiL.ready_p = -1
pttn_r = None
try:
pttn_r = FiL.compile_pttn(what, FiL.opts['reex'], FiL.opts['case'], FiL.opts['word'])
except Exception as ex:
return up_hist+[FiL.msg_upd(str(ex), fid=awht)]
pass; log__('FiL.ready_p,min_rc,max_rc={}',(FiL.ready_p,min_rc,max_rc) ,__=(log4fun,_log4mod))
FiL.ready_p = -1
for row in range(ed.get_line_count()):