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"
16 #include "GuiApplication.h"
18 #include "GuiWorkArea.h"
19 #include "qt_helpers.h"
23 #include "BufferParams.h"
24 #include "BufferList.h"
25 #include "BufferView.h"
27 #include "TextClass.h"
29 #include "FuncRequest.h"
33 #include "frontends/alert.h"
35 #include "support/debug.h"
36 #include "support/filetools.h"
37 #include "support/FileName.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
42 #include <QCloseEvent>
47 using namespace lyx::support;
53 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
54 : QTabWidget(&view), view_(view)
57 find_work_area_->setGuiView(view_);
58 find_work_area_->init();
59 find_work_area_->setFrameStyle(QFrame::StyledPanel);
61 setFocusProxy(find_work_area_);
62 replace_work_area_->setGuiView(view_);
63 replace_work_area_->init();
64 replace_work_area_->setFrameStyle(QFrame::StyledPanel);
66 // We don't want two cursors blinking.
67 find_work_area_->stopBlinkingCursor();
68 replace_work_area_->stopBlinkingCursor();
72 void FindAndReplaceWidget::dockLocationChanged(Qt::DockWidgetArea area)
74 if (area == Qt::RightDockWidgetArea || area == Qt::LeftDockWidgetArea) {
75 dynamicLayoutBasic_->setDirection(QBoxLayout::TopToBottom);
76 dynamicLayoutAdvanced_->setDirection(QBoxLayout::TopToBottom);
78 dynamicLayoutBasic_->setDirection(QBoxLayout::LeftToRight);
79 dynamicLayoutAdvanced_->setDirection(QBoxLayout::LeftToRight);
84 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
86 if (event->type() != QEvent::KeyPress
87 || (obj != find_work_area_ && obj != replace_work_area_))
88 return QWidget::eventFilter(obj, event);
90 QKeyEvent * e = static_cast<QKeyEvent *> (event);
93 if (e->modifiers() == Qt::NoModifier) {
100 case Qt::Key_Return: {
101 // with shift we (temporarily) change search/replace direction
102 bool const searchback = searchbackCB->isChecked();
103 if (e->modifiers() == Qt::ShiftModifier && !searchback)
104 searchbackCB->setChecked(!searchback);
106 if (obj == find_work_area_)
107 on_findNextPB_clicked();
109 on_replacePB_clicked();
110 // back to how it was
111 searchbackCB->setChecked(searchback);
116 if (e->modifiers() == Qt::NoModifier) {
117 if (obj == find_work_area_){
118 LYXERR(Debug::FIND, "Focusing replace WA");
119 replace_work_area_->setFocus();
120 LYXERR(Debug::FIND, "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::FIND, "Focusing find WA");
131 find_work_area_->setFocus();
132 LYXERR(Debug::FIND, "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 vector<string> v;
150 static const char * files[] = {
151 "Intro", "UserGuide", "Tutorial", "Additional",
152 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
153 "LFUNs", "LaTeXConfig"
157 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
158 fname = i18nLibFileSearch("doc", files[i], "lyx");
159 v.push_back(fname.absFileName());
166 /** Switch buf to point to next document buffer.
168 ** Return true if restarted from master-document buffer.
170 static bool nextDocumentBuffer(Buffer * & buf)
172 ListOfBuffers const children = buf->allRelatives();
173 LYXERR(Debug::FIND, "children.size()=" << children.size());
174 ListOfBuffers::const_iterator it =
175 find(children.begin(), children.end(), buf);
176 LASSERT(it != children.end(), return false);
178 if (it == children.end()) {
179 buf = *children.begin();
187 /** Switch p_buf to point to previous document buffer.
189 ** Return true if restarted from last child buffer.
191 static bool prevDocumentBuffer(Buffer * & buf)
193 ListOfBuffers const children = buf->allRelatives();
194 LYXERR(Debug::FIND, "children.size()=" << children.size());
195 ListOfBuffers::const_iterator it =
196 find(children.begin(), children.end(), buf);
197 LASSERT(it != children.end(), return false)
198 if (it == children.begin()) {
210 /** Switch buf to point to next or previous buffer in search scope.
212 ** Return true if restarted from scratch.
214 static bool nextPrevBuffer(Buffer * & buf,
215 FindAndReplaceOptions const & opt)
217 bool restarted = false;
219 case FindAndReplaceOptions::S_BUFFER:
222 case FindAndReplaceOptions::S_DOCUMENT:
224 restarted = nextDocumentBuffer(buf);
226 restarted = prevDocumentBuffer(buf);
228 case FindAndReplaceOptions::S_OPEN_BUFFERS:
230 buf = theBufferList().next(buf);
231 restarted = (buf == *theBufferList().begin());
233 buf = theBufferList().previous(buf);
234 restarted = (buf == *(theBufferList().end() - 1));
237 case FindAndReplaceOptions::S_ALL_MANUALS:
238 vector<string> const & manuals = allManualsFiles();
239 vector<string>::const_iterator it =
240 find(manuals.begin(), manuals.end(), buf->absFileName());
241 if (it == manuals.end())
242 it = manuals.begin();
243 else if (opt.forward) {
245 if (it == manuals.end()) {
246 it = manuals.begin();
250 if (it == manuals.begin()) {
256 FileName const & fname = FileName(*it);
257 if (!theBufferList().exists(fname)) {
258 guiApp->currentView()->setBusy(false);
259 guiApp->currentView()->loadDocument(fname, false);
260 guiApp->currentView()->setBusy(true);
262 buf = theBufferList().getBuffer(fname);
269 /** Find the finest question message to post to the user */
270 docstring getQuestionString(FindAndReplaceOptions const & opt)
274 case FindAndReplaceOptions::S_BUFFER:
277 case FindAndReplaceOptions::S_DOCUMENT:
278 scope = _("Master document");
280 case FindAndReplaceOptions::S_OPEN_BUFFERS:
281 scope = _("Open files");
283 case FindAndReplaceOptions::S_ALL_MANUALS:
284 scope = _("Manuals");
287 docstring message = opt.forward ?
288 bformat(_("%1$s: the end was reached while searching forward.\n"
289 "Continue searching from the beginning?"),
291 bformat(_("%1$s: the beginning was reached while searching backward.\n"
292 "Continue searching from the end?"),
299 /// Return true if a match was found
300 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
302 BufferView * bv = view_.documentBufferView();
305 Buffer * buf = &bv->buffer();
306 Buffer * buf_orig = &bv->buffer();
307 DocIterator cur_orig(bv->cursor());
308 int wrap_answer = -1;
311 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
313 view_.message(_("Advanced search in progress (press ESC to cancel) . . ."));
314 theApp()->startLongOperation();
316 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
317 vector<string> const & v = allManualsFiles();
318 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
319 FileName const & fname = FileName(*v.begin());
320 if (!theBufferList().exists(fname)) {
321 guiApp->currentView()->setBusy(false);
322 theApp()->stopLongOperation();
323 guiApp->currentView()->loadDocument(fname, false);
324 theApp()->startLongOperation();
325 guiApp->currentView()->setBusy(true);
327 buf = theBufferList().getBuffer(fname);
329 view_.setBusy(false);
333 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
334 buf->absFileName()));
335 bv = view_.documentBufferView();
336 bv->cursor().clear();
337 bv->cursor().push_back(CursorSlice(buf->inset()));
342 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
344 LYXERR(Debug::FIND, "dispatched");
345 if (bv->cursor().result().dispatched()) {
346 // New match found and selected (old selection replaced if needed)
349 view_.setBusy(false);
350 theApp()->stopLongOperation();
352 } else if (replace_all)
353 bv->clearSelection();
355 if (theApp()->longOperationCancelled()) {
356 // Search aborted by user
357 view_.message(_("Advanced search cancelled by user"));
358 view_.setBusy(false);
359 theApp()->stopLongOperation();
363 // No match found in current buffer (however old selection might have been replaced)
364 // select next buffer in scope, if any
365 bool const prompt = nextPrevBuffer(buf, opt);
369 if (wrap_answer != -1)
371 docstring q = getQuestionString(opt);
372 view_.setBusy(false);
373 theApp()->stopLongOperation();
374 wrap_answer = frontend::Alert::prompt(
375 _("Wrap search?"), q,
376 0, 1, _("&Yes"), _("&No"));
377 theApp()->startLongOperation();
379 if (wrap_answer == 1)
382 if (buf != &view_.documentBufferView()->buffer())
383 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
384 buf->absFileName()));
385 bv = view_.documentBufferView();
387 bv->cursor().clear();
388 bv->cursor().push_back(CursorSlice(buf->inset()));
390 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
391 bv->cursor().setCursor(doc_iterator_end(buf));
392 bv->cursor().backwardPos();
393 LYXERR(Debug::FIND, "findBackAdv5: cur: "
396 bv->clearSelection();
397 } while (wrap_answer != 1);
398 if (buf_orig != &view_.documentBufferView()->buffer())
399 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
400 buf_orig->absFileName()));
401 bv = view_.documentBufferView();
402 // This may happen after a replace occurred
403 if (cur_orig.pos() > cur_orig.lastpos())
404 cur_orig.pos() = cur_orig.lastpos();
405 bv->cursor().setCursor(cur_orig);
406 view_.setBusy(false);
407 theApp()->stopLongOperation();
412 /// Return true if a match was found
413 bool FindAndReplaceWidget::findAndReplace(
414 bool casesensitive, bool matchword, bool backwards,
415 bool expandmacros, bool ignoreformat, bool replace,
416 bool keep_case, bool replace_all)
418 Buffer & find_buf = find_work_area_->bufferView().buffer();
419 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
421 if (find_buf.text().empty()) {
422 view_.message(_("Nothing to search"));
426 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
427 docstring const & repl_buf_name = replace ?
428 repl_buf.fileName().absoluteFilePath() : docstring();
430 FindAndReplaceOptions::SearchScope scope =
431 FindAndReplaceOptions::S_BUFFER;
432 if (CurrentDocument->isChecked())
433 scope = FindAndReplaceOptions::S_BUFFER;
434 else if (MasterDocument->isChecked())
435 scope = FindAndReplaceOptions::S_DOCUMENT;
436 else if (OpenDocuments->isChecked())
437 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
438 else if (AllManualsRB->isChecked())
439 scope = FindAndReplaceOptions::S_ALL_MANUALS;
443 FindAndReplaceOptions::SearchRestriction restr =
444 OnlyMaths->isChecked()
445 ? FindAndReplaceOptions::R_ONLY_MATHS
446 : FindAndReplaceOptions::R_EVERYTHING;
448 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
449 << "find_buf_name=" << find_buf_name
450 << ", casesensitiv=" << casesensitive
451 << ", matchword=" << matchword
452 << ", backwards=" << backwards
453 << ", expandmacros=" << expandmacros
454 << ", ignoreformat=" << ignoreformat
455 << ", repl_buf_name" << repl_buf_name
456 << ", keep_case=" << keep_case
457 << ", scope=" << scope
458 << ", restr=" << restr);
460 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
461 !backwards, expandmacros, ignoreformat,
462 repl_buf_name, keep_case, scope, restr);
463 return findAndReplaceScope(opt, replace_all);
467 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
469 if (! view_.currentMainWorkArea()) {
470 view_.message(_("No open document(s) in which to search"));
473 // Finalize macros that are being typed, both in main document and in search or replacement WAs
474 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
475 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
476 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
477 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
479 // FIXME: create a Dialog::returnFocus()
480 // or something instead of this:
481 view_.setCurrentWorkArea(view_.currentMainWorkArea());
482 return findAndReplace(caseCB->isChecked(),
483 wordsCB->isChecked(),
485 expandMacrosCB->isChecked(),
486 ignoreFormatCB->isChecked(),
488 keepCaseCB->isChecked(),
493 void FindAndReplaceWidget::hideDialog()
495 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
499 void FindAndReplaceWidget::on_findNextPB_clicked()
501 findAndReplace(searchbackCB->isChecked(), false);
502 find_work_area_->setFocus();
506 void FindAndReplaceWidget::on_replacePB_clicked()
508 findAndReplace(searchbackCB->isChecked(), true);
509 replace_work_area_->setFocus();
513 void FindAndReplaceWidget::on_replaceallPB_clicked()
515 findAndReplace(searchbackCB->isChecked(), true, true);
516 replace_work_area_->setFocus();
520 /** Copy selected elements from bv's BufferParams to the dest_bv's one
521 ** We don't want to copy'em all, e.g., not the default master **/
522 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
523 Buffer const & doc_buf = bv.buffer();
524 BufferParams const & doc_bp = doc_buf.params();
525 string const & lang = doc_bp.language->lang();
526 string const & doc_class = doc_bp.documentClass().name();
527 Buffer & dest_buf = dest_bv.buffer();
528 dest_buf.params().setLanguage(lang);
529 dest_buf.params().setBaseClass(doc_class);
530 dest_bv.makeDocumentClass();
531 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
535 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
537 LYXERR(Debug::DEBUG, "showEvent()" << endl);
538 BufferView * bv = view_.documentBufferView();
540 copy_params(*bv, find_work_area_->bufferView());
541 copy_params(*bv, replace_work_area_->bufferView());
544 find_work_area_->installEventFilter(this);
545 replace_work_area_->installEventFilter(this);
547 view_.setCurrentWorkArea(find_work_area_);
548 LYXERR(Debug::FIND, "Selecting entire find buffer");
549 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
550 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
554 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
556 replace_work_area_->removeEventFilter(this);
557 find_work_area_->removeEventFilter(this);
558 this->QWidget::hideEvent(ev);
562 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
568 void FindAndReplace::updateView()
570 widget_->updateGUI();
574 FindAndReplace::FindAndReplace(GuiView & parent,
575 Qt::DockWidgetArea area, Qt::WindowFlags flags)
576 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
579 widget_ = new FindAndReplaceWidget(parent);
581 setFocusProxy(widget_);
583 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
584 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
588 FindAndReplace::~FindAndReplace()
595 bool FindAndReplace::initialiseParams(std::string const & params)
597 return widget_->initialiseParams(params);
601 void FindAndReplaceWidget::updateGUI()
603 bool replace_enabled = view_.documentBufferView()
604 && !view_.documentBufferView()->buffer().isReadonly();
605 replace_work_area_->setEnabled(replace_enabled);
606 replacePB->setEnabled(replace_enabled);
607 replaceallPB->setEnabled(replace_enabled);
611 Dialog * createGuiSearchAdv(GuiView & lv)
613 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
615 // On Mac show and floating
616 gui->setFloating(true);
622 } // namespace frontend
626 #include "moc_FindAndReplace.cpp"