]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
Now ESC cancels long Advanced Find and Replace operations.
[lyx.git] / src / frontends / qt4 / FindAndReplace.cpp
1 /**
2  * \file FindAndReplace.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Tommaso Cucinotta
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "FindAndReplace.h"
14
15 #include "Lexer.h"
16 #include "GuiApplication.h"
17 #include "GuiView.h"
18 #include "GuiWorkArea.h"
19 #include "qt_helpers.h"
20 #include "Language.h"
21
22 #include "BufferParams.h"
23 #include "BufferList.h"
24 #include "TextClass.h"
25 #include "Cursor.h"
26 #include "FuncRequest.h"
27 #include "lyxfind.h"
28
29 #include "frontends/alert.h"
30
31 #include "support/debug.h"
32 #include "support/filetools.h"
33 #include "support/FileName.h"
34 #include "support/gettext.h"
35 #include "support/lassert.h"
36 #include "support/lstrings.h"
37
38 #include <QCloseEvent>
39 #include <QLineEdit>
40 #include <QMenu>
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46 namespace frontend {
47
48
49 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
50         : QTabWidget(&view), view_(view)
51 {
52         setupUi(this);
53         find_work_area_->setGuiView(view_);
54         find_work_area_->init();
55         find_work_area_->setFrameStyle(QFrame::StyledPanel);
56
57         setFocusProxy(find_work_area_);
58         replace_work_area_->setGuiView(view_);
59         replace_work_area_->init();
60         replace_work_area_->setFrameStyle(QFrame::StyledPanel);
61
62         // We don't want two cursors blinking.
63         find_work_area_->stopBlinkingCursor();
64         replace_work_area_->stopBlinkingCursor();
65 }
66
67
68 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
69 {
70         if (event->type() != QEvent::KeyPress
71                   || (obj != find_work_area_ && obj != replace_work_area_))
72                 return QWidget::eventFilter(obj, event);
73
74         QKeyEvent * e = static_cast<QKeyEvent *> (event);
75         switch (e->key()) {
76         case Qt::Key_Escape:
77                 if (e->modifiers() == Qt::NoModifier) {
78                         hideDialog();
79                         return true;
80                 }
81                 break;
82
83         case Qt::Key_Enter:
84         case Qt::Key_Return: {
85                 // with shift we (temporarily) change search/replace direction
86                 bool const searchback = searchbackCB->isChecked();
87                 if (e->modifiers() == Qt::ShiftModifier && !searchback)
88                         searchbackCB->setChecked(!searchback);
89
90                 if (obj == find_work_area_)
91                         on_findNextPB_clicked();
92                 else
93                         on_replacePB_clicked();
94                 // back to how it was
95                 searchbackCB->setChecked(searchback);
96                 return true;
97                 break;
98                 }
99         case Qt::Key_Tab:
100                 if (e->modifiers() == Qt::NoModifier) {
101                         if (obj == find_work_area_){
102                                 LYXERR(Debug::FIND, "Focusing replace WA");
103                                 replace_work_area_->setFocus();
104                                 LYXERR(Debug::FIND, "Selecting entire replace buffer");
105                                 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
106                                 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
107                                 return true;
108                         }
109                 }
110                 break;
111
112         case Qt::Key_Backtab:
113                 if (obj == replace_work_area_) {
114                         LYXERR(Debug::FIND, "Focusing find WA");
115                         find_work_area_->setFocus();
116                         LYXERR(Debug::FIND, "Selecting entire find buffer");
117                         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
118                         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
119                         return true;
120                 }
121                 break;
122
123         default:
124                 break;
125         }
126         // standard event processing
127         return QWidget::eventFilter(obj, event);
128 }
129
130
131 static vector<string> const & allManualsFiles() 
132 {
133         static vector<string> v;
134         static const char * files[] = {
135                 "Intro", "UserGuide", "Tutorial", "Additional",
136                 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
137                 "LFUNs", "LaTeXConfig"
138         };
139         if (v.empty()) {
140                 FileName fname;
141                 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
142                         fname = i18nLibFileSearch("doc", files[i], "lyx");
143                         v.push_back(fname.absFileName());
144                 }
145         }
146         return v;
147 }
148
149
150 /** Switch p_buf to point to next document buffer.
151  **
152  ** Return true if restarted from master-document buffer.
153  **/
154 static bool nextDocumentBuffer(Buffer * & buf) 
155 {
156         ListOfBuffers const children = buf->allRelatives();
157         LYXERR(Debug::FIND, "children.size()=" << children.size());
158         ListOfBuffers::const_iterator it =
159                 find(children.begin(), children.end(), buf);
160         LASSERT(it != children.end(), /**/);
161         ++it;
162         if (it == children.end()) {
163                 buf = *children.begin();
164                 return true;
165         }
166         buf = *it;
167         return false;
168 }
169
170
171 /** Switch p_buf to point to previous document buffer.
172  **
173  ** Return true if restarted from last child buffer.
174  **/
175 static bool prevDocumentBuffer(Buffer * & buf) 
176 {
177         ListOfBuffers const children = buf->allRelatives();
178         LYXERR(Debug::FIND, "children.size()=" << children.size());
179         ListOfBuffers::const_iterator it =
180                 find(children.begin(), children.end(), buf);
181         LASSERT(it != children.end(), /**/)
182         if (it == children.begin()) {
183                 it = children.end();
184                 --it;
185                 buf = *it;
186                 return true;
187         }
188         --it;
189         buf = *it;
190         return false;
191 }
192
193
194 /** Switch buf to point to next or previous buffer in search scope.
195  **
196  ** Return true if restarted from scratch.
197  **/
198 static bool nextPrevBuffer(Buffer * & buf,
199                              FindAndReplaceOptions const & opt)
200 {
201         bool restarted = false;
202         switch (opt.scope) {
203         case FindAndReplaceOptions::S_BUFFER:
204                 restarted = true;
205                 break;
206         case FindAndReplaceOptions::S_DOCUMENT:
207                 if (opt.forward)
208                         restarted = nextDocumentBuffer(buf);
209                 else
210                         restarted = prevDocumentBuffer(buf);
211                 break;
212         case FindAndReplaceOptions::S_OPEN_BUFFERS:
213                 if (opt.forward) {
214                         buf = theBufferList().next(buf);
215                         restarted = (buf == *theBufferList().begin());
216                 } else {
217                         buf = theBufferList().previous(buf);
218                         restarted = (buf == *(theBufferList().end() - 1));
219                 }
220                 break;
221         case FindAndReplaceOptions::S_ALL_MANUALS:
222                 vector<string> const & manuals = allManualsFiles();
223                 vector<string>::const_iterator it =
224                         find(manuals.begin(), manuals.end(), buf->absFileName());
225                 if (it == manuals.end())
226                         it = manuals.begin();
227                 else if (opt.forward) {
228                         ++it;
229                         if (it == manuals.end()) {
230                                 it = manuals.begin();
231                                 restarted = true;
232                         }
233                 } else {
234                         if (it == manuals.begin()) {
235                                 it = manuals.end();
236                                 restarted = true;
237                         }
238                         --it;
239                 }
240                 FileName const & fname = FileName(*it);
241                 if (!theBufferList().exists(fname)) {
242                         guiApp->currentView()->setBusy(false);
243                         guiApp->currentView()->loadDocument(fname, false);
244                         guiApp->currentView()->setBusy(true);
245                 }
246                 buf = theBufferList().getBuffer(fname);
247                 break;
248         }
249         return restarted;
250 }
251
252
253 /** Find the finest question message to post to the user */
254 docstring getQuestionString(FindAndReplaceOptions const & opt)
255 {
256         docstring scope;
257         switch (opt.scope) {
258         case FindAndReplaceOptions::S_BUFFER:
259                 scope = _("File");
260                 break;
261         case FindAndReplaceOptions::S_DOCUMENT:
262                 scope = _("Master document");
263                 break;
264         case FindAndReplaceOptions::S_OPEN_BUFFERS:
265                 scope = _("Open files");
266                 break;
267         case FindAndReplaceOptions::S_ALL_MANUALS:
268                 scope = _("Manuals");
269                 break;
270         }
271         docstring message = opt.forward ?
272                 bformat(_("%1$s: the end was reached while searching forward.\n"
273                           "Continue searching from the beginning?"),
274                         scope) : 
275                 bformat(_("%1$s: the beginning was reached while searching backward.\n"
276                           "Continue searching from the end?"),
277                         scope);
278
279         return message;
280 }
281
282
283 /// Return true if a match was found
284 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
285 {
286         BufferView * bv = view_.documentBufferView();
287         if (!bv)
288                 return false;
289         Buffer * buf = &bv->buffer();
290         Buffer * buf_orig = &bv->buffer();
291         DocIterator cur_orig(bv->cursor());
292         int wrap_answer = -1;
293         ostringstream oss;
294         oss << opt;
295         FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
296
297         view_.message(_("Advanced search started: please wait . . ."));
298         theApp()->startLongOperation();
299         view_.setBusy(true);
300         if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
301                 vector<string> const & v = allManualsFiles();
302                 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
303                         FileName const & fname = FileName(*v.begin());
304                         if (!theBufferList().exists(fname)) {
305                                 guiApp->currentView()->setBusy(false);
306                                 theApp()->stopLongOperation();
307                                 guiApp->currentView()->loadDocument(fname, false);
308                                 theApp()->startLongOperation();
309                                 guiApp->currentView()->setBusy(true);
310                         }
311                         buf = theBufferList().getBuffer(fname);
312                         if (!buf) {
313                                 view_.setBusy(false);
314                                 return false;
315                         }
316
317                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
318                                                   buf->absFileName()));
319                         bv = view_.documentBufferView();
320                         bv->cursor().clear();
321                         bv->cursor().push_back(CursorSlice(buf->inset()));
322                 }
323         }
324
325         do {
326                 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
327                 dispatch(cmd);
328                 LYXERR(Debug::FIND, "dispatched");
329                 if (bv->cursor().result().dispatched()) {
330                         // New match found and selected (old selection replaced if needed)
331                         if (replace_all)
332                                 continue;
333                         view_.setBusy(false);
334                         theApp()->stopLongOperation();
335                         return true;
336                 } else if (replace_all)
337                         bv->clearSelection();
338
339                 if (theApp()->longOperationCancelled()) {
340                         // Search aborted by user
341                         view_.message(_("Advanced search cancelled by user"));
342                         view_.setBusy(false);
343                         theApp()->stopLongOperation();
344                         return false;
345                 }
346
347                 // No match found in current buffer (however old selection might have been replaced)
348                 // select next buffer in scope, if any
349                 bool const prompt = nextPrevBuffer(buf, opt);
350                 if (!buf)
351                         break;
352                 if (prompt) {
353                         if (wrap_answer != -1)
354                                 break;
355                         docstring q = getQuestionString(opt);
356                         view_.setBusy(false);
357                         theApp()->stopLongOperation();
358                         wrap_answer = frontend::Alert::prompt(
359                                 _("Wrap search?"), q,
360                                 0, 1, _("&Yes"), _("&No"));
361                         theApp()->startLongOperation();
362                         view_.setBusy(true);
363                         if (wrap_answer == 1)
364                                 break;
365                 }
366                 if (buf != &view_.documentBufferView()->buffer())
367                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
368                                                   buf->absFileName()));
369                 bv = view_.documentBufferView();
370                 if (opt.forward) {
371                         bv->cursor().clear();
372                         bv->cursor().push_back(CursorSlice(buf->inset()));
373                 } else {
374                         //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
375                         bv->cursor().setCursor(doc_iterator_end(buf));
376                         bv->cursor().backwardPos();
377                         LYXERR(Debug::FIND, "findBackAdv5: cur: "
378                                 << bv->cursor());
379                 }
380                 bv->clearSelection();
381         } while (wrap_answer != 1);
382         if (buf_orig != &view_.documentBufferView()->buffer())
383                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
384                                           buf_orig->absFileName()));
385         bv = view_.documentBufferView();
386         // This may happen after a replace occurred
387         if (cur_orig.pos() > cur_orig.lastpos())
388                 cur_orig.pos() = cur_orig.lastpos();
389         bv->cursor().setCursor(cur_orig);
390         view_.setBusy(false);
391         theApp()->stopLongOperation();
392         return false;
393 }
394
395
396 /// Return true if a match was found
397 bool FindAndReplaceWidget::findAndReplace(
398         bool casesensitive, bool matchword, bool backwards,
399         bool expandmacros, bool ignoreformat, bool replace,
400         bool keep_case, bool replace_all)
401 {
402         Buffer & find_buf = find_work_area_->bufferView().buffer();
403         docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
404
405         if (find_buf.text().empty()) {
406                 view_.message(_("Nothing to search"));
407                 return false;
408         }
409
410         Buffer & repl_buf = replace_work_area_->bufferView().buffer();
411         docstring const & repl_buf_name = replace ?
412                 repl_buf.fileName().absoluteFilePath() : docstring();
413
414         FindAndReplaceOptions::SearchScope scope =
415                 FindAndReplaceOptions::S_BUFFER;
416         if (CurrentDocument->isChecked())
417                 scope = FindAndReplaceOptions::S_BUFFER;
418         else if (MasterDocument->isChecked())
419                 scope = FindAndReplaceOptions::S_DOCUMENT;
420         else if (OpenDocuments->isChecked())
421                 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
422         else if (AllManualsRB->isChecked())
423                 scope = FindAndReplaceOptions::S_ALL_MANUALS;
424         else
425                 LASSERT(false, /**/);
426         LYXERR(Debug::FIND, "FindAndReplaceOptions: "
427                << "find_buf_name=" << find_buf_name
428                << ", casesensitiv=" << casesensitive
429                << ", matchword=" << matchword
430                << ", backwards=" << backwards
431                << ", expandmacros=" << expandmacros
432                << ", ignoreformat=" << ignoreformat
433                << ", repl_buf_name" << repl_buf_name
434                << ", keep_case=" << keep_case
435                << ", scope=" << scope);
436         FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
437                                   !backwards, expandmacros, ignoreformat,
438                                   repl_buf_name, keep_case, scope);
439         return findAndReplaceScope(opt, replace_all);
440 }
441
442
443 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
444 {
445         if (! view_.currentMainWorkArea()) {
446                 view_.message(_("No open document(s) in which to search"));
447                 return false;
448         }
449         // Finalize macros that are being typed, both in main document and in search or replacement WAs
450         if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
451                 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
452         if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
453                 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
454
455         // FIXME: create a Dialog::returnFocus()
456         // or something instead of this:
457         view_.setCurrentWorkArea(view_.currentMainWorkArea());
458         return findAndReplace(caseCB->isChecked(),
459                 wordsCB->isChecked(),
460                 backwards,
461                 expandMacrosCB->isChecked(),
462                 ignoreFormatCB->isChecked(),
463                 replace,
464                 keepCaseCB->isChecked(),
465                 replace_all);
466 }
467
468
469 void FindAndReplaceWidget::hideDialog()
470 {
471         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
472 }
473
474
475 void FindAndReplaceWidget::on_findNextPB_clicked() 
476 {
477         findAndReplace(searchbackCB->isChecked(), false);
478         find_work_area_->setFocus();
479 }
480
481
482 void FindAndReplaceWidget::on_replacePB_clicked()
483 {
484         findAndReplace(searchbackCB->isChecked(), true);
485         replace_work_area_->setFocus();
486 }
487
488
489 void FindAndReplaceWidget::on_replaceallPB_clicked()
490 {
491         findAndReplace(searchbackCB->isChecked(), true, true);
492         replace_work_area_->setFocus();
493 }
494
495
496 /** Copy selected elements from bv's BufferParams to the dest_bv's one
497  ** We don't want to copy'em all, e.g., not the default master **/
498 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
499         Buffer const & doc_buf = bv.buffer();
500         BufferParams const & doc_bp = doc_buf.params();
501         string const & lang = doc_bp.language->lang();
502         string const & doc_class = doc_bp.documentClass().name();
503         Buffer & dest_buf = dest_bv.buffer();
504         dest_buf.params().setLanguage(lang);
505         dest_buf.params().setBaseClass(doc_class);
506         dest_buf.params().makeDocumentClass();
507         dest_bv.cursor().current_font.setLanguage(doc_bp.language);
508 }
509
510
511 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
512 {
513         LYXERR(Debug::DEBUG, "showEvent()" << endl);
514         BufferView * bv = view_.documentBufferView();
515         if (bv) {
516                 copy_params(*bv, find_work_area_->bufferView());
517                 copy_params(*bv, replace_work_area_->bufferView());
518         }
519
520         find_work_area_->installEventFilter(this);
521         replace_work_area_->installEventFilter(this);
522
523         view_.setCurrentWorkArea(find_work_area_);
524         LYXERR(Debug::FIND, "Selecting entire find buffer");
525         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
526         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
527 }
528
529
530 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
531 {
532         replace_work_area_->removeEventFilter(this);
533         find_work_area_->removeEventFilter(this);
534         this->QWidget::hideEvent(ev);
535 }
536
537
538 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
539 {
540         return true;
541 }
542
543
544 void FindAndReplace::updateView()
545 {
546         widget_->updateGUI();
547 }
548
549
550 FindAndReplace::FindAndReplace(GuiView & parent,
551                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
552         : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
553                    area, flags)
554 {
555         widget_ = new FindAndReplaceWidget(parent);
556         setWidget(widget_);
557         setFocusProxy(widget_);
558 }
559
560
561 FindAndReplace::~FindAndReplace()
562 {
563         setFocusProxy(0);
564         delete widget_;
565 }
566
567
568 bool FindAndReplace::initialiseParams(std::string const & params)
569 {
570         return widget_->initialiseParams(params);
571 }
572
573
574 void FindAndReplaceWidget::updateGUI()
575 {
576         bool replace_enabled = view_.documentBufferView()
577                 && !view_.documentBufferView()->buffer().isReadonly();
578         replace_work_area_->setEnabled(replace_enabled);
579         replacePB->setEnabled(replace_enabled);
580         replaceallPB->setEnabled(replace_enabled);
581 }
582
583
584 Dialog * createGuiSearchAdv(GuiView & lv)
585 {
586         FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
587 #ifdef Q_WS_MACX
588         // On Mac show and floating
589         gui->setFloating(true);
590 #endif
591         return gui;
592 }
593
594
595 } // namespace frontend
596 } // namespace lyx
597
598
599 #include "moc_FindAndReplace.cpp"