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"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
23 #include "FuncRequest.h"
29 #include "frontends/alert.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/filetools.h"
34 #include "support/FileName.h"
35 #include "support/gettext.h"
36 #include "support/lassert.h"
37 #include "support/lstrings.h"
39 #include <QCloseEvent>
44 using namespace lyx::support;
50 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
51 : QTabWidget(&view), view_(view)
54 find_work_area_->setGuiView(view_);
55 find_work_area_->init();
56 find_work_area_->setFrameStyle(QFrame::StyledPanel);
58 setFocusProxy(find_work_area_);
59 replace_work_area_->setGuiView(view_);
60 replace_work_area_->init();
61 replace_work_area_->setFrameStyle(QFrame::StyledPanel);
63 // We don't want two cursors blinking.
64 find_work_area_->stopBlinkingCaret();
65 replace_work_area_->stopBlinkingCaret();
66 old_buffer_ = view_.documentBufferView() ?
67 &(view_.documentBufferView()->buffer()) : 0;
70 cbVerticalLayout->setAlignment(Qt::AlignTop);
71 pbVerticalLayout->setAlignment(Qt::AlignTop);
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)
90 if (event->type() != QEvent::KeyPress
91 || (obj != find_work_area_ && obj != replace_work_area_))
92 return QWidget::eventFilter(obj, event);
94 QKeyEvent * e = static_cast<QKeyEvent *> (event);
97 if (e->modifiers() == Qt::NoModifier) {
104 case Qt::Key_Return: {
105 bool const searchback = (e->modifiers() == Qt::ShiftModifier);
106 bool const replace = (obj == replace_work_area_);
107 findAndReplace(searchback, replace);
109 replace_work_area_->setFocus();
111 find_work_area_->setFocus();
116 if (e->modifiers() == Qt::NoModifier) {
117 if (obj == find_work_area_){
118 LYXERR(Debug::FINDVERBOSE, "Focusing replace WA");
119 replace_work_area_->setFocus();
120 LYXERR(Debug::FINDVERBOSE, "Selecting entire replace buffer");
121 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
122 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
128 case Qt::Key_Backtab:
129 if (obj == replace_work_area_) {
130 LYXERR(Debug::FINDVERBOSE, "Focusing find WA");
131 find_work_area_->setFocus();
132 LYXERR(Debug::FINDVERBOSE, "Selecting entire find buffer");
133 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
134 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
142 // standard event processing
143 return QWidget::eventFilter(obj, event);
147 static vector<string> const & allManualsFiles()
149 static const char * files[] = {
150 "Intro", "UserGuide", "Tutorial", "Additional",
151 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
152 "LFUNs", "LaTeXConfig"
155 static vector<string> v;
158 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
159 fname = i18nLibFileSearch("doc", files[i], "lyx");
160 v.push_back(fname.absFileName());
168 /** Switch buf to point to next document buffer.
170 ** Return true if restarted from master-document buffer.
172 static bool nextDocumentBuffer(Buffer * & buf)
174 ListOfBuffers const children = buf->allRelatives();
175 LYXERR(Debug::FINDVERBOSE, "children.size()=" << children.size());
176 ListOfBuffers::const_iterator it =
177 find(children.begin(), children.end(), buf);
178 LASSERT(it != children.end(), return false);
180 if (it == children.end()) {
181 buf = *children.begin();
189 /** Switch p_buf to point to previous document buffer.
191 ** Return true if restarted from last child buffer.
193 static bool prevDocumentBuffer(Buffer * & buf)
195 ListOfBuffers const children = buf->allRelatives();
196 LYXERR(Debug::FINDVERBOSE, "children.size()=" << children.size());
197 ListOfBuffers::const_iterator it =
198 find(children.begin(), children.end(), buf);
199 LASSERT(it != children.end(), return false)
200 if (it == children.begin()) {
212 /** Switch buf to point to next or previous buffer in search scope.
214 ** Return true if restarted from scratch.
216 static bool nextPrevBuffer(Buffer * & buf,
217 FindAndReplaceOptions const & opt)
219 bool restarted = false;
221 case FindAndReplaceOptions::S_BUFFER:
224 case FindAndReplaceOptions::S_DOCUMENT:
226 restarted = nextDocumentBuffer(buf);
228 restarted = prevDocumentBuffer(buf);
230 case FindAndReplaceOptions::S_OPEN_BUFFERS:
232 buf = theBufferList().next(buf);
233 restarted = (buf == *theBufferList().begin());
235 buf = theBufferList().previous(buf);
236 restarted = (buf == *(theBufferList().end() - 1));
239 case FindAndReplaceOptions::S_ALL_MANUALS:
240 vector<string> const & manuals = allManualsFiles();
241 vector<string>::const_iterator it =
242 find(manuals.begin(), manuals.end(), buf->absFileName());
243 if (it == manuals.end())
244 it = manuals.begin();
245 else if (opt.forward) {
247 if (it == manuals.end()) {
248 it = manuals.begin();
252 if (it == manuals.begin()) {
258 FileName const & fname = FileName(*it);
259 if (!theBufferList().exists(fname)) {
260 guiApp->currentView()->setBusy(false);
261 guiApp->currentView()->loadDocument(fname, false);
262 guiApp->currentView()->setBusy(true);
264 buf = theBufferList().getBuffer(fname);
271 /** Find the finest question message to post to the user */
272 docstring getQuestionString(FindAndReplaceOptions const & opt)
276 case FindAndReplaceOptions::S_BUFFER:
279 case FindAndReplaceOptions::S_DOCUMENT:
280 scope = _("Master document");
282 case FindAndReplaceOptions::S_OPEN_BUFFERS:
283 scope = _("Open files");
285 case FindAndReplaceOptions::S_ALL_MANUALS:
286 scope = _("Manuals");
289 docstring message = opt.forward ?
290 bformat(_("%1$s: the end was reached while searching forward.\n"
291 "Continue searching from the beginning?"),
293 bformat(_("%1$s: the beginning was reached while searching backward.\n"
294 "Continue searching from the end?"),
301 /// Return true if a match was found
302 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
304 BufferView * bv = view_.documentBufferView();
307 Buffer * buf = &bv->buffer();
308 Buffer * buf_orig = &bv->buffer();
309 DocIterator cur_orig(bv->cursor());
310 int wrap_answer = -1;
311 opt.replace_all = replace_all;
314 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
316 view_.message(_("Advanced search in progress (press ESC to cancel) . . ."));
317 theApp()->startLongOperation();
319 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
320 vector<string> const & v = allManualsFiles();
321 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
322 FileName const & fname = FileName(*v.begin());
323 if (!theBufferList().exists(fname)) {
324 guiApp->currentView()->setBusy(false);
325 theApp()->stopLongOperation();
326 guiApp->currentView()->loadDocument(fname, false);
327 theApp()->startLongOperation();
328 guiApp->currentView()->setBusy(true);
330 buf = theBufferList().getBuffer(fname);
332 view_.setBusy(false);
336 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
337 buf->absFileName()));
338 bv = view_.documentBufferView();
339 bv->cursor().clear();
340 bv->cursor().push_back(CursorSlice(buf->inset()));
344 UndoGroupHelper helper(buf);
347 LYXERR(Debug::FINDVERBOSE, "Dispatching LFUN_WORD_FINDADV");
349 LYXERR(Debug::FINDVERBOSE, "dispatched");
350 if (bv->cursor().result().dispatched()) {
351 // New match found and selected (old selection replaced if needed)
354 view_.setBusy(false);
355 theApp()->stopLongOperation();
357 } else if (replace_all)
358 bv->clearSelection();
360 if (theApp()->longOperationCancelled()) {
361 // Search aborted by user
362 view_.message(_("Advanced search cancelled by user"));
363 view_.setBusy(false);
364 theApp()->stopLongOperation();
368 // No match found in current buffer (however old selection might have been replaced)
369 // select next buffer in scope, if any
370 bool const prompt = nextPrevBuffer(buf, opt);
374 if (wrap_answer != -1)
376 docstring q = getQuestionString(opt);
377 view_.setBusy(false);
378 theApp()->stopLongOperation();
379 wrap_answer = frontend::Alert::prompt(
380 _("Wrap search?"), q,
381 0, 1, _("&Yes"), _("&No"));
382 theApp()->startLongOperation();
384 if (wrap_answer == 1)
387 if (buf != &view_.documentBufferView()->buffer())
388 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
389 buf->absFileName()));
391 helper.resetBuffer(buf);
393 bv = view_.documentBufferView();
395 bv->cursor().clear();
396 bv->cursor().push_back(CursorSlice(buf->inset()));
398 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
399 bv->cursor().setCursor(doc_iterator_end(buf));
400 bv->cursor().backwardPos();
401 LYXERR(Debug::FINDVERBOSE, "findBackAdv5: cur: "
404 bv->clearSelection();
405 } while (wrap_answer != 1);
407 if (buf_orig != &view_.documentBufferView()->buffer())
408 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
409 buf_orig->absFileName()));
410 bv = view_.documentBufferView();
411 // This may happen after a replace occurred
412 if (cur_orig.pos() > cur_orig.lastpos())
413 cur_orig.pos() = cur_orig.lastpos();
414 bv->cursor().setCursor(cur_orig);
415 view_.setBusy(false);
416 theApp()->stopLongOperation();
421 /// Return true if a match was found
422 bool FindAndReplaceWidget::findAndReplace(
423 bool casesensitive, bool matchword, bool backwards,
424 bool expandmacros, bool adhereformat, bool replace,
425 bool keep_case, bool replace_all)
427 Buffer & find_buf = find_work_area_->bufferView().buffer();
428 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
430 if (find_buf.text().empty()) {
431 view_.message(_("Nothing to search"));
435 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
436 docstring const & repl_buf_name = replace ?
437 repl_buf.fileName().absoluteFilePath() : docstring();
439 FindAndReplaceOptions::SearchScope scope =
440 FindAndReplaceOptions::S_BUFFER;
441 if (CurrentDocument->isChecked())
442 scope = FindAndReplaceOptions::S_BUFFER;
443 else if (MasterDocument->isChecked())
444 scope = FindAndReplaceOptions::S_DOCUMENT;
445 else if (OpenDocuments->isChecked())
446 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
447 else if (AllManualsRB->isChecked())
448 scope = FindAndReplaceOptions::S_ALL_MANUALS;
452 FindAndReplaceOptions::SearchRestriction restr =
453 OnlyMaths->isChecked()
454 ? FindAndReplaceOptions::R_ONLY_MATHS
455 : FindAndReplaceOptions::R_EVERYTHING;
457 LYXERR(Debug::FINDVERBOSE, "FindAndReplaceOptions: "
458 << "find_buf_name=" << find_buf_name
459 << ", casesensitiv=" << casesensitive
460 << ", matchword=" << matchword
461 << ", backwards=" << backwards
462 << ", expandmacros=" << expandmacros
463 << ", adhereformat=" << adhereformat
464 << ", repl_buf_name" << repl_buf_name
465 << ", keep_case=" << keep_case
466 << ", scope=" << scope
467 << ", restr=" << restr);
469 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
470 !backwards, expandmacros, !adhereformat,
471 repl_buf_name, keep_case, scope, restr);
475 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("language",
476 !adhereLanguageCB->isChecked())));
477 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("color",
478 !adhereColorCB->isChecked())));
479 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("family",
480 !adhereFFamilyCB->isChecked())));
481 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("series",
482 !adhereFSeriesCB->isChecked())));
483 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("shape",
484 !adhereFShapeCB->isChecked())));
485 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("size",
486 !adhereFSizeCB->isChecked())));
487 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("markup",
488 !adhereMarkupCB->isChecked())));
489 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("underline",
490 !adhereUnderlineCB->isChecked())));
491 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("strike",
492 !adhereStrikeCB->isChecked())));
493 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("deleted",
494 !adhereDeletedCB->isChecked())));
495 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("sectioning",
496 !adhereSectioningCB->isChecked())));
498 lyx::dispatch(FuncRequest(LFUN_SEARCH_IGNORE, checkState("non-output-content",
499 ignoreNonOutputCB->isChecked())));
501 return findAndReplaceScope(opt, replace_all);
505 docstring const FindAndReplaceWidget::checkState(string const s, bool const b)
507 docstring res = from_ascii(s) + from_ascii(" ");
509 res += from_ascii("true");
511 res += from_ascii("false");
516 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
518 if (! view_.currentMainWorkArea()) {
519 view_.message(_("No open document(s) in which to search"));
522 // Finalize macros that are being typed, both in main document and in search or replacement WAs
523 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
524 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
525 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
526 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
528 // FIXME: create a Dialog::returnFocus()
529 // or something instead of this:
530 view_.setCurrentWorkArea(view_.currentMainWorkArea());
531 return findAndReplace(caseCB->isChecked(),
532 wordsCB->isChecked(),
534 expandMacrosCB->isChecked(),
535 adhereFormatGB->isChecked(),
537 keepCaseCB->isChecked(),
542 void FindAndReplaceWidget::hideDialog()
544 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
548 void FindAndReplaceWidget::on_findNextPB_clicked()
550 findAndReplace(searchbackCB->isChecked(), false);
551 find_work_area_->setFocus();
555 void FindAndReplaceWidget::on_replacePB_clicked()
557 findAndReplace(searchbackCB->isChecked(), true);
558 replace_work_area_->setFocus();
562 void FindAndReplaceWidget::on_replaceallPB_clicked()
564 findAndReplace(searchbackCB->isChecked(), true, true);
565 replace_work_area_->setFocus();
569 void FindAndReplaceWidget::on_searchbackCB_clicked()
575 void FindAndReplaceWidget::setFormatIgnores(bool const b)
577 adhereLanguageCB->setChecked(b);
578 adhereColorCB->setChecked(b);
579 adhereFFamilyCB->setChecked(b);
580 adhereFSeriesCB->setChecked(b);
581 adhereFShapeCB->setChecked(b);
582 adhereFSizeCB->setChecked(b);
583 adhereMarkupCB->setChecked(b);
584 adhereUnderlineCB->setChecked(b);
585 adhereStrikeCB->setChecked(b);
586 adhereDeletedCB->setChecked(b);
587 adhereSectioningCB->setChecked(b);
591 void FindAndReplaceWidget::on_selectAllPB_clicked()
593 setFormatIgnores(true);
597 void FindAndReplaceWidget::on_deselectAllPB_clicked()
599 setFormatIgnores(false);
603 // Copy selected elements from bv's BufferParams to the dest_bv's
604 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
605 Buffer const & doc_buf = bv.buffer();
606 BufferParams const & doc_bp = doc_buf.params();
607 Buffer & dest_buf = dest_bv.buffer();
608 dest_buf.params().copyForAdvFR(doc_bp);
609 dest_bv.makeDocumentClass();
610 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
614 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
616 LYXERR(Debug::DEBUG, "showEvent()" << endl);
617 BufferView * bv = view_.documentBufferView();
619 copy_params(*bv, find_work_area_->bufferView());
620 copy_params(*bv, replace_work_area_->bufferView());
623 find_work_area_->installEventFilter(this);
624 replace_work_area_->installEventFilter(this);
626 view_.setCurrentWorkArea(find_work_area_);
627 LYXERR(Debug::FINDVERBOSE, "Selecting entire find buffer");
628 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
629 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
633 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
635 replace_work_area_->removeEventFilter(this);
636 find_work_area_->removeEventFilter(this);
637 this->QWidget::hideEvent(ev);
641 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
647 void FindAndReplace::updateView()
649 widget_->updateGUI();
650 widget_->updateButtons();
654 FindAndReplace::FindAndReplace(GuiView & parent,
655 Qt::DockWidgetArea area,
656 Qt::WindowFlags flags)
657 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
660 widget_ = new FindAndReplaceWidget(parent);
662 setFocusProxy(widget_);
664 // On Mac show and floating
668 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
669 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
673 FindAndReplace::~FindAndReplace()
675 setFocusProxy(nullptr);
680 bool FindAndReplace::initialiseParams(std::string const & params)
682 return widget_->initialiseParams(params);
686 void FindAndReplaceWidget::updateGUI()
688 BufferView * bv = view_.documentBufferView();
690 if (old_buffer_ != &bv->buffer()) {
691 copy_params(*bv, find_work_area_->bufferView());
692 copy_params(*bv, replace_work_area_->bufferView());
693 old_buffer_ = &bv->buffer();
696 old_buffer_ = nullptr;
698 bool const find_enabled = !find_work_area_->bufferView().buffer().empty();
699 findNextPB->setEnabled(find_enabled);
700 bool const replace_enabled = find_enabled && bv && !bv->buffer().isReadonly();
701 replaceLabel->setEnabled(replace_enabled);
702 replace_work_area_->setEnabled(replace_enabled);
703 replacePB->setEnabled(replace_enabled);
704 replaceallPB->setEnabled(replace_enabled);
708 void FindAndReplaceWidget::updateButtons()
710 if (searchbackCB->isChecked()) {
711 findNextPB->setText(qt_("&< Find"));
712 findNextPB->setToolTip(qt_("Find previous occurrence (Shift+Enter, forwards: Enter)"));
713 replacePB->setText(qt_("< Rep&lace"));
714 replacePB->setToolTip(qt_("Replace and find previous occurrence (Shift+Enter, forwards: Enter)"));
716 findNextPB->setText(qt_("Find &>"));
717 findNextPB->setToolTip(qt_("Find next occurrence (Enter, backwards: Shift+Enter)"));
718 replacePB->setText(qt_("Rep&lace >"));
719 replacePB->setToolTip(qt_("Replace and find next occurrence (Enter, backwards: Shift+Enter)"));
724 } // namespace frontend
728 #include "moc_FindAndReplace.cpp"