-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain_search.cc
1181 lines (1038 loc) · 36 KB
/
main_search.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ----------------------------------------------------------------------------
* Copyright (C) 2007-2010,2020 Th. Zoerner
* ----------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ----------------------------------------------------------------------------
*
* Module description:
*
* This module implements the class that performs searches in the text widget
* of the main window. The class has many interfaces that are connected to the
* main menu, key bindings in the main text window, and most importantly to the
* entry field and checkboxes of the main window's "find" toolbar.
*
* The class becomes active as soon as keyboard focus changes into the entry
* fields. For each modification of the entry text, the class immediately
* schedules a search in the background, and when found highlights the next
* match (via the Highligher module) and makes that text line visible in the
* main text widget. When global search highlighting is enabled, the class has
* the Highligher class mark all matches wihin visible part of the text (and
* start a background task for highlighting the rest of the document). When
* the user modifies the search pattern before this process is completed, it
* is aborted and restarted for the new pattern. When no match is found for the
* new pattern, the cursor and view are reset to the start of the search. The
* process described here is called "incremental search".
*
* In addition to the above, the class offers interfaces such as for repeating
* the previous search in either direction. Such searches are done
* "atomically", which means they are blocking. Notably the functionality for
* the "search all" button of the "find" toolbar is not implemented here, but
* rather in the search list class.
*/
#include <QApplication>
#include <QWidget>
#include <QKeyEvent>
#include <QShortcut>
#include <QPlainTextEdit>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
#include <QScrollBar>
#include <QCheckBox>
#include <QTextBlock>
#include <QTextDocument>
#include <QRegularExpression>
#include <QTimer>
#include <QJsonObject>
#include <QJsonArray>
#include <cstdio>
#include <string>
#include "main_win.h"
#include "main_text.h"
#include "main_search.h"
#include "highlighter.h"
#include "status_line.h"
#include "search_list.h"
#include "config_file.h"
#include "bg_task.h"
#include "text_block_find.h"
#include "dlg_bookmarks.h"
// ----------------------------------------------------------------------------
/**
* This wrapper class implements the search string entry field in the main
* window. The class is derived from QLineEdit for overriding the key and focus
* in/out event handlers. The events are forwarded directly to the MainSearch
* object.
*/
MainFindEnt::MainFindEnt(MainSearch * search, QWidget * parent)
: QLineEdit(parent)
, m_search(search)
{
connect(this, &QLineEdit::textChanged, m_search, &MainSearch::searchVarTrace);
}
void MainFindEnt::focusInEvent(QFocusEvent *e)
{
QLineEdit::focusInEvent(e);
m_search->searchInit();
}
void MainFindEnt::focusOutEvent(QFocusEvent *e)
{
QLineEdit::focusOutEvent(e);
m_search->searchLeave();
}
void MainFindEnt::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
case Qt::Key_Escape:
m_search->searchAbort();
break;
case Qt::Key_Return:
m_search->searchReturn();
break;
case Qt::Key_N:
if (e->modifiers() == Qt::ControlModifier)
m_search->searchIncrement(true, false);
else if (e->modifiers() == (Qt::ControlModifier + Qt::ShiftModifier))
m_search->searchIncrement(false, false);
else
QLineEdit::keyPressEvent(e);
break;
case Qt::Key_C:
if (e->modifiers() == Qt::ControlModifier)
m_search->searchAbort();
else
QLineEdit::keyPressEvent(e);
break;
case Qt::Key_X:
if (e->modifiers() == Qt::ControlModifier)
m_search->searchRemoveFromHistory();
else
QLineEdit::keyPressEvent(e);
break;
case Qt::Key_D:
if (e->modifiers() == Qt::ControlModifier)
m_search->searchComplete();
else if (e->modifiers() == (Qt::ControlModifier + Qt::ShiftModifier))
m_search->searchCompleteLeft();
else
QLineEdit::keyPressEvent(e);
break;
case Qt::Key_Up:
m_search->searchBrowseHistory(true);
break;
case Qt::Key_Down:
m_search->searchBrowseHistory(false);
break;
default:
QLineEdit::keyPressEvent(e);
break;
}
}
// ----------------------------------------------------------------------------
MainSearch::MainSearch(MainWin * mainWin)
: QObject(mainWin)
, m_mainWin(mainWin)
, m_histList(mainWin)
{
m_timSearchInc = new BgTask(this, BG_PRIO_SEARCH_INC);
}
/**
* Destructor: Freeing resources not automatically deleted via widget tree
*/
MainSearch::~MainSearch()
{
delete m_timSearchInc;
}
/**
* This external interface function is called once during start-up after all
* classes are instantiated to establish the required connections, which are
* the main text widget (within which this class performs searches), the
* Highlighter class (which is used to highlight search matches) and the
* widgets of the "find" toolbar (which provide user input to this class).
*/
void MainSearch::connectWidgets(MainText * mainText,
Highlighter * higl,
MainFindEnt * f2_e,
QCheckBox * f2_hall,
QCheckBox * f2_mcase,
QCheckBox * f2_regexp)
{
m_mainText = mainText;
m_higl = higl;
m_f2_e = f2_e;
m_f2_hall = f2_hall;
m_f2_mcase = f2_mcase;
m_f2_regexp = f2_regexp;
}
/**
* This function is called when writing the config file to retrieve persistent
* settings of this class. Currently these are the current search string and
* options.
*/
QJsonObject MainSearch::getRcValues()
{
QJsonObject obj;
// dump search settings
obj.insert("tlb_case", QJsonValue(tlb_find.m_opt_case));
obj.insert("tlb_regexp", QJsonValue(tlb_find.m_opt_regexp));
obj.insert("tlb_hall", QJsonValue(tlb_hall));
//TODO obj.insert("tlb_hist_maxlen", QJsonValue((int)TLB_HIST_MAXLEN));
obj.insert("tlb_history", m_histList.getRcValues());
return obj;
}
/**
* This function is called during start-up to apply configuration variables.
* The function is the inverse of getRcValues()
*/
void MainSearch::setRcValues(const QJsonObject& obj)
{
for (auto it = obj.begin(); it != obj.end(); ++it)
{
const QString& var = it.key();
const QJsonValue& val = it.value();
if (var == "tlb_case")
{
tlb_find.m_opt_case = val.toBool();
m_f2_mcase->setChecked(tlb_find.m_opt_case);
}
else if (var == "tlb_regexp")
{
tlb_find.m_opt_regexp = val.toBool();
m_f2_regexp->setChecked(tlb_find.m_opt_regexp);
}
else if (var == "tlb_hall")
{
tlb_hall = val.toBool();
m_f2_hall->setChecked(tlb_hall);
}
else if (var == "tlb_history")
{
m_histList.setRcValues(val.toArray());
}
else if (var == "tlb_hist_maxlen")
{
//TODO
}
else
fprintf(stderr, "trowser: unknown keyword %s in search RC config\n", var.toLatin1().data());
}
}
/**
* This function is bound to the "Highlight all" checkbutton and keyboard
* shortcut to enable or disable global highlighting of search matches.
*/
void MainSearch::searchOptToggleHall(int v)
{
tlb_hall = (v != 0);
searchHighlightSettingChange();
}
/**
* This function is bound to the "Reg.Exp." checkbutton and keyboard shortcut
* to enable or disable use of regular expression in search matches.
*/
void MainSearch::searchOptToggleRegExp(int v)
{
tlb_find.m_opt_regexp = (v != 0);
searchHighlightSettingChange();
}
/**
* This function is bound to the "Match case" checkbutton and keyboard shortcut
* to enable or disable use of regular expression in search matches.
*/
void MainSearch::searchOptToggleCase(int v)
{
tlb_find.m_opt_case = (v != 0);
searchHighlightSettingChange();
}
/**
* This function is invoked after a change in search settings (i.e. case
* match, reg.exp. or global highlighting.) The changed settings are
* stored in the RC file and a possible search highlighting is removed
* or updated (the latter only if global highlighting is enabled)
*/
void MainSearch::searchHighlightSettingChange()
{
if (m_f2_e->hasFocus())
{
searchIncrement(tlb_last_dir, true);
}
else
{
searchHighlightClear();
searchHighlightUpdateCurrent();
}
ConfigFile::updateRcAfterIdle();
}
/**
* This is a wrapper for the following function which works on the current
* pattern in the search entry field.
*/
void MainSearch::searchHighlightUpdateCurrent()
{
if (tlb_hall)
{
if (tlb_find.m_pat.isEmpty() == false)
{
if (searchExprCheck(tlb_find, true))
{
searchHighlightUpdate(tlb_find);
}
}
}
}
/**
* This function initiates global highlighting (using "search highlight"
* mark-up) of all lines matching the given pattern and options.
*/
void MainSearch::searchHighlightUpdate(const SearchPar& par)
{
Q_ASSERT(!par.m_pat.isEmpty());
m_higl->searchHighlightUpdate(par, m_f2_e->hasFocus());
}
/**
* This function clears highlighting of search results. This applies to all
* forms of search highlighting, namely (1) the specific line containing the
* last match, (2) incremental search highlight, and optional global search
* highlighting.
*/
void MainSearch::searchHighlightClear()
{
m_higl->searchHighlightClear();
}
// ----------------------------------------------------------------------------
/**
* This function is invoked when the user enters text in the "find" entry field.
* In contrary to the "atomic" search, this function only searches a small chunk
* of text, then re-schedules itself as an "idle" task. The search can be aborted
* at any time by canceling the task.
*/
void MainSearch::searchBackground(const SearchPar& par, bool is_fwd, int startPos, bool is_changed,
const std::function<void(QTextCursor&)>& callback)
{
bool isDone;
if (is_fwd)
{
QTextBlock b = m_mainText->document()->end();
if (b != m_mainText->document()->begin())
b = b.previous();
isDone = (startPos >= b.position() + b.length());
}
else
{
isDone = (startPos <= 0);
}
if (!isDone)
{
auto finder = MainTextFind::create(m_mainText->document(), par, is_fwd, startPos);
// invoke the actual search in the selected portion of the document
int matchPos, matchLen;
bool found = finder->findNext(matchPos, matchLen);
//printf("XXX %d -> %d,%d found?:%d\n", startPos, matchPos, matchLen, found);
if (found)
{
// match found -> report; done
QTextCursor c2 = m_mainText->textCursor();
c2.setPosition(matchPos);
c2.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, matchLen);
searchHandleMatch(c2, par, is_changed);
callback(c2);
}
else if (!finder->isDone())
{
// no match found in this portion -> reschedule next iteration
m_timSearchInc->start([=](){ searchBackground(par, is_fwd, matchPos, is_changed, callback); });
}
else
isDone = true;
}
if (isDone)
{
QTextCursor c2;
searchHandleMatch(c2, par, is_changed);
callback(c2);
}
}
/**
* This function searches the main text content for the given pattern in the
* given direction, starting at the current cursor position. When a match is
* found, the cursor is moved there and the line is highlighed. If no match is
* found, a warning is displayed and the cursor and previous search
* highlight(!) remains unchanged.
*
* The search is repeated the given number of times; if not enough matches are
* found before reaching the end of document, a warning is displayed, but the
* cursor is still moved to the last match and the function return value still
* indicates success.
*/
bool MainSearch::searchAtomic(const SearchPar& par, bool is_fwd, bool is_changed, int repCnt)
{
bool found = false;
if (!par.m_pat.isEmpty() && searchExprCheck(par, true))
{
m_mainText->cursorJumpPushPos();
tlb_last_dir = is_fwd;
QTextCursor lastMatch;
int repIdx;
for (repIdx = 0; repIdx < repCnt; ++repIdx)
{
int start_pos = searchGetBase(is_fwd, false);
auto match = m_mainText->findInDoc(par, is_fwd, start_pos);
if (match.isNull())
break;
lastMatch = match;
// determine new start position
match.setPosition(std::min(match.position(), match.anchor()));
m_mainText->setTextCursor(match);
}
if (!lastMatch.isNull())
{
if (repIdx < repCnt)
{
QString msg = QString("Only ") + QString::number(repIdx) + " of "
+ QString::number(repCnt) + " matches until "
+ (is_fwd ? "end" : "start") + " of file";
m_mainWin->mainStatusLine()->showWarning("search", msg);
}
// update cursor position and highlight
searchHandleMatch(lastMatch, par, is_changed);
found = true;
}
else // no match found at all
{
QString msg = QString("No match until ") + (is_fwd ? "end" : "start")
+ " of file" + (par.m_pat.isEmpty() ? "" : ": ") + par.m_pat;
m_mainWin->mainStatusLine()->showWarning("search", msg);
}
}
else
{
// empty or invalid expression: just remove old highlights
searchHighlightClear();
}
return found;
}
/**
* This function handles the result of a text search in the main window.
* If a match was found, the cursor is moved to the start of the match and
* the word, line are highlighted. Optionally, a background process to
* highlight all matches is started. If no match is found, any previously
* applies highlights are removed.
*/
void MainSearch::searchHandleMatch(QTextCursor& match, const SearchPar& par, bool is_changed)
{
if (!match.isNull() || is_changed)
{
m_higl->removeInc(m_mainText->document());
if (!tlb_hall) // else done below
searchHighlightClear();
}
if (!match.isNull())
{
// mark the matching text & complete line containing the match
m_higl->searchHighlightMatch(match);
// move the cursor to the beginning of the matching text
match.setPosition(std::min(match.position(), match.anchor()));
m_mainText->setTextCursor(match);
int line = match.block().blockNumber();
SearchList::signalHighlightLine(line);
SearchList::matchView(line);
DlgBookmarks::matchView(line);
}
if (tlb_hall)
{
searchHighlightUpdate(par);
}
}
/**
* This function is bound to all changes of the search text in the "find" entry
* field. It's called when the user enters new text and triggers an incremental
* search.
*/
void MainSearch::searchVarTrace(const QString & val)
{
tlb_find.m_pat = val;
m_histList.trackIter(m_histIter, val);
if (m_f2_e->hasFocus())
{
// delay start of search, to avoid jumps while user still typing fast
m_timSearchInc->start(SEARCH_INC_DELAY, [=, is_fwd=tlb_last_dir](){ searchIncrement(is_fwd, true); });
}
}
/**
* This function performs a so-called "incremental" search after the user
* has modified the search text. This means searches are started already
* while the user is typing.
*/
void MainSearch::searchIncrement(bool is_fwd, bool is_changed)
{
m_timSearchInc->stop();
if (!tlb_find.m_pat.isEmpty() && searchExprCheck(tlb_find, false))
{
if (tlb_inc_base < 0)
{
tlb_inc_base = searchGetBase(is_fwd, true);
tlb_inc_xview = m_mainText->verticalScrollBar()->value();
tlb_inc_yview = m_mainText->horizontalScrollBar()->value();
m_mainText->cursorJumpPushPos();
}
int start_pos;
if (is_changed)
{
searchHighlightClear();
start_pos = tlb_inc_base;
}
else
start_pos = searchGetBase(is_fwd, false);
searchBackground(tlb_find, is_fwd, start_pos, is_changed,
[=](QTextCursor& c){ searchIncMatch(c, is_fwd, is_changed); });
}
else
{
searchReset();
if (!tlb_find.m_pat.isEmpty())
m_mainWin->mainStatusLine()->showError("search", "Incomplete or invalid reg.exp.");
else
m_mainWin->mainStatusLine()->clearMessage("search");
}
}
/**
* This function is invoked as callback after a background search for the
* incremental search in the entry field is completed. (Before this call,
* cursor position and search highlights are already updated.)
*/
void MainSearch::searchIncMatch(QTextCursor& match, bool is_fwd, bool is_changed)
{
if (match.isNull() && (tlb_inc_base >= 0))
{
if (is_changed)
{
m_mainText->verticalScrollBar()->setValue(tlb_inc_xview);
m_mainText->horizontalScrollBar()->setValue(tlb_inc_yview);
QTextCursor c = m_mainText->textCursor();
c.setPosition(tlb_inc_base);
m_mainText->setTextCursor(c);
}
if (is_fwd)
m_mainWin->mainStatusLine()->showWarning("search", "No match until end of file");
else
m_mainWin->mainStatusLine()->showWarning("search", "No match until start of file");
}
else
m_mainWin->mainStatusLine()->clearMessage("search");
}
/**
* This function checks if the search pattern syntax is valid
*/
bool MainSearch::searchExprCheck(const SearchPar& par, bool display)
{
if (par.m_opt_regexp)
{
QRegularExpression re(par.m_pat);
if (re.isValid() == false)
{
if (display)
{
QString msg = QString("Syntax error in search expression: ")
+ re.errorString();
m_mainWin->mainStatusLine()->showError("search", msg);
}
return false;
}
}
return true;
}
/**
* This function returns the start address for a search. The first search
* starts at the insertion cursor. If the cursor is not visible, the search
* starts at the top or bottom of the visible text. When a search is repeated,
* the search must behind the previous match (for a forward search) to prevent
* finding the same word again, or finding an overlapping match. (For backwards
* searches overlaps cannot be handled via search arguments; such results are
* filtered out when a match is found.)
*/
int MainSearch::searchGetBase(bool is_fwd, bool is_init)
{
int view_start = m_mainText->cursorForPosition(QPoint(0, 0)).position();
QPoint bottom_right(m_mainText->viewport()->width() - 1, m_mainText->viewport()->height() - 1);
int view_end = m_mainText->cursorForPosition(bottom_right).position();
//cursor.setPosition(view_end, QTextCursor::KeepAnchor);
QTextCursor c = m_mainText->textCursor();
int cur_pos = c.position();
int start_pos;
if ((cur_pos >= view_start) && (cur_pos <= view_end))
{
if (is_init)
start_pos = cur_pos;
else if (is_fwd == false)
start_pos = ((cur_pos > 0) ? (cur_pos - 1) : 0);
else
{
auto lastBlk = m_mainText->document()->lastBlock();
int docLen = lastBlk.position() + lastBlk.length();
start_pos = ((cur_pos + 1 < docLen) ? (cur_pos + 1) : cur_pos);
}
}
else
{
start_pos = is_fwd ? view_start : view_end;
c.setPosition(cur_pos);
m_mainText->setTextCursor(c);
m_mainText->centerCursor();
}
return start_pos;
}
/**
* This function returns the current search pattern and options as configured
* via the widgets in the main window. If the search field is empty (maybe
* because a search was aborted via ESCAPE), the parameters of the last search
* are returned, equivalently as for search repetition via Next/Prev buttons.
*/
SearchPar MainSearch::getCurSearchParams()
{
if (!tlb_find.m_pat.isEmpty())
{
return tlb_find;
}
else if (!m_histList.isEmpty())
{
return m_histList.front();
}
else
return SearchPar();
}
/**
* This function is used by the search history and highlight pattern dialogs
* for searching one or more of the user-defined patterns within the main
* window. The cursor is set onto the first line matching one of the patterns
* in the given direction, if any.
*/
bool MainSearch::searchFirst(bool is_fwd, const std::vector<SearchPar>& patList)
{
m_mainText->cursorJumpPushPos();
searchHighlightClear();
m_histList.addMultiple(patList);
QTextCursor match;
const SearchPar * matchPar = nullptr;
int start_pos = searchGetBase(is_fwd, false);
for (auto& pat : patList)
{
if (pat.m_pat.isEmpty() || !searchExprCheck(pat, false))
continue;
auto c2 = m_mainText->findInDoc(pat, is_fwd, start_pos);
if ( !c2.isNull()
&& (match.isNull() || (is_fwd ? (c2 < match) : (c2 > match))) )
{
match = c2;
matchPar = &pat;
}
}
if (matchPar != nullptr)
{
m_mainWin->mainStatusLine()->clearMessage("search");
searchHandleMatch(match, *matchPar, true);
}
return (matchPar != nullptr);
}
/**
* This function is used by the highlight editor to copy a set of search
* parameters into the respective entry fields.
*/
void MainSearch::searchEnterOpt(const SearchPar& pat)
{
// force focus into find entry field & suppress "Enter" event
searchInit();
tlb_find_focus = true;
m_f2_e->setFocus(Qt::ShortcutFocusReason);
m_f2_e->activateWindow();
searchHighlightClear();
// copy parameters
tlb_find = pat;
// update widgets accordingly
m_f2_e->setText(pat.m_pat);
m_f2_regexp->setChecked(pat.m_opt_regexp);
m_f2_mcase->setChecked(pat.m_opt_case);
searchNext(tlb_last_dir);
}
/**
* This function is used by the various key bindings which repeat a previous
* search in the given direction. NOTE unlike vim, the direction parameter
* (e.g. derived from "n" vs "N") does not invert the direction of the previous
* search, but instead specifies the direction directly.
*
* If a match is found, the cursor is moved there and the line is marked using
* search highlighting. If no match is found, a warning is issued and a
* possible previous highlighting remains.
*/
bool MainSearch::searchNext(bool is_fwd, int repCnt)
{
bool found = false;
m_mainWin->mainStatusLine()->clearMessage("search");
if (!tlb_find.m_pat.isEmpty())
{
found = searchAtomic(tlb_find, is_fwd, false, repCnt);
}
else if (!m_histList.isEmpty())
{
// empty expression: repeat last search
const SearchPar &par = m_histList.front();
found = searchAtomic(par, is_fwd, false, repCnt);
}
else
{
m_mainWin->mainStatusLine()->showError("search", "No pattern defined for search");
}
return found;
}
/**
* This function is used by the "All" or "List all" buttons and assorted
* keyboard shortcuts to list all text lines matching the current search
* expression in a separate dialog window. In case the window is already open,
* the first parameter indicates if it should be raised. The second parameter
* indicates search range and direction: 0 to list all; -1 to list all above
* and including the cursor; +1 to list all below and including the cursor.
*/
void MainSearch::searchAll(bool raiseWin, int direction)
{
if (searchExprCheck(tlb_find, true))
{
m_histList.addEntry(tlb_find);
// make focus return and cursor jump back to original position
if (tlb_find_focus)
{
searchHighlightClear();
searchReset();
if (tlb_last_wid != nullptr)
{
// raise the caller's window above the main window
tlb_last_wid->setFocus(Qt::ShortcutFocusReason);
tlb_last_wid->activateWindow();
tlb_last_wid->raise();
}
else
{
// note more clean-up is triggered via the focus-out event
m_mainText->setFocus(Qt::ShortcutFocusReason);
}
}
SearchList::getInstance(raiseWin)->searchMatches(true, direction, tlb_find);
}
}
/**
* This function resets the state of the search engine. It is called when
* the search string is empty or a search is aborted with the Escape key.
*/
void MainSearch::searchReset()
{
searchHighlightClear();
if (tlb_inc_base >= 0)
{
m_mainText->verticalScrollBar()->setValue(tlb_inc_xview);
m_mainText->horizontalScrollBar()->setValue(tlb_inc_yview);
QTextCursor c = m_mainText->textCursor();
c.setPosition(tlb_inc_base);
m_mainText->setTextCursor(c);
tlb_inc_base = -1;
}
m_mainWin->mainStatusLine()->clearMessage("search");
}
/**
* This function is called when the "find" entry field receives keyboard focus
* to intialize the search state machine for a new search.
*/
void MainSearch::searchInit()
{
if (tlb_find_focus == false)
{
tlb_find_focus = true;
m_histIter.reset();
m_mainWin->mainStatusLine()->clearMessage("search");
}
}
/**
* This function is called to move keyboard focus into the search entry field.
* The focus change will trigger the "init" function. The caller can pass a
* widget to which focus is passed when leaving the search via the Return or
* Escape keys.
*/
void MainSearch::searchEnter(bool is_fwd, QWidget * parent)
{
tlb_last_dir = is_fwd;
tlb_find.m_pat.clear();
m_f2_e->setText(tlb_find.m_pat);
m_f2_e->setFocus(Qt::ShortcutFocusReason);
// clear "highlight all" since search pattern is reset above
searchHighlightClear();
tlb_last_wid = parent;
if (tlb_last_wid != nullptr)
{
tlb_last_wid->activateWindow();
tlb_last_wid->raise();
}
}
/**
* This function is bound to the FocusOut event in the search entry field.
* It resets the incremental search state.
*/
void MainSearch::searchLeave()
{
m_timSearchInc->stop();
// ignore if the keyboard focus is leaving towards another application
if (m_mainWin->focusWidget() != nullptr)
{
if (searchExprCheck(tlb_find, false))
{
searchHighlightUpdateCurrent();
m_histList.addEntry(tlb_find);
}
m_histIter.reset();
tlb_inc_base = -1;
tlb_last_wid = nullptr;
tlb_find_focus = false;
}
}
/**
* This function is called when the search window is left via "Escape" key.
* The search highlighting is removed and the search text is deleted.
*/
void MainSearch::searchAbort()
{
if (searchExprCheck(tlb_find, false))
{
m_histList.addEntry(tlb_find);
}
tlb_find.m_pat.clear();
m_f2_e->setText(tlb_find.m_pat);
searchReset();
if (tlb_last_wid != nullptr)
{
tlb_last_wid->setFocus(Qt::ShortcutFocusReason);
tlb_last_wid->activateWindow();
tlb_last_wid->raise();
}
else
{
m_mainText->setFocus(Qt::ShortcutFocusReason);
}
// note more clean-up is triggered via the focus-out event
}
/**
* This function is bound to the Return key in the search entry field.
* If the search pattern is invalid (reg.exp. syntax) an error message is
* displayed and the focus stays in the entry field. Else, the keyboard
* focus is switched to the main window.
*/
void MainSearch::searchReturn()
{
bool restart = false;
if (m_timSearchInc->isActive())
{
m_timSearchInc->stop();
restart = 1;
}
if (tlb_find.m_pat.isEmpty())
{
// empty expression: repeat last search
if (!m_histList.isEmpty())
{
tlb_find.m_pat = m_histList.front().m_pat;
m_f2_e->setText(tlb_find.m_pat);
restart = true;
}
else
{
m_mainWin->mainStatusLine()->showError("search", "No pattern defined for search repetition");
}
}
if (searchExprCheck(tlb_find, true))
{
if (restart)
{
// incremental search not completed -> start regular search
if (searchNext(tlb_last_dir) == false)
{
if (tlb_inc_base >= 0)
{
m_mainText->verticalScrollBar()->setValue(tlb_inc_xview);
m_mainText->horizontalScrollBar()->setValue(tlb_inc_yview);
QTextCursor c = m_mainText->textCursor();
c.setPosition(tlb_inc_base);
m_mainText->setTextCursor(c);
}
}
}
// note this implicitly triggers the leave event
if (tlb_last_wid != nullptr)
{
tlb_last_wid->setFocus(Qt::ShortcutFocusReason);
tlb_last_wid->activateWindow();
tlb_last_wid->raise();
}
else
{