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