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 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::FIND, "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::FIND, "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;
313 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
315 view_.message(_("Advanced search in progress (press ESC to cancel) . . ."));
316 theApp()->startLongOperation();
318 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
319 vector<string> const & v = allManualsFiles();
320 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
321 FileName const & fname = FileName(*v.begin());
322 if (!theBufferList().exists(fname)) {
323 guiApp->currentView()->setBusy(false);
324 theApp()->stopLongOperation();
325 guiApp->currentView()->loadDocument(fname, false);
326 theApp()->startLongOperation();
327 guiApp->currentView()->setBusy(true);
329 buf = theBufferList().getBuffer(fname);
331 view_.setBusy(false);
335 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
336 buf->absFileName()));
337 bv = view_.documentBufferView();
338 bv->cursor().clear();
339 bv->cursor().push_back(CursorSlice(buf->inset()));
343 UndoGroupHelper helper(buf);
346 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
348 LYXERR(Debug::FIND, "dispatched");
349 if (bv->cursor().result().dispatched()) {
350 // New match found and selected (old selection replaced if needed)
353 view_.setBusy(false);
354 theApp()->stopLongOperation();
356 } else if (replace_all)
357 bv->clearSelection();
359 if (theApp()->longOperationCancelled()) {
360 // Search aborted by user
361 view_.message(_("Advanced search cancelled by user"));
362 view_.setBusy(false);
363 theApp()->stopLongOperation();
367 // No match found in current buffer (however old selection might have been replaced)
368 // select next buffer in scope, if any
369 bool const prompt = nextPrevBuffer(buf, opt);
373 if (wrap_answer != -1)
375 docstring q = getQuestionString(opt);
376 view_.setBusy(false);
377 theApp()->stopLongOperation();
378 wrap_answer = frontend::Alert::prompt(
379 _("Wrap search?"), q,
380 0, 1, _("&Yes"), _("&No"));
381 theApp()->startLongOperation();
383 if (wrap_answer == 1)
386 if (buf != &view_.documentBufferView()->buffer())
387 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
388 buf->absFileName()));
390 helper.resetBuffer(buf);
392 bv = view_.documentBufferView();
394 bv->cursor().clear();
395 bv->cursor().push_back(CursorSlice(buf->inset()));
397 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
398 bv->cursor().setCursor(doc_iterator_end(buf));
399 bv->cursor().backwardPos();
400 LYXERR(Debug::FIND, "findBackAdv5: cur: "
403 bv->clearSelection();
404 } while (wrap_answer != 1);
406 if (buf_orig != &view_.documentBufferView()->buffer())
407 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
408 buf_orig->absFileName()));
409 bv = view_.documentBufferView();
410 // This may happen after a replace occurred
411 if (cur_orig.pos() > cur_orig.lastpos())
412 cur_orig.pos() = cur_orig.lastpos();
413 bv->cursor().setCursor(cur_orig);
414 view_.setBusy(false);
415 theApp()->stopLongOperation();
420 /// Return true if a match was found
421 bool FindAndReplaceWidget::findAndReplace(
422 bool casesensitive, bool matchword, bool backwards,
423 bool expandmacros, bool ignoreformat, bool replace,
424 bool keep_case, bool replace_all)
426 Buffer & find_buf = find_work_area_->bufferView().buffer();
427 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
429 if (find_buf.text().empty()) {
430 view_.message(_("Nothing to search"));
434 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
435 docstring const & repl_buf_name = replace ?
436 repl_buf.fileName().absoluteFilePath() : docstring();
438 FindAndReplaceOptions::SearchScope scope =
439 FindAndReplaceOptions::S_BUFFER;
440 if (CurrentDocument->isChecked())
441 scope = FindAndReplaceOptions::S_BUFFER;
442 else if (MasterDocument->isChecked())
443 scope = FindAndReplaceOptions::S_DOCUMENT;
444 else if (OpenDocuments->isChecked())
445 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
446 else if (AllManualsRB->isChecked())
447 scope = FindAndReplaceOptions::S_ALL_MANUALS;
451 FindAndReplaceOptions::SearchRestriction restr =
452 OnlyMaths->isChecked()
453 ? FindAndReplaceOptions::R_ONLY_MATHS
454 : FindAndReplaceOptions::R_EVERYTHING;
456 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
457 << "find_buf_name=" << find_buf_name
458 << ", casesensitiv=" << casesensitive
459 << ", matchword=" << matchword
460 << ", backwards=" << backwards
461 << ", expandmacros=" << expandmacros
462 << ", ignoreformat=" << ignoreformat
463 << ", repl_buf_name" << repl_buf_name
464 << ", keep_case=" << keep_case
465 << ", scope=" << scope
466 << ", restr=" << restr);
468 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
469 !backwards, expandmacros, ignoreformat,
470 repl_buf_name, keep_case, scope, restr);
471 return findAndReplaceScope(opt, replace_all);
475 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
477 if (! view_.currentMainWorkArea()) {
478 view_.message(_("No open document(s) in which to search"));
481 // Finalize macros that are being typed, both in main document and in search or replacement WAs
482 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
483 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
484 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
485 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
487 // FIXME: create a Dialog::returnFocus()
488 // or something instead of this:
489 view_.setCurrentWorkArea(view_.currentMainWorkArea());
490 return findAndReplace(caseCB->isChecked(),
491 wordsCB->isChecked(),
493 expandMacrosCB->isChecked(),
494 ignoreFormatCB->isChecked(),
496 keepCaseCB->isChecked(),
501 void FindAndReplaceWidget::hideDialog()
503 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
507 void FindAndReplaceWidget::on_findNextPB_clicked()
509 findAndReplace(searchbackCB->isChecked(), false);
510 find_work_area_->setFocus();
514 void FindAndReplaceWidget::on_replacePB_clicked()
516 findAndReplace(searchbackCB->isChecked(), true);
517 replace_work_area_->setFocus();
521 void FindAndReplaceWidget::on_replaceallPB_clicked()
523 findAndReplace(searchbackCB->isChecked(), true, true);
524 replace_work_area_->setFocus();
528 /** Copy selected elements from bv's BufferParams to the dest_bv's one
529 ** We don't want to copy'em all, e.g., not the default master **/
530 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
531 Buffer const & doc_buf = bv.buffer();
532 BufferParams const & doc_bp = doc_buf.params();
533 string const & lang = doc_bp.language->lang();
534 string const & doc_class = doc_bp.documentClass().name();
535 Buffer & dest_buf = dest_bv.buffer();
536 dest_buf.params().setLanguage(lang);
537 dest_buf.params().setBaseClass(doc_class);
538 dest_bv.makeDocumentClass();
539 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
543 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
545 LYXERR(Debug::DEBUG, "showEvent()" << endl);
546 BufferView * bv = view_.documentBufferView();
548 copy_params(*bv, find_work_area_->bufferView());
549 copy_params(*bv, replace_work_area_->bufferView());
552 find_work_area_->installEventFilter(this);
553 replace_work_area_->installEventFilter(this);
555 view_.setCurrentWorkArea(find_work_area_);
556 LYXERR(Debug::FIND, "Selecting entire find buffer");
557 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
558 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
562 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
564 replace_work_area_->removeEventFilter(this);
565 find_work_area_->removeEventFilter(this);
566 this->QWidget::hideEvent(ev);
570 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
576 void FindAndReplace::updateView()
578 widget_->updateGUI();
582 FindAndReplace::FindAndReplace(GuiView & parent,
583 Qt::DockWidgetArea area, Qt::WindowFlags flags)
584 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
587 widget_ = new FindAndReplaceWidget(parent);
589 setFocusProxy(widget_);
591 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
592 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
596 FindAndReplace::~FindAndReplace()
603 bool FindAndReplace::initialiseParams(std::string const & params)
605 return widget_->initialiseParams(params);
609 void FindAndReplaceWidget::updateGUI()
611 bool replace_enabled = view_.documentBufferView()
612 && !view_.documentBufferView()->buffer().isReadonly();
613 replace_work_area_->setEnabled(replace_enabled);
614 replacePB->setEnabled(replace_enabled);
615 replaceallPB->setEnabled(replace_enabled);
619 Dialog * createGuiSearchAdv(GuiView & lv)
621 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
623 // On Mac show and floating
624 gui->setFloating(true);
630 } // namespace frontend
634 #include "moc_FindAndReplace.cpp"