Codit/Plugins/SearchReplace.pm untested

filter: Statementstmt 0.0% 0 / 432 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 35 totaltotal 0.0% 0 / 655 CC 71 SCAR 33.0
CC
71
Cov
0%
BrowseNext
72.0
FindInDoc
72.0
BrowsePrevious
56.0
CRAP 27.2
1 package App::Codit::Plugins::SearchReplace;
2  
3 =head1 NAME
4  
5 App::Codit::Plugins::SearchReplace - plugin for App::Codit
6  
7 =cut
8  
9 use strict;
10 use warnings;
11 use vars qw( $VERSION );
12 $VERSION = '0.21';
13  
14 use base qw( Tk::AppWindow::BaseClasses::Plugin );
15 use Tk;
16 require Tk::LabFrame;
17 require Tk::ITree;
18  
19 my $srchcur = 'Search in current document';
20 my $srchall = 'Search in all documents';
21 my $srchprj = 'Search in project files';
22 my $srchres = 'Search in results';
23  
24 =head1 DESCRIPTION
25  
26 Search and replace across multiple files.
27  
28 =head1 DETAILS
29  
30 This plugin allows you to do a search and replace across multiple or just one file.
31  
32 After filling out the search and replace fields you first click Find.
33 The list box will fill with the search results.
34  
35 When you click Replace the first item in the list is replaced and then removed from the list.
36  
37 You can skip replaces by pressing Skip.
38  
39 When searching with a regular expression you can include the captures you make with () in
40 the replace string with ‘$1’, ‘$2’, etcetera.
41  
42 Clear removes all search results.
43  
44 =cut
45  
46 sub new {
47 my $class = shift;
48 my $self = $class->SUPER::new(@_);
49 return undef unless defined $self;
50
51 # my $tp = $self->extGet('ToolPanel');
52 # my $page = $tp->addPage('SearchReplace', 'edit-find-replace', undef, 'Search and replace');
53 my $page = $self->ToolRightPageAdd('SearchReplace', 'edit-find-replace', undef, 'Search and replace', 350);
54  
55 my $searchterm = '';
56 my $replaceterm = '';
57 my $casesensitive = '-case';
58 my $useregex = '-exact';
59 my $searchmode = 'Search in current document';
60  
61 $self->{CASE} = \$casesensitive;
62 $self->{CURRENT} = undef;
63 $self->{FINDACTIVE} = 0;
64 $self->{LASTRESULTS} = [];
65 $self->{MODE} = \$searchmode;
66 $self->{OFFSET} = {};
67 $self->{REPLACE} = \$replaceterm;
68 $self->{REPLACED} = 0;
69 $self->{REGEX} = \$useregex;
70 $self->{SEARCH} = \$searchterm;
71 $self->{SKIPPED} = 0;
72  
73 my @padding = (-padx => 2, -pady => 2);
74  
75 my $sa = $page->Frame(
76 -relief => 'groove',
77 -borderwidth => 2,
78 )->pack(@padding, -fill => 'x');
79  
80 my $sf = $sa->Frame->pack(-expand => 1, -fill => 'x');
81 $sf->Label(
82 -text => 'Search',
83 -width => 7,
84 -anchor => 'e',
85 )->pack(@padding, -side => 'left');
86 my $se = $sf->Entry(
87 -textvariable => \$searchterm,
88 )->pack(@padding, -side => 'left', -expand => 1, -fill => 'x');
89 $se->bind('<Return>', [$self, 'Find']);
90  
91 my $rf = $sa->Frame->pack(-expand => 1, -fill => 'x');
92 $rf->Label(
93 -text => 'Replace',
94 -width => 7,
95 -anchor => 'e',
96 )->pack(@padding, -side => 'left');
97 $rf->Entry(
98 -textvariable => \$replaceterm,
99 )->pack(@padding, -side => 'left', -expand => 1, -fill => 'x');
100  
101 my $sb = $page->LabFrame(
102 -labelside => 'acrosstop',
103 -relief => 'groove',
104 -label => 'Search options',
105 )->pack(@padding, -fill => 'x');
106  
107 $sb->Checkbutton(
108 -variable => \$useregex,
109 -text => 'Regular expression',
110 -onvalue => '-regexp',
111 -offvalue => '-exact',
112 -anchor => 'w',
113 )->pack(@padding, -fill => 'x');
114 $sb->Checkbutton(
115 -variable => \$casesensitive,
116 -onvalue => '-case',
117 -offvalue => '-nocase',
118 -text => 'Case sensitive',
119 -anchor => 'w',
120 )->pack(@padding, -fill => 'x');
121 my $mb = $sb->Menubutton(
122 # -relief => 'raised',
123 -anchor => 'w',
124 -textvariable => \$searchmode,
125 )->pack(@padding, -fill => 'x');
126 my @menu = ();
127 for ($srchcur, $srchall, $srchprj, $srchres) {
128 my $mode = $_;
129 push @menu, [command => $mode,
130 -command => sub { $searchmode = $mode },
131 ];
132 }
133 $mb->configure(-menu => $mb->Menu(
134 -menuitems => \@menu,
135 ));
136  
137  
138 my $sc = $page->Frame(
139 -relief => 'groove',
140 -borderwidth => 2,
141 )->pack(@padding, -fill => 'x');
142 $sc->gridColumnconfigure(0, -weight => 2);
143 $sc->gridColumnconfigure(1, -weight => 2);
144 $sc->Button(
145 -command => ['Find', $self],
146 -text => 'Find',
147 -width => 8,
148 )->grid(@padding, -column => 0, -row => 0, -sticky => 'ew');
149 $sc->Button(
150 -command => ['Clear', $self],
151 -text => 'Clear',
152 -width => 8,
153 )->grid(@padding, -column => 1, -row => 0, -sticky => 'ew');
154 $sc->Button(
155 -command => ['Replace', $self],
156 -text => 'Replace',
157 -width => 8,
158 )->grid(@padding, -column => 0, -row => 1, -sticky => 'ew');
159 $sc->Button(
160 -command => ['Skip', $self],
161 -text => 'Skip',
162 -width => 8,
163 )->grid(@padding, -column => 1, -row => 1, -sticky => 'ew');
164  
165  
166 my $tf = $page->Frame(
167 -relief => 'groove',
168 -borderwidth => 2,
169 )->pack(@padding, -expand => 1, -fill => 'both');
170 $tf->gridColumnconfigure(0, -weight => 2);
171 $tf->gridColumnconfigure(1, -weight => 2);
172 $tf->gridRowconfigure(1, -weight => 2);
173 $tf->Button(
174 -text => 'Previous',
175 -command => ['BrowsePrevious', $self],
176 -width => 8,
177 )->grid(@padding, -column => 0, -row => 0, -sticky => 'ew');
178 $tf->Button(
179 -text => 'Next',
180 -command => ['BrowseNext', $self],
181 -width => 8,
182 )->grid(@padding, -column => 1, -row => 0, -sticky => 'ew');
183 my $results = $tf->Scrolled('ITree',
184 -height => 4,
185 -browsecmd => ['Select', $self],
186 -scrollbars => 'osoe',
187 -separator => '@',
188 )->grid(@padding, -column => 0, -columnspan => 2, -row => 1, -sticky => 'nsew');
189 $results->autosetmode;
190 $self->{RESULTSLIST} = $results;
191
192 $self->cmdHookAfter('doc_select', 'DocResults', $self);
193  
194 return $self;
195 }
196  
197 sub BrowseNext {
198 my $self = shift;
199 my $list = $self->list;
200 my ($sel) = $list->infoSelection;
201  
202 #select the first hit if no selection is set
203 unless (defined $sel) {
204 $sel = $self->SelectFirst;
205 return
206 }
207 return unless defined $sel;
208  
209 #select the first hit is the last hit is selected
210 my $last = $self->GetLast;
211 if ($self->IsSelected($last)) {
212 $sel = $self->SelectFirst;
213 return
214 }
215  
216 my ($name, $index) = split(/@/, $sel);
217 if (defined $index) {
218 my $next = $list->infoNext($sel);
219 return unless defined $next;
220 my ($nname, $nindex) = split(/@/, $next);
221 unless (defined $nindex) {
222 my @d = $list->infoChildren($nname);
223 if (@d) {
224 $self->Select($d[0]);
225 return
226 }
227 } else {
228 $self->Select($next);
229 }
230 }
231 }
232  
233 sub BrowsePrevious {
234 my $self = shift;
235 my $list = $self->list;
236 my ($sel) = $list->infoSelection;
237  
238 #select the last hit if no selection is set
239 unless (defined $sel) {
240 $self->SelectLast;
241 return
242 }
243 return unless defined $sel;
244  
245 #select the last hit is the first hit is selected
246 my $first = $self->GetFirst;
247 if ($self->IsSelected($first)) {
248 $self->SelectLast;
249 return
250 }
251 my ($name, $index) = split(/@/, $sel);
252 if (defined $index) {
253 my $prev = $list->infoPrev($sel);
254 return unless defined $prev;
255 my ($nname, $nindex) = split(/@/, $prev);
256 unless (defined $nindex) { #previous is a file entry;
257 $prev = $list->infoPrev($prev);
258 $self->Select($prev);
259 } else { #previous is a hit entry
260 $self->Select($prev);
261 }
262 }
263 }
264  
265 sub Clear {
266 my $self = shift;
267 my $list = $self->list;
268 my @c = $list->infoChildren('');
269 $self->Current(undef);
270 $self->{LASTRESULTS} = \@c;
271 $list->deleteAll;
272 $self->{OFFSET} = {};
273 $self->repl(0);
274 $self->skipped(0);
275 $self->FindActive(0);
276 my $mdi = $self->mdi;
277 for (@c) {
278 my $doc = $_;
279 unless ($mdi->deferredExists($doc)) {
280 my $widg = $mdi->docGet($doc);
281 $widg->FindClear;
282 }
283 }
284 $self->ShowResults;
285 }
286  
287 sub Current {
288 my $self = shift;
289 $self->{CURRENT} = shift if @_;
290 return $self->{CURRENT}
291 }
292  
293 sub DocSelected {
294 my $self = shift;
295 my $mdi = $self->extGet('CoditMDI');
296 return $mdi->docSelected;
297 }
298  
299 sub DocResults {
300 my $self = shift;
301 $self->ShowResults;
302 return unless $self->FindActive;
303 my $name = $self->mdi->docSelected;
304 return unless defined $name;
305 my $list = $self->{RESULTSLIST};
306 if ($list->infoExists($name)) {
307 my @c = $list->infoChildren($name);
308 my $num = @c;
309 $self->after(10, sub {
310 $self->log("$num results in $name")
311 })
312 }
313 }
314  
315 sub DocWidget {
316 my ($self, $name) = @_;
317 my $mdi = $self->extGet('CoditMDI');
318 return $mdi->docGet($name)->CWidg if defined $name
319 }
320  
321 sub Find {
322 my $self = shift;
323 my $search = $self->{SEARCH};
324 $self->Current(undef);
325 if ($$search eq '') {
326 $self->popMessage("Please enter a search phrase", 'dialog-warning', 32);
327 return
328 }
329 $self->Clear;
330 my $mode = $self->{MODE};
331 my $mdi = $self->extGet('CoditMDI');
332 if ($$mode eq $srchcur) {
333 my $cur = $mdi->docSelected;
334 return unless defined $cur;
335 $self->FindInDoc($cur);
336 } elsif ($$mode eq $srchall) {
337 my @list = ($mdi->docList, $mdi->deferredList);
338 for (@list) {
339 $self->FindInDoc($_);
340 }
341 } elsif ($$mode eq $srchprj) {
342 $self->FindInProject;
343 } elsif ($$mode eq $srchres) {
344 $self->FindInResults;
345 }
346 $self->FindActive(1);
347 $self->ShowResults(1);
348 }
349  
350 sub FindActive {
351 my $self = shift;
352 $self->{FINDACTIVE} = shift if @_;
353 return $self->{FINDACTIVE}
354 }
355  
356 sub FindInDoc {
357 my ($self, $name) = @_;
358  
359 my $mdi = $self->mdi;
360 my $search = $self->{SEARCH};
361 my $case = $self->{CASE};
362 my $regex = $self->{REGEX};
363 my $results = $self->list;
364 my $srch;
365 if ($$regex eq '-exact') {
366 $srch = quotemeta($$search)
367 } else {
368 eval "qr/$$search/";
369 my $error = $@;
370 if ($error ne '') {
371 $error =~ s/\n//;
372 $self->logError($error);
373 return
374 }
375 $srch = $$search;
376 }
377 if ($$case eq '-case') {
378 $srch = qr/$srch/
379 } else {
380 $srch = qr/$srch/i
381 }
382 my @hits = ();
383 if (($mdi->docExists($name)) and (not $mdi->deferredExists($name))) {
384 my $widg = $mdi->docGet($name)->CWidg;
385 my $last = $widg->linenumber('end - 1c');
386 my $end = $widg->index('end - 1c');
387 my $count = 0;
388 for (1 .. $last) {
389 my $linenum = $_;
390 my $linestart = "$linenum.0";
391
392 my $lineend = $widg->index("$linestart lineend + 1c");
393 $lineend = $end if $widg->compare($end,'<',$lineend);
394 my $line = $widg->get($linestart, $lineend);
395 push @hits, $self->FindInLine($line, $srch, $linenum);
396 }
397 } else {
398 if (open IFILE, "<", $name) {
399 my $linenum = 1;
400 while (<IFILE>) {
401 my $line = $_;
402 push @hits, $self->FindInLine($line, $srch, $linenum);
403 $linenum ++;
404 }
405 close IFILE;
406 }
407 }
408 if (@hits) {
409 $results->add($name,
410 -text => $self->abbreviate($name, 30),
411 -itemtype => 'imagetext',
412 -image => $self->getArt('text-x-plain')
413 );
414 }
415 while (@hits) {
416 my $hit = shift @hits;
417 my $begin = $hit->[0];
418 my $line = $hit->[2];
419 $results->add($name . '@' . $begin,
420 -text => "$begin - $line",
421 -data => $hit,
422 );
423 $results->autosetmode;
424 }
425 $self->update;
426 }
427  
428 sub FindInLine {
429 my ($self, $line, $search, $linenum) = @_;
430 $line =~ s/\n$//; #remove trailing newline
431 my $copy = $line;
432 $line =~ s/^\s+//; #remove leading spaces
433 my $offset = 0;
434 my @hits = ();
435 while ($copy =~ /($search)/g) {
436 my $end = pos($copy);
437 my $begin = $end - length($1);
438 my @cap = ();
439 if ($#- > 1) {
440 no strict 'refs';
441 @cap = map {$$_} 2 .. $#-;
442 }
443 push @hits, ["$linenum.$begin", "$linenum.$end", $line, \@cap];
444 }
445 return @hits;
446 }
447  
448 sub FindInProject {
449 my $self = shift;
450 my $git = $self->extGet('Plugins')->plugGet('Git');
451 unless (defined $git) {
452 $self->popMessage('Plugin git must be loaded for this', 'dialog-warning');
453 return
454 }
455 my $project = $git->projectCurrent;
456 if ($project eq '') {
457 $self->popMessage('No project selected in Git plugin', 'dialog-warning');
458 return
459 }
460 my @list = $git->gitFileList($project);
461 for (@list) {
462 $self->FindInDoc($_) if -T $_;
463 }
464 }
465  
466 sub FindInResults {
467 my $self = shift;
468 my $list = $self->{LASTRESULTS};
469 for (@$list) {
470 $self->FindInDoc($_);
471 }
472
473 }
474  
475 sub FinishedCheck {
476 my $self = shift;
477 my $cur = $self->GetCurrent;
478 unless (defined $cur) {
479 $self->list->selectionClear;
480 my $num = $self->{REPLACES};
481 $self->Report(1);
482 return 1
483 }
484 return 0;
485 }
486  
487 sub GetCurrent {
488 my $self = shift;
489 my $list = $self->list;
490 my @c = $list->infoChildren('');
491 my $mdi = $self->extGet('CoditMDI');
492  
493 for (@c) {
494 my $name = $_;
495 my @hits = $list->infoChildren($name);
496 my $offset = $self->OffsetGet($name);
497 my $cur = $hits[$offset];
498 if (defined $cur) {
499 $mdi->docSelect($name);
500 # if(exists $self->{FRESH}->{$name}) {
501 # $self->DocWidget($name)->unselectAll;
502 # delete $self->{FRESH}->{$name};
503 # }
504 return $cur
505 }
506 }
507 return undef;
508 }
509  
510 sub GetFirst {
511 my ($self, $name) = @_;
512 my @c = $self->GetList($name);
513 if (@c) {
514 return $c[0]
515 }
516 }
517  
518 sub GetLast {
519 my ($self, $name) = @_;
520 my @c = $self->GetList($name, 1);
521 if (@c) {
522 my $size = @c;
523 return $c[$size - 1]
524 }
525 }
526  
527 sub GetList {
528 my ($self, $name, $flag) = @_;
529 $flag = 0 unless defined $flag;
530 my $list = $self->list;
531 unless (defined $name) {
532 my @d = $list->infoChildren('');
533 if ($flag) {
534 my $size = @d;
535 return $list->infoChildren($d[$size - 1]);
536 } else {
537 return $list->infoChildren($d[0]);
538 }
539 } else {
540 return () unless $list->infoExists($name);
541 return $list->infoChildren($name);
542 }
543 }
544  
545 sub GoCurrent {
546 my $self = shift;
547 my $cur = $self->GetCurrent;
548 return unless defined $cur;
549 $self->Select($cur);
550 }
551  
552 sub IsSelected {
553 my ($self, $entry) = @_;
554 my $list = $self->list;
555 my ($sel) = $list->infoSelection;
556 return 0 unless defined $sel;
557 return $sel eq $entry
558 }
559  
560 sub list { return $_[0]->{RESULTSLIST} }
561  
562 sub OffsetGet {
563 my ($self, $name) = @_;
564 return $self->{OFFSET}->{$name} if exists $self->{OFFSET}->{$name};
565 return 0
566 }
567  
568 sub OffsetInc {
569 my ($self, $name) = @_;
570 my $offset = $self->OffsetGet($name);
571 $offset ++;
572 $self->OffsetSet($name, $offset);
573 }
574  
575 sub OffsetSet {
576 my ($self, $name, $offset) = @_;
577 $self->{OFFSET}->{$name} = $offset
578 }
579  
580 sub Replace {
581 my $self = shift;
582 my $cur = $self->GetCurrent;
583 unless (defined $cur) {
584 $self->logWarning('Nothing to replace');
585 return
586 }
587 my ($name, $index) = split(/@/, $cur);
588 my $widg = $self->DocWidget($name);
589 if (defined $self->Current) {
590 my $list = $self->list;
591 my ($begin, $end, $dummy, $captures) = $list->infoData($cur);
592 my $r = $self->{REPLACE};
593 my $replace = $$r;
594 if (@$captures) {
595 my $num = 1;
596 for (@$captures) {
597 my $cap = $_;
598 $replace =~ s/\$$num/$cap/g;
599 $num ++
600 }
601 }
602 $widg->replace($begin, $end, $replace);
603 $list->deleteEntry($cur);
604 $self->repl($self->repl + 1);
605 my @h = $list->infoChildren($name);
606 $list->deleteEntry($name) unless @h;
607 }
608 $self->GoCurrent unless $self->FinishedCheck;
609 }
610  
611 sub repl {
612 my $self = shift;
613 $self->{REPLACED} = shift if @_;
614 return $self->{REPLACED}
615 }
616  
617 sub Report {
618 my ($self, $flag) = @_;
619 $flag = 0 unless defined $flag;
620 my $rep = $self->repl;
621 my $skp = $self->skipped;
622 my $text = "Made $rep replaces and skipped $skp";
623 $text = "Replacing finished. $text" if $flag;
624 $self->log($text);
625 $self->FindActive(0) if $flag;
626 }
627  
628 sub Select {
629 my ($self, $entry) = @_;
630 my ($name, $index) = split(/@/, $entry);
631 my $mdi = $self->mdi;
632 my $list = $self->list;
633  
634 $list->selectionClear;
635 $list->anchorClear;
636 $list->selectionSet($entry);
637 return if $entry eq $name;
638 $self->Current($entry);
639 my ($begin, $end) = $list->infoData($entry);
640  
641 $self->cmdExecute('doc_open', $name) unless ($mdi->docExists($name));
642 $mdi->docSelect($name);
643 my $widg = $mdi->docGet($name)->CWidg;
644  
645 $widg->unselectAll;
646 $widg->goTo($begin);
647 $widg->focus;
648 }
649  
650 sub SelectFirst {
651 my $self = shift;
652 my $first = $self->GetFirst;
653 $self->Select($first) if defined $first
654 }
655  
656 sub SelectLast {
657 my $self = shift;
658 my $last = $self->GetLast;
659 $self->Select($last) if defined $last
660 }
661  
662 sub ShowResults {
663 my ($self, $log) = @_;
664 return unless $self->FindActive;
665 $log = 0 unless defined $log;
666 my $mdi = $self->mdi;
667 my $name = $mdi->docSelected;
668 return @_ unless defined $name;
669 my $widg = $mdi->docWidget;
670 my $list = $self->list;
671 my @hits = $self->GetList($name);
672 $widg->FindClear;
673 for (@hits) {
674 my $data = $list->infoData($_);
675 my ($begin, $end) = @$data;
676 $widg->tagAdd('Find', $begin, $end);
677 }
678 if ($log) {
679 my $nhits = @hits;
680 my @e = $list->infoChildren('');
681 my $ndocs = @e;
682 $self->after(10, sub {
683 $self->log("$nhits hits in $ndocs documents");
684 })
685 }
686 }
687  
688 sub Skip {
689 my $self = shift;
690 my $cur = $self->GetCurrent;
691 unless (defined $cur) {
692 $self->logWarning('Nothing to skip');
693 return
694 }
695 my ($name, $index) = split(/@/, $cur);
696 if (defined $self->Current) {
697 $self->OffsetInc($name);
698 $self->skipped($self->skipped + 1);
699 $self->Report;
700 }
701 $self->GoCurrent unless $self->FinishedCheck;
702 }
703  
704 sub skipped {
705 my $self = shift;
706 $self->{SKIPPED} = shift if @_;
707 return $self->{SKIPPED}
708 }
709  
710 sub Unload {
711 my $self = shift;
712 $self->ToolRightPageRemove('SearchReplace');
713 $self->cmdUnhookAfter('doc_select', 'DocResults', $self);
714 return $self->SUPER::Unload
715 }
716  
717 =head1 LICENSE
718  
719 Same as Perl.
720  
721 =head1 AUTHOR
722  
723 Hans Jeuken (hanje at cpan dot org)
724  
725 =head1 TODO
726  
727 =over 4
728  
729 =back
730  
731 =head1 BUGS AND CAVEATS
732  
733 If you find any bugs, please report them here L<https://github.com/haje61/App-Codit/issues>.
734  
735 =head1 SEE ALSO
736  
737 =over 4
738  
739 =back
740  
741 =cut
742  
743  
744  
745 1;
746  
747  
748  
749  
750  
751  
752  
753  
754  
755  
756  
757  
758  
759