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();
70 old_buffer_ = view_.documentBufferView() ?
71 &(view_.documentBufferView()->buffer()) : 0;
74 cbVerticalLayout->setAlignment(Qt::AlignTop);
75 pbVerticalLayout->setAlignment(Qt::AlignTop);
79 void FindAndReplaceWidget::dockLocationChanged(Qt::DockWidgetArea area)
81 if (area == Qt::RightDockWidgetArea || area == Qt::LeftDockWidgetArea) {
82 dynamicLayoutBasic_->setDirection(QBoxLayout::TopToBottom);
83 dynamicLayoutAdvanced_->setDirection(QBoxLayout::TopToBottom);
85 dynamicLayoutBasic_->setDirection(QBoxLayout::LeftToRight);
86 dynamicLayoutAdvanced_->setDirection(QBoxLayout::LeftToRight);
91 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
93 if (event->type() != QEvent::KeyPress
94 || (obj != find_work_area_ && obj != replace_work_area_))
95 return QWidget::eventFilter(obj, event);
97 QKeyEvent * e = static_cast<QKeyEvent *> (event);
100 if (e->modifiers() == Qt::NoModifier) {
107 case Qt::Key_Return: {
108 // with shift we (temporarily) change search/replace direction
109 bool const searchback = searchbackCB->isChecked();
110 if (e->modifiers() == Qt::ShiftModifier && !searchback)
111 searchbackCB->setChecked(!searchback);
113 if (obj == find_work_area_)
114 on_findNextPB_clicked();
116 on_replacePB_clicked();
117 // back to how it was
118 searchbackCB->setChecked(searchback);
123 if (e->modifiers() == Qt::NoModifier) {
124 if (obj == find_work_area_){
125 LYXERR(Debug::FIND, "Focusing replace WA");
126 replace_work_area_->setFocus();
127 LYXERR(Debug::FIND, "Selecting entire replace buffer");
128 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
129 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
135 case Qt::Key_Backtab:
136 if (obj == replace_work_area_) {
137 LYXERR(Debug::FIND, "Focusing find WA");
138 find_work_area_->setFocus();
139 LYXERR(Debug::FIND, "Selecting entire find buffer");
140 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
141 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
149 // standard event processing
150 return QWidget::eventFilter(obj, event);
154 static vector<string> const & allManualsFiles()
156 static const char * files[] = {
157 "Intro", "UserGuide", "Tutorial", "Additional",
158 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
159 "LFUNs", "LaTeXConfig"
162 static vector<string> v;
165 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
166 fname = i18nLibFileSearch("doc", files[i], "lyx");
167 v.push_back(fname.absFileName());
175 /** Switch buf to point to next document buffer.
177 ** Return true if restarted from master-document buffer.
179 static bool nextDocumentBuffer(Buffer * & buf)
181 ListOfBuffers const children = buf->allRelatives();
182 LYXERR(Debug::FIND, "children.size()=" << children.size());
183 ListOfBuffers::const_iterator it =
184 find(children.begin(), children.end(), buf);
185 LASSERT(it != children.end(), return false);
187 if (it == children.end()) {
188 buf = *children.begin();
196 /** Switch p_buf to point to previous document buffer.
198 ** Return true if restarted from last child buffer.
200 static bool prevDocumentBuffer(Buffer * & buf)
202 ListOfBuffers const children = buf->allRelatives();
203 LYXERR(Debug::FIND, "children.size()=" << children.size());
204 ListOfBuffers::const_iterator it =
205 find(children.begin(), children.end(), buf);
206 LASSERT(it != children.end(), return false)
207 if (it == children.begin()) {
219 /** Switch buf to point to next or previous buffer in search scope.
221 ** Return true if restarted from scratch.
223 static bool nextPrevBuffer(Buffer * & buf,
224 FindAndReplaceOptions const & opt)
226 bool restarted = false;
228 case FindAndReplaceOptions::S_BUFFER:
231 case FindAndReplaceOptions::S_DOCUMENT:
233 restarted = nextDocumentBuffer(buf);
235 restarted = prevDocumentBuffer(buf);
237 case FindAndReplaceOptions::S_OPEN_BUFFERS:
239 buf = theBufferList().next(buf);
240 restarted = (buf == *theBufferList().begin());
242 buf = theBufferList().previous(buf);
243 restarted = (buf == *(theBufferList().end() - 1));
246 case FindAndReplaceOptions::S_ALL_MANUALS:
247 vector<string> const & manuals = allManualsFiles();
248 vector<string>::const_iterator it =
249 find(manuals.begin(), manuals.end(), buf->absFileName());
250 if (it == manuals.end())
251 it = manuals.begin();
252 else if (opt.forward) {
254 if (it == manuals.end()) {
255 it = manuals.begin();
259 if (it == manuals.begin()) {
265 FileName const & fname = FileName(*it);
266 if (!theBufferList().exists(fname)) {
267 guiApp->currentView()->setBusy(false);
268 guiApp->currentView()->loadDocument(fname, false);
269 guiApp->currentView()->setBusy(true);
271 buf = theBufferList().getBuffer(fname);
278 /** Find the finest question message to post to the user */
279 docstring getQuestionString(FindAndReplaceOptions const & opt)
283 case FindAndReplaceOptions::S_BUFFER:
286 case FindAndReplaceOptions::S_DOCUMENT:
287 scope = _("Master document");
289 case FindAndReplaceOptions::S_OPEN_BUFFERS:
290 scope = _("Open files");
292 case FindAndReplaceOptions::S_ALL_MANUALS:
293 scope = _("Manuals");
296 docstring message = opt.forward ?
297 bformat(_("%1$s: the end was reached while searching forward.\n"
298 "Continue searching from the beginning?"),
300 bformat(_("%1$s: the beginning was reached while searching backward.\n"
301 "Continue searching from the end?"),
308 /// Return true if a match was found
309 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
311 BufferView * bv = view_.documentBufferView();
314 Buffer * buf = &bv->buffer();
315 Buffer * buf_orig = &bv->buffer();
316 DocIterator cur_orig(bv->cursor());
317 int wrap_answer = -1;
318 opt.replace_all = replace_all;
321 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
323 view_.message(_("Advanced search in progress (press ESC to cancel) . . ."));
324 theApp()->startLongOperation();
326 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
327 vector<string> const & v = allManualsFiles();
328 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
329 FileName const & fname = FileName(*v.begin());
330 if (!theBufferList().exists(fname)) {
331 guiApp->currentView()->setBusy(false);
332 theApp()->stopLongOperation();
333 guiApp->currentView()->loadDocument(fname, false);
334 theApp()->startLongOperation();
335 guiApp->currentView()->setBusy(true);
337 buf = theBufferList().getBuffer(fname);
339 view_.setBusy(false);
343 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
344 buf->absFileName()));
345 bv = view_.documentBufferView();
346 bv->cursor().clear();
347 bv->cursor().push_back(CursorSlice(buf->inset()));
351 UndoGroupHelper helper(buf);
354 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
356 LYXERR(Debug::FIND, "dispatched");
357 if (bv->cursor().result().dispatched()) {
358 // New match found and selected (old selection replaced if needed)
361 view_.setBusy(false);
362 theApp()->stopLongOperation();
364 } else if (replace_all)
365 bv->clearSelection();
367 if (theApp()->longOperationCancelled()) {
368 // Search aborted by user
369 view_.message(_("Advanced search cancelled by user"));
370 view_.setBusy(false);
371 theApp()->stopLongOperation();
375 // No match found in current buffer (however old selection might have been replaced)
376 // select next buffer in scope, if any
377 bool const prompt = nextPrevBuffer(buf, opt);
381 if (wrap_answer != -1)
383 docstring q = getQuestionString(opt);
384 view_.setBusy(false);
385 theApp()->stopLongOperation();
386 wrap_answer = frontend::Alert::prompt(
387 _("Wrap search?"), q,
388 0, 1, _("&Yes"), _("&No"));
389 theApp()->startLongOperation();
391 if (wrap_answer == 1)
394 if (buf != &view_.documentBufferView()->buffer())
395 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
396 buf->absFileName()));
398 helper.resetBuffer(buf);
400 bv = view_.documentBufferView();
402 bv->cursor().clear();
403 bv->cursor().push_back(CursorSlice(buf->inset()));
405 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
406 bv->cursor().setCursor(doc_iterator_end(buf));
407 bv->cursor().backwardPos();
408 LYXERR(Debug::FIND, "findBackAdv5: cur: "
411 bv->clearSelection();
412 } while (wrap_answer != 1);
414 if (buf_orig != &view_.documentBufferView()->buffer())
415 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
416 buf_orig->absFileName()));
417 bv = view_.documentBufferView();
418 // This may happen after a replace occurred
419 if (cur_orig.pos() > cur_orig.lastpos())
420 cur_orig.pos() = cur_orig.lastpos();
421 bv->cursor().setCursor(cur_orig);
422 view_.setBusy(false);
423 theApp()->stopLongOperation();
428 /// Return true if a match was found
429 bool FindAndReplaceWidget::findAndReplace(
430 bool casesensitive, bool matchword, bool backwards,
431 bool expandmacros, bool ignoreformat, bool replace,
432 bool keep_case, bool replace_all)
434 Buffer & find_buf = find_work_area_->bufferView().buffer();
435 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
437 if (find_buf.text().empty()) {
438 view_.message(_("Nothing to search"));
442 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
443 docstring const & repl_buf_name = replace ?
444 repl_buf.fileName().absoluteFilePath() : docstring();
446 FindAndReplaceOptions::SearchScope scope =
447 FindAndReplaceOptions::S_BUFFER;
448 if (CurrentDocument->isChecked())
449 scope = FindAndReplaceOptions::S_BUFFER;
450 else if (MasterDocument->isChecked())
451 scope = FindAndReplaceOptions::S_DOCUMENT;
452 else if (OpenDocuments->isChecked())
453 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
454 else if (AllManualsRB->isChecked())
455 scope = FindAndReplaceOptions::S_ALL_MANUALS;
459 FindAndReplaceOptions::SearchRestriction restr =
460 OnlyMaths->isChecked()
461 ? FindAndReplaceOptions::R_ONLY_MATHS
462 : FindAndReplaceOptions::R_EVERYTHING;
464 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
465 << "find_buf_name=" << find_buf_name
466 << ", casesensitiv=" << casesensitive
467 << ", matchword=" << matchword
468 << ", backwards=" << backwards
469 << ", expandmacros=" << expandmacros
470 << ", ignoreformat=" << ignoreformat
471 << ", repl_buf_name" << repl_buf_name
472 << ", keep_case=" << keep_case
473 << ", scope=" << scope
474 << ", restr=" << restr);
476 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
477 !backwards, expandmacros, ignoreformat,
478 repl_buf_name, keep_case, scope, restr);
479 return findAndReplaceScope(opt, replace_all);
483 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
485 if (! view_.currentMainWorkArea()) {
486 view_.message(_("No open document(s) in which to search"));
489 // Finalize macros that are being typed, both in main document and in search or replacement WAs
490 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
491 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
492 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
493 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
495 // FIXME: create a Dialog::returnFocus()
496 // or something instead of this:
497 view_.setCurrentWorkArea(view_.currentMainWorkArea());
498 return findAndReplace(caseCB->isChecked(),
499 wordsCB->isChecked(),
501 expandMacrosCB->isChecked(),
502 ignoreFormatCB->isChecked(),
504 keepCaseCB->isChecked(),
509 void FindAndReplaceWidget::hideDialog()
511 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
515 void FindAndReplaceWidget::on_findNextPB_clicked()
517 findAndReplace(searchbackCB->isChecked(), false);
518 find_work_area_->setFocus();
522 void FindAndReplaceWidget::on_replacePB_clicked()
524 findAndReplace(searchbackCB->isChecked(), true);
525 replace_work_area_->setFocus();
529 void FindAndReplaceWidget::on_replaceallPB_clicked()
531 findAndReplace(searchbackCB->isChecked(), true, true);
532 replace_work_area_->setFocus();
536 // Copy selected elements from bv's BufferParams to the dest_bv's
537 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
538 Buffer const & doc_buf = bv.buffer();
539 BufferParams const & doc_bp = doc_buf.params();
540 Buffer & dest_buf = dest_bv.buffer();
541 dest_buf.params().copyForAdvFR(doc_bp);
542 dest_bv.makeDocumentClass();
543 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
547 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
549 LYXERR(Debug::DEBUG, "showEvent()" << endl);
550 BufferView * bv = view_.documentBufferView();
552 copy_params(*bv, find_work_area_->bufferView());
553 copy_params(*bv, replace_work_area_->bufferView());
556 find_work_area_->installEventFilter(this);
557 replace_work_area_->installEventFilter(this);
559 view_.setCurrentWorkArea(find_work_area_);
560 LYXERR(Debug::FIND, "Selecting entire find buffer");
561 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
562 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
566 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
568 replace_work_area_->removeEventFilter(this);
569 find_work_area_->removeEventFilter(this);
570 this->QWidget::hideEvent(ev);
574 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
580 void FindAndReplace::updateView()
582 widget_->updateGUI();
586 FindAndReplace::FindAndReplace(GuiView & parent,
587 Qt::DockWidgetArea area, Qt::WindowFlags flags)
588 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
591 widget_ = new FindAndReplaceWidget(parent);
593 setFocusProxy(widget_);
595 connect(this, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),
596 widget_, SLOT(dockLocationChanged(Qt::DockWidgetArea)));
600 FindAndReplace::~FindAndReplace()
607 bool FindAndReplace::initialiseParams(std::string const & params)
609 return widget_->initialiseParams(params);
613 void FindAndReplaceWidget::updateGUI()
615 BufferView * bv = view_.documentBufferView();
617 if (old_buffer_ != &bv->buffer()) {
618 copy_params(*bv, find_work_area_->bufferView());
619 copy_params(*bv, replace_work_area_->bufferView());
620 old_buffer_ = &bv->buffer();
625 bool const replace_enabled = bv && !bv->buffer().isReadonly();
626 replace_work_area_->setEnabled(replace_enabled);
627 replacePB->setEnabled(replace_enabled);
628 replaceallPB->setEnabled(replace_enabled);
632 Dialog * createGuiSearchAdv(GuiView & lv)
634 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
636 // On Mac show and floating
637 gui->setFloating(true);
643 } // namespace frontend
647 #include "moc_FindAndReplace.cpp"