2 * \file FindAndReplace.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Tommaso Cucinotta
8 * Full author contact details are available in file CREDITS.
13 #include "FindAndReplace.h"
15 #include "GuiApplication.h"
17 #include "GuiWorkArea.h"
18 #include "qt_helpers.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
25 #include "FuncRequest.h"
31 #include "TextClass.h"
33 #include "frontends/alert.h"
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"
43 #include <QCloseEvent>
48 using namespace lyx::support;
54 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
55 : QTabWidget(&view), view_(view)
58 find_work_area_->setGuiView(view_);
59 find_work_area_->init();
60 find_work_area_->setFrameStyle(QFrame::StyledPanel);
62 setFocusProxy(find_work_area_);
63 replace_work_area_->setGuiView(view_);
64 replace_work_area_->init();
65 replace_work_area_->setFrameStyle(QFrame::StyledPanel);
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;
75 void FindAndReplaceWidget::dockLocationChanged(Qt::DockWidgetArea area)
77 if (area == Qt::RightDockWidgetArea || area == Qt::LeftDockWidgetArea) {
78 dynamicLayoutBasic_->setDirection(QBoxLayout::TopToBottom);
79 dynamicLayoutAdvanced_->setDirection(QBoxLayout::TopToBottom);
81 dynamicLayoutBasic_->setDirection(QBoxLayout::LeftToRight);
82 dynamicLayoutAdvanced_->setDirection(QBoxLayout::LeftToRight);
87 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
89 if (event->type() != QEvent::KeyPress
90 || (obj != find_work_area_ && obj != replace_work_area_))
91 return QWidget::eventFilter(obj, event);
93 QKeyEvent * e = static_cast<QKeyEvent *> (event);
96 if (e->modifiers() == Qt::NoModifier) {
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);
109 if (obj == find_work_area_)
110 on_findNextPB_clicked();
112 on_replacePB_clicked();
113 // back to how it was
114 searchbackCB->setChecked(searchback);
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));
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));
145 // standard event processing
146 return QWidget::eventFilter(obj, event);
150 static vector<string> const & allManualsFiles()
152 static const char * files[] = {
153 "Intro", "UserGuide", "Tutorial", "Additional",
154 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
155 "LFUNs", "LaTeXConfig"
158 static vector<string> v;
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());
171 /** Switch buf to point to next document buffer.
173 ** Return true if restarted from master-document buffer.
175 static bool nextDocumentBuffer(Buffer * & buf)
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);
183 if (it == children.end()) {
184 buf = *children.begin();
192 /** Switch p_buf to point to previous document buffer.
194 ** Return true if restarted from last child buffer.
196 static bool prevDocumentBuffer(Buffer * & buf)
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()) {
215 /** Switch buf to point to next or previous buffer in search scope.
217 ** Return true if restarted from scratch.
219 static bool nextPrevBuffer(Buffer * & buf,
220 FindAndReplaceOptions const & opt)
222 bool restarted = false;
224 case FindAndReplaceOptions::S_BUFFER:
227 case FindAndReplaceOptions::S_DOCUMENT:
229 restarted = nextDocumentBuffer(buf);
231 restarted = prevDocumentBuffer(buf);
233 case FindAndReplaceOptions::S_OPEN_BUFFERS:
235 buf = theBufferList().next(buf);
236 restarted = (buf == *theBufferList().begin());
238 buf = theBufferList().previous(buf);
239 restarted = (buf == *(theBufferList().end() - 1));
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) {
250 if (it == manuals.end()) {
251 it = manuals.begin();
255 if (it == manuals.begin()) {
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);
267 buf = theBufferList().getBuffer(fname);
274 /** Find the finest question message to post to the user */
275 docstring getQuestionString(FindAndReplaceOptions const & opt)
279 case FindAndReplaceOptions::S_BUFFER:
282 case FindAndReplaceOptions::S_DOCUMENT:
283 scope = _("Master document");
285 case FindAndReplaceOptions::S_OPEN_BUFFERS:
286 scope = _("Open files");
288 case FindAndReplaceOptions::S_ALL_MANUALS:
289 scope = _("Manuals");
292 docstring message = opt.forward ?
293 bformat(_("%1$s: the end was reached while searching forward.\n"
294 "Continue searching from the beginning?"),
296 bformat(_("%1$s: the beginning was reached while searching backward.\n"
297 "Continue searching from the end?"),
304 /// Return true if a match was found
305 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
307 BufferView * bv = view_.documentBufferView();
310 Buffer * buf = &bv->buffer();
311 Buffer * buf_orig = &bv->buffer();
312 DocIterator cur_orig(bv->cursor());
313 int wrap_answer = -1;
316 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
318 view_.message(_("Advanced search in progress (press ESC to cancel) . . ."));
319 theApp()->startLongOperation();
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);
332 buf = theBufferList().getBuffer(fname);
334 view_.setBusy(false);
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()));
346 UndoGroupHelper helper(buf);
349 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
351 LYXERR(Debug::FIND, "dispatched");
352 if (bv->cursor().result().dispatched()) {
353 // New match found and selected (old selection replaced if needed)
356 view_.setBusy(false);
357 theApp()->stopLongOperation();
359 } else if (replace_all)
360 bv->clearSelection();
362 if (theApp()->longOperationCancelled()) {
363 // Search aborted by user
364 view_.message(_("Advanced search cancelled by user"));
365 view_.setBusy(false);
366 theApp()->stopLongOperation();
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);
376 if (wrap_answer != -1)
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();
386 if (wrap_answer == 1)
389 if (buf != &view_.documentBufferView()->buffer())
390 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
391 buf->absFileName()));
393 helper.resetBuffer(buf);
395 bv = view_.documentBufferView();
397 bv->cursor().clear();
398 bv->cursor().push_back(CursorSlice(buf->inset()));
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: "
406 bv->clearSelection();
407 } while (wrap_answer != 1);
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();
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)
429 Buffer & find_buf = find_work_area_->bufferView().buffer();
430 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
432 if (find_buf.text().empty()) {
433 view_.message(_("Nothing to search"));
437 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
438 docstring const & repl_buf_name = replace ?
439 repl_buf.fileName().absoluteFilePath() : docstring();
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;
454 FindAndReplaceOptions::SearchRestriction restr =
455 OnlyMaths->isChecked()
456 ? FindAndReplaceOptions::R_ONLY_MATHS
457 : FindAndReplaceOptions::R_EVERYTHING;
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);
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);
478 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
480 if (! view_.currentMainWorkArea()) {
481 view_.message(_("No open document(s) in which to search"));
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);
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(),
496 expandMacrosCB->isChecked(),
497 ignoreFormatCB->isChecked(),
499 keepCaseCB->isChecked(),
504 void FindAndReplaceWidget::hideDialog()
506 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
510 void FindAndReplaceWidget::on_findNextPB_clicked()
512 findAndReplace(searchbackCB->isChecked(), false);
513 find_work_area_->setFocus();
517 void FindAndReplaceWidget::on_replacePB_clicked()
519 findAndReplace(searchbackCB->isChecked(), true);
520 replace_work_area_->setFocus();
524 void FindAndReplaceWidget::on_replaceallPB_clicked()
526 findAndReplace(searchbackCB->isChecked(), true, true);
527 replace_work_area_->setFocus();
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);
542 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
544 LYXERR(Debug::DEBUG, "showEvent()" << endl);
545 BufferView * bv = view_.documentBufferView();
547 copy_params(*bv, find_work_area_->bufferView());
548 copy_params(*bv, replace_work_area_->bufferView());
551 find_work_area_->installEventFilter(this);
552 replace_work_area_->installEventFilter(this);
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));
561 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
563 replace_work_area_->removeEventFilter(this);
564 find_work_area_->removeEventFilter(this);
565 this->QWidget::hideEvent(ev);
569 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
575 void FindAndReplace::updateView()
577 widget_->updateGUI();
581 FindAndReplace::FindAndReplace(GuiView & parent,
582 Qt::DockWidgetArea area, Qt::WindowFlags flags)
583 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
586 widget_ = new FindAndReplaceWidget(parent);
588 setFocusProxy(widget_);
590 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
591 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
595 FindAndReplace::~FindAndReplace()
602 bool FindAndReplace::initialiseParams(std::string const & params)
604 return widget_->initialiseParams(params);
608 void FindAndReplaceWidget::updateGUI()
610 BufferView * bv = view_.documentBufferView();
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();
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);
627 Dialog * createGuiSearchAdv(GuiView & lv)
629 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
631 // On Mac show and floating
632 gui->setFloating(true);
638 } // namespace frontend
642 #include "moc_FindAndReplace.cpp"