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();
73 void FindAndReplaceWidget::dockLocationChanged(Qt::DockWidgetArea area)
75 if (area == Qt::RightDockWidgetArea || area == Qt::LeftDockWidgetArea) {
76 dynamicLayoutBasic_->setDirection(QBoxLayout::TopToBottom);
77 dynamicLayoutAdvanced_->setDirection(QBoxLayout::TopToBottom);
79 dynamicLayoutBasic_->setDirection(QBoxLayout::LeftToRight);
80 dynamicLayoutAdvanced_->setDirection(QBoxLayout::LeftToRight);
85 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
87 if (event->type() != QEvent::KeyPress
88 || (obj != find_work_area_ && obj != replace_work_area_))
89 return QWidget::eventFilter(obj, event);
91 QKeyEvent * e = static_cast<QKeyEvent *> (event);
94 if (e->modifiers() == Qt::NoModifier) {
101 case Qt::Key_Return: {
102 // with shift we (temporarily) change search/replace direction
103 bool const searchback = searchbackCB->isChecked();
104 if (e->modifiers() == Qt::ShiftModifier && !searchback)
105 searchbackCB->setChecked(!searchback);
107 if (obj == find_work_area_)
108 on_findNextPB_clicked();
110 on_replacePB_clicked();
111 // back to how it was
112 searchbackCB->setChecked(searchback);
117 if (e->modifiers() == Qt::NoModifier) {
118 if (obj == find_work_area_){
119 LYXERR(Debug::FIND, "Focusing replace WA");
120 replace_work_area_->setFocus();
121 LYXERR(Debug::FIND, "Selecting entire replace buffer");
122 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
123 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
129 case Qt::Key_Backtab:
130 if (obj == replace_work_area_) {
131 LYXERR(Debug::FIND, "Focusing find WA");
132 find_work_area_->setFocus();
133 LYXERR(Debug::FIND, "Selecting entire find buffer");
134 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
135 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
143 // standard event processing
144 return QWidget::eventFilter(obj, event);
148 static vector<string> const & allManualsFiles()
150 static const char * files[] = {
151 "Intro", "UserGuide", "Tutorial", "Additional",
152 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
153 "LFUNs", "LaTeXConfig"
156 static vector<string> v;
159 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
160 fname = i18nLibFileSearch("doc", files[i], "lyx");
161 v.push_back(fname.absFileName());
169 /** Switch buf to point to next document buffer.
171 ** Return true if restarted from master-document buffer.
173 static bool nextDocumentBuffer(Buffer * & buf)
175 ListOfBuffers const children = buf->allRelatives();
176 LYXERR(Debug::FIND, "children.size()=" << children.size());
177 ListOfBuffers::const_iterator it =
178 find(children.begin(), children.end(), buf);
179 LASSERT(it != children.end(), return false);
181 if (it == children.end()) {
182 buf = *children.begin();
190 /** Switch p_buf to point to previous document buffer.
192 ** Return true if restarted from last child buffer.
194 static bool prevDocumentBuffer(Buffer * & buf)
196 ListOfBuffers const children = buf->allRelatives();
197 LYXERR(Debug::FIND, "children.size()=" << children.size());
198 ListOfBuffers::const_iterator it =
199 find(children.begin(), children.end(), buf);
200 LASSERT(it != children.end(), return false)
201 if (it == children.begin()) {
213 /** Switch buf to point to next or previous buffer in search scope.
215 ** Return true if restarted from scratch.
217 static bool nextPrevBuffer(Buffer * & buf,
218 FindAndReplaceOptions const & opt)
220 bool restarted = false;
222 case FindAndReplaceOptions::S_BUFFER:
225 case FindAndReplaceOptions::S_DOCUMENT:
227 restarted = nextDocumentBuffer(buf);
229 restarted = prevDocumentBuffer(buf);
231 case FindAndReplaceOptions::S_OPEN_BUFFERS:
233 buf = theBufferList().next(buf);
234 restarted = (buf == *theBufferList().begin());
236 buf = theBufferList().previous(buf);
237 restarted = (buf == *(theBufferList().end() - 1));
240 case FindAndReplaceOptions::S_ALL_MANUALS:
241 vector<string> const & manuals = allManualsFiles();
242 vector<string>::const_iterator it =
243 find(manuals.begin(), manuals.end(), buf->absFileName());
244 if (it == manuals.end())
245 it = manuals.begin();
246 else if (opt.forward) {
248 if (it == manuals.end()) {
249 it = manuals.begin();
253 if (it == manuals.begin()) {
259 FileName const & fname = FileName(*it);
260 if (!theBufferList().exists(fname)) {
261 guiApp->currentView()->setBusy(false);
262 guiApp->currentView()->loadDocument(fname, false);
263 guiApp->currentView()->setBusy(true);
265 buf = theBufferList().getBuffer(fname);
272 /** Find the finest question message to post to the user */
273 docstring getQuestionString(FindAndReplaceOptions const & opt)
277 case FindAndReplaceOptions::S_BUFFER:
280 case FindAndReplaceOptions::S_DOCUMENT:
281 scope = _("Master document");
283 case FindAndReplaceOptions::S_OPEN_BUFFERS:
284 scope = _("Open files");
286 case FindAndReplaceOptions::S_ALL_MANUALS:
287 scope = _("Manuals");
290 docstring message = opt.forward ?
291 bformat(_("%1$s: the end was reached while searching forward.\n"
292 "Continue searching from the beginning?"),
294 bformat(_("%1$s: the beginning was reached while searching backward.\n"
295 "Continue searching from the end?"),
302 /// Return true if a match was found
303 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
305 BufferView * bv = view_.documentBufferView();
308 Buffer * buf = &bv->buffer();
309 Buffer * buf_orig = &bv->buffer();
310 DocIterator cur_orig(bv->cursor());
311 int wrap_answer = -1;
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::FIND, "Dispatching LFUN_WORD_FINDADV");
349 LYXERR(Debug::FIND, "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::FIND, "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 ignoreformat, 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::FIND, "FindAndReplaceOptions: "
458 << "find_buf_name=" << find_buf_name
459 << ", casesensitiv=" << casesensitive
460 << ", matchword=" << matchword
461 << ", backwards=" << backwards
462 << ", expandmacros=" << expandmacros
463 << ", ignoreformat=" << ignoreformat
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, ignoreformat,
471 repl_buf_name, keep_case, scope, restr);
472 return findAndReplaceScope(opt, replace_all);
476 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
478 if (! view_.currentMainWorkArea()) {
479 view_.message(_("No open document(s) in which to search"));
482 // Finalize macros that are being typed, both in main document and in search or replacement WAs
483 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
484 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
485 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
486 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
488 // FIXME: create a Dialog::returnFocus()
489 // or something instead of this:
490 view_.setCurrentWorkArea(view_.currentMainWorkArea());
491 return findAndReplace(caseCB->isChecked(),
492 wordsCB->isChecked(),
494 expandMacrosCB->isChecked(),
495 ignoreFormatCB->isChecked(),
497 keepCaseCB->isChecked(),
502 void FindAndReplaceWidget::hideDialog()
504 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
508 void FindAndReplaceWidget::on_findNextPB_clicked()
510 findAndReplace(searchbackCB->isChecked(), false);
511 find_work_area_->setFocus();
515 void FindAndReplaceWidget::on_replacePB_clicked()
517 findAndReplace(searchbackCB->isChecked(), true);
518 replace_work_area_->setFocus();
522 void FindAndReplaceWidget::on_replaceallPB_clicked()
524 findAndReplace(searchbackCB->isChecked(), true, true);
525 replace_work_area_->setFocus();
529 // Copy selected elements from bv's BufferParams to the dest_bv's
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 Buffer & dest_buf = dest_bv.buffer();
534 dest_buf.params().copyForAdvFR(doc_bp);
535 dest_bv.makeDocumentClass();
536 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
540 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
542 LYXERR(Debug::DEBUG, "showEvent()" << endl);
543 BufferView * bv = view_.documentBufferView();
545 copy_params(*bv, find_work_area_->bufferView());
546 copy_params(*bv, replace_work_area_->bufferView());
549 find_work_area_->installEventFilter(this);
550 replace_work_area_->installEventFilter(this);
552 view_.setCurrentWorkArea(find_work_area_);
553 LYXERR(Debug::FIND, "Selecting entire find buffer");
554 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
555 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
559 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
561 replace_work_area_->removeEventFilter(this);
562 find_work_area_->removeEventFilter(this);
563 this->QWidget::hideEvent(ev);
567 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
573 void FindAndReplace::updateView()
575 widget_->updateGUI();
579 FindAndReplace::FindAndReplace(GuiView & parent,
580 Qt::DockWidgetArea area, Qt::WindowFlags flags)
581 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
584 widget_ = new FindAndReplaceWidget(parent);
586 setFocusProxy(widget_);
588 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
589 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
593 FindAndReplace::~FindAndReplace()
600 bool FindAndReplace::initialiseParams(std::string const & params)
602 return widget_->initialiseParams(params);
606 void FindAndReplaceWidget::updateGUI()
608 bool replace_enabled = view_.documentBufferView()
609 && !view_.documentBufferView()->buffer().isReadonly();
610 replace_work_area_->setEnabled(replace_enabled);
611 replacePB->setEnabled(replace_enabled);
612 replaceallPB->setEnabled(replace_enabled);
616 Dialog * createGuiSearchAdv(GuiView & lv)
618 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
620 // On Mac show and floating
621 gui->setFloating(true);
627 } // namespace frontend
631 #include "moc_FindAndReplace.cpp"