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()));
344 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
346 LYXERR(Debug::FIND, "dispatched");
347 if (bv->cursor().result().dispatched()) {
348 // New match found and selected (old selection replaced if needed)
351 view_.setBusy(false);
352 theApp()->stopLongOperation();
354 } else if (replace_all)
355 bv->clearSelection();
357 if (theApp()->longOperationCancelled()) {
358 // Search aborted by user
359 view_.message(_("Advanced search cancelled by user"));
360 view_.setBusy(false);
361 theApp()->stopLongOperation();
365 // No match found in current buffer (however old selection might have been replaced)
366 // select next buffer in scope, if any
367 bool const prompt = nextPrevBuffer(buf, opt);
371 if (wrap_answer != -1)
373 docstring q = getQuestionString(opt);
374 view_.setBusy(false);
375 theApp()->stopLongOperation();
376 wrap_answer = frontend::Alert::prompt(
377 _("Wrap search?"), q,
378 0, 1, _("&Yes"), _("&No"));
379 theApp()->startLongOperation();
381 if (wrap_answer == 1)
384 if (buf != &view_.documentBufferView()->buffer())
385 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
386 buf->absFileName()));
387 bv = view_.documentBufferView();
389 bv->cursor().clear();
390 bv->cursor().push_back(CursorSlice(buf->inset()));
392 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
393 bv->cursor().setCursor(doc_iterator_end(buf));
394 bv->cursor().backwardPos();
395 LYXERR(Debug::FIND, "findBackAdv5: cur: "
398 bv->clearSelection();
399 } while (wrap_answer != 1);
400 if (buf_orig != &view_.documentBufferView()->buffer())
401 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
402 buf_orig->absFileName()));
403 bv = view_.documentBufferView();
404 // This may happen after a replace occurred
405 if (cur_orig.pos() > cur_orig.lastpos())
406 cur_orig.pos() = cur_orig.lastpos();
407 bv->cursor().setCursor(cur_orig);
408 view_.setBusy(false);
409 theApp()->stopLongOperation();
414 /// Return true if a match was found
415 bool FindAndReplaceWidget::findAndReplace(
416 bool casesensitive, bool matchword, bool backwards,
417 bool expandmacros, bool ignoreformat, bool replace,
418 bool keep_case, bool replace_all)
420 Buffer & find_buf = find_work_area_->bufferView().buffer();
421 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
423 if (find_buf.text().empty()) {
424 view_.message(_("Nothing to search"));
428 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
429 docstring const & repl_buf_name = replace ?
430 repl_buf.fileName().absoluteFilePath() : docstring();
432 FindAndReplaceOptions::SearchScope scope =
433 FindAndReplaceOptions::S_BUFFER;
434 if (CurrentDocument->isChecked())
435 scope = FindAndReplaceOptions::S_BUFFER;
436 else if (MasterDocument->isChecked())
437 scope = FindAndReplaceOptions::S_DOCUMENT;
438 else if (OpenDocuments->isChecked())
439 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
440 else if (AllManualsRB->isChecked())
441 scope = FindAndReplaceOptions::S_ALL_MANUALS;
445 FindAndReplaceOptions::SearchRestriction restr =
446 OnlyMaths->isChecked()
447 ? FindAndReplaceOptions::R_ONLY_MATHS
448 : FindAndReplaceOptions::R_EVERYTHING;
450 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
451 << "find_buf_name=" << find_buf_name
452 << ", casesensitiv=" << casesensitive
453 << ", matchword=" << matchword
454 << ", backwards=" << backwards
455 << ", expandmacros=" << expandmacros
456 << ", ignoreformat=" << ignoreformat
457 << ", repl_buf_name" << repl_buf_name
458 << ", keep_case=" << keep_case
459 << ", scope=" << scope
460 << ", restr=" << restr);
462 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
463 !backwards, expandmacros, ignoreformat,
464 repl_buf_name, keep_case, scope, restr);
465 return findAndReplaceScope(opt, replace_all);
469 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
471 if (! view_.currentMainWorkArea()) {
472 view_.message(_("No open document(s) in which to search"));
475 // Finalize macros that are being typed, both in main document and in search or replacement WAs
476 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
477 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
478 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
479 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
481 // FIXME: create a Dialog::returnFocus()
482 // or something instead of this:
483 view_.setCurrentWorkArea(view_.currentMainWorkArea());
484 return findAndReplace(caseCB->isChecked(),
485 wordsCB->isChecked(),
487 expandMacrosCB->isChecked(),
488 ignoreFormatCB->isChecked(),
490 keepCaseCB->isChecked(),
495 void FindAndReplaceWidget::hideDialog()
497 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
501 void FindAndReplaceWidget::on_findNextPB_clicked()
503 findAndReplace(searchbackCB->isChecked(), false);
504 find_work_area_->setFocus();
508 void FindAndReplaceWidget::on_replacePB_clicked()
510 findAndReplace(searchbackCB->isChecked(), true);
511 replace_work_area_->setFocus();
515 void FindAndReplaceWidget::on_replaceallPB_clicked()
517 findAndReplace(searchbackCB->isChecked(), true, true);
518 replace_work_area_->setFocus();
522 /** Copy selected elements from bv's BufferParams to the dest_bv's one
523 ** We don't want to copy'em all, e.g., not the default master **/
524 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
525 Buffer const & doc_buf = bv.buffer();
526 BufferParams const & doc_bp = doc_buf.params();
527 string const & lang = doc_bp.language->lang();
528 string const & doc_class = doc_bp.documentClass().name();
529 Buffer & dest_buf = dest_bv.buffer();
530 dest_buf.params().setLanguage(lang);
531 dest_buf.params().setBaseClass(doc_class);
532 dest_bv.makeDocumentClass();
533 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
537 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
539 LYXERR(Debug::DEBUG, "showEvent()" << endl);
540 BufferView * bv = view_.documentBufferView();
542 copy_params(*bv, find_work_area_->bufferView());
543 copy_params(*bv, replace_work_area_->bufferView());
546 find_work_area_->installEventFilter(this);
547 replace_work_area_->installEventFilter(this);
549 view_.setCurrentWorkArea(find_work_area_);
550 LYXERR(Debug::FIND, "Selecting entire find buffer");
551 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
552 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
556 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
558 replace_work_area_->removeEventFilter(this);
559 find_work_area_->removeEventFilter(this);
560 this->QWidget::hideEvent(ev);
564 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
570 void FindAndReplace::updateView()
572 widget_->updateGUI();
576 FindAndReplace::FindAndReplace(GuiView & parent,
577 Qt::DockWidgetArea area, Qt::WindowFlags flags)
578 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
581 widget_ = new FindAndReplaceWidget(parent);
583 setFocusProxy(widget_);
585 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
586 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
590 FindAndReplace::~FindAndReplace()
597 bool FindAndReplace::initialiseParams(std::string const & params)
599 return widget_->initialiseParams(params);
603 void FindAndReplaceWidget::updateGUI()
605 bool replace_enabled = view_.documentBufferView()
606 && !view_.documentBufferView()->buffer().isReadonly();
607 replace_work_area_->setEnabled(replace_enabled);
608 replacePB->setEnabled(replace_enabled);
609 replaceallPB->setEnabled(replace_enabled);
613 Dialog * createGuiSearchAdv(GuiView & lv)
615 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
617 // On Mac show and floating
618 gui->setFloating(true);
624 } // namespace frontend
628 #include "moc_FindAndReplace.cpp"