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"
22 #include "BufferParams.h"
23 #include "BufferList.h"
24 #include "TextClass.h"
26 #include "FuncRequest.h"
29 #include "frontends/alert.h"
31 #include "support/debug.h"
32 #include "support/filetools.h"
33 #include "support/FileName.h"
34 #include "support/gettext.h"
35 #include "support/lassert.h"
36 #include "support/lstrings.h"
38 #include <QCloseEvent>
43 using namespace lyx::support;
49 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
50 : QTabWidget(&view), view_(view)
53 find_work_area_->setGuiView(view_);
54 find_work_area_->init();
55 find_work_area_->setFrameStyle(QFrame::StyledPanel);
57 setFocusProxy(find_work_area_);
58 replace_work_area_->setGuiView(view_);
59 replace_work_area_->init();
60 replace_work_area_->setFrameStyle(QFrame::StyledPanel);
62 // We don't want two cursors blinking.
63 find_work_area_->stopBlinkingCursor();
64 replace_work_area_->stopBlinkingCursor();
68 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
70 if (event->type() != QEvent::KeyPress
71 || (obj != find_work_area_ && obj != replace_work_area_))
72 return QWidget::eventFilter(obj, event);
74 QKeyEvent * e = static_cast<QKeyEvent *> (event);
77 if (e->modifiers() == Qt::NoModifier) {
84 case Qt::Key_Return: {
85 // with shift we (temporarily) change search/replace direction
86 bool const searchback = searchbackCB->isChecked();
87 if (e->modifiers() == Qt::ShiftModifier && !searchback)
88 searchbackCB->setChecked(!searchback);
90 if (obj == find_work_area_)
91 on_findNextPB_clicked();
93 on_replacePB_clicked();
95 searchbackCB->setChecked(searchback);
100 if (e->modifiers() == Qt::NoModifier) {
101 if (obj == find_work_area_){
102 LYXERR(Debug::FIND, "Focusing replace WA");
103 replace_work_area_->setFocus();
104 LYXERR(Debug::FIND, "Selecting entire replace buffer");
105 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
106 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
112 case Qt::Key_Backtab:
113 if (obj == replace_work_area_) {
114 LYXERR(Debug::FIND, "Focusing find WA");
115 find_work_area_->setFocus();
116 LYXERR(Debug::FIND, "Selecting entire find buffer");
117 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
118 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
126 // standard event processing
127 return QWidget::eventFilter(obj, event);
131 static vector<string> const & allManualsFiles()
133 static vector<string> v;
134 static const char * files[] = {
135 "Intro", "UserGuide", "Tutorial", "Additional",
136 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
137 "LFUNs", "LaTeXConfig"
141 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
142 fname = i18nLibFileSearch("doc", files[i], "lyx");
143 v.push_back(fname.absFileName());
150 /** Switch p_buf to point to next document buffer.
152 ** Return true if restarted from master-document buffer.
154 static bool nextDocumentBuffer(Buffer * & buf)
156 ListOfBuffers const children = buf->allRelatives();
157 LYXERR(Debug::FIND, "children.size()=" << children.size());
158 ListOfBuffers::const_iterator it =
159 find(children.begin(), children.end(), buf);
160 LASSERT(it != children.end(), /**/);
162 if (it == children.end()) {
163 buf = *children.begin();
171 /** Switch p_buf to point to previous document buffer.
173 ** Return true if restarted from last child buffer.
175 static bool prevDocumentBuffer(Buffer * & buf)
177 ListOfBuffers const children = buf->allRelatives();
178 LYXERR(Debug::FIND, "children.size()=" << children.size());
179 ListOfBuffers::const_iterator it =
180 find(children.begin(), children.end(), buf);
181 LASSERT(it != children.end(), /**/)
182 if (it == children.begin()) {
194 /** Switch buf to point to next or previous buffer in search scope.
196 ** Return true if restarted from scratch.
198 static bool nextPrevBuffer(Buffer * & buf,
199 FindAndReplaceOptions const & opt)
201 bool restarted = false;
203 case FindAndReplaceOptions::S_BUFFER:
206 case FindAndReplaceOptions::S_DOCUMENT:
208 restarted = nextDocumentBuffer(buf);
210 restarted = prevDocumentBuffer(buf);
212 case FindAndReplaceOptions::S_OPEN_BUFFERS:
214 buf = theBufferList().next(buf);
215 restarted = (buf == *theBufferList().begin());
217 buf = theBufferList().previous(buf);
218 restarted = (buf == *(theBufferList().end() - 1));
221 case FindAndReplaceOptions::S_ALL_MANUALS:
222 vector<string> const & manuals = allManualsFiles();
223 vector<string>::const_iterator it =
224 find(manuals.begin(), manuals.end(), buf->absFileName());
225 if (it == manuals.end())
226 it = manuals.begin();
227 else if (opt.forward) {
229 if (it == manuals.end()) {
230 it = manuals.begin();
234 if (it == manuals.begin()) {
240 FileName const & fname = FileName(*it);
241 if (!theBufferList().exists(fname)) {
242 guiApp->currentView()->setBusy(false);
243 guiApp->currentView()->loadDocument(fname, false);
244 guiApp->currentView()->setBusy(true);
246 buf = theBufferList().getBuffer(fname);
253 /** Find the finest question message to post to the user */
254 docstring getQuestionString(FindAndReplaceOptions const & opt)
258 case FindAndReplaceOptions::S_BUFFER:
261 case FindAndReplaceOptions::S_DOCUMENT:
262 scope = _("Master document");
264 case FindAndReplaceOptions::S_OPEN_BUFFERS:
265 scope = _("Open files");
267 case FindAndReplaceOptions::S_ALL_MANUALS:
268 scope = _("Manuals");
271 docstring message = opt.forward ?
272 bformat(_("%1$s: the end was reached while searching forward.\n"
273 "Continue searching from the beginning?"),
275 bformat(_("%1$s: the beginning was reached while searching backward.\n"
276 "Continue searching from the end?"),
283 /// Return true if a match was found
284 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
286 BufferView * bv = view_.documentBufferView();
289 Buffer * buf = &bv->buffer();
290 Buffer * buf_orig = &bv->buffer();
291 DocIterator cur_orig(bv->cursor());
292 int wrap_answer = -1;
295 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
298 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
299 vector<string> const & v = allManualsFiles();
300 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
301 FileName const & fname = FileName(*v.begin());
302 if (!theBufferList().exists(fname)) {
303 guiApp->currentView()->setBusy(false);
304 guiApp->currentView()->loadDocument(fname, false);
305 guiApp->currentView()->setBusy(true);
307 buf = theBufferList().getBuffer(fname);
309 view_.setBusy(false);
313 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
314 buf->absFileName()));
315 bv = view_.documentBufferView();
316 bv->cursor().clear();
317 bv->cursor().push_back(CursorSlice(buf->inset()));
322 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
324 LYXERR(Debug::FIND, "dispatched");
325 if (bv->cursor().result().dispatched()) {
326 // New match found and selected (old selection replaced if needed)
329 view_.setBusy(false);
331 } else if (replace_all)
332 bv->clearSelection();
334 // No match found in current buffer (however old selection might have been replaced)
335 // select next buffer in scope, if any
336 bool const prompt = nextPrevBuffer(buf, opt);
340 if (wrap_answer != -1)
342 docstring q = getQuestionString(opt);
343 view_.setBusy(false);
344 wrap_answer = frontend::Alert::prompt(
345 _("Wrap search?"), q,
346 0, 1, _("&Yes"), _("&No"));
348 if (wrap_answer == 1)
351 if (buf != &view_.documentBufferView()->buffer())
352 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
353 buf->absFileName()));
354 bv = view_.documentBufferView();
356 bv->cursor().clear();
357 bv->cursor().push_back(CursorSlice(buf->inset()));
359 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
360 bv->cursor().setCursor(doc_iterator_end(buf));
361 bv->cursor().backwardPos();
362 LYXERR(Debug::FIND, "findBackAdv5: cur: "
365 bv->clearSelection();
366 } while (wrap_answer != 1);
367 if (buf_orig != &view_.documentBufferView()->buffer())
368 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
369 buf_orig->absFileName()));
370 bv = view_.documentBufferView();
371 // This may happen after a replace occurred
372 if (cur_orig.pos() > cur_orig.lastpos())
373 cur_orig.pos() = cur_orig.lastpos();
374 bv->cursor().setCursor(cur_orig);
375 view_.setBusy(false);
380 /// Return true if a match was found
381 bool FindAndReplaceWidget::findAndReplace(
382 bool casesensitive, bool matchword, bool backwards,
383 bool expandmacros, bool ignoreformat, bool replace,
384 bool keep_case, bool replace_all)
386 Buffer & find_buf = find_work_area_->bufferView().buffer();
387 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
389 if (find_buf.text().empty()) {
390 view_.message(_("Nothing to search"));
394 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
395 docstring const & repl_buf_name = replace ?
396 repl_buf.fileName().absoluteFilePath() : docstring();
398 FindAndReplaceOptions::SearchScope scope =
399 FindAndReplaceOptions::S_BUFFER;
400 if (CurrentDocument->isChecked())
401 scope = FindAndReplaceOptions::S_BUFFER;
402 else if (MasterDocument->isChecked())
403 scope = FindAndReplaceOptions::S_DOCUMENT;
404 else if (OpenDocuments->isChecked())
405 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
406 else if (AllManualsRB->isChecked())
407 scope = FindAndReplaceOptions::S_ALL_MANUALS;
409 LASSERT(false, /**/);
410 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
411 << "find_buf_name=" << find_buf_name
412 << ", casesensitiv=" << casesensitive
413 << ", matchword=" << matchword
414 << ", backwards=" << backwards
415 << ", expandmacros=" << expandmacros
416 << ", ignoreformat=" << ignoreformat
417 << ", repl_buf_name" << repl_buf_name
418 << ", keep_case=" << keep_case
419 << ", scope=" << scope);
420 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
421 !backwards, expandmacros, ignoreformat,
422 repl_buf_name, keep_case, scope);
423 return findAndReplaceScope(opt, replace_all);
427 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
429 if (! view_.currentMainWorkArea()) {
430 view_.message(_("No open document(s) in which to search"));
433 // Finalize macros that are being typed, both in main document and in search or replacement WAs
434 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
435 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
436 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
437 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
439 // FIXME: create a Dialog::returnFocus()
440 // or something instead of this:
441 view_.setCurrentWorkArea(view_.currentMainWorkArea());
442 return findAndReplace(caseCB->isChecked(),
443 wordsCB->isChecked(),
445 expandMacrosCB->isChecked(),
446 ignoreFormatCB->isChecked(),
448 keepCaseCB->isChecked(),
453 void FindAndReplaceWidget::hideDialog()
455 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
459 void FindAndReplaceWidget::on_findNextPB_clicked()
461 findAndReplace(searchbackCB->isChecked(), false);
462 find_work_area_->setFocus();
466 void FindAndReplaceWidget::on_replacePB_clicked()
468 findAndReplace(searchbackCB->isChecked(), true);
469 replace_work_area_->setFocus();
473 void FindAndReplaceWidget::on_replaceallPB_clicked()
475 findAndReplace(searchbackCB->isChecked(), true, true);
476 replace_work_area_->setFocus();
480 /** Copy selected elements from bv's BufferParams to the dest_bv's one
481 ** We don't want to copy'em all, e.g., not the default master **/
482 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
483 Buffer const & doc_buf = bv.buffer();
484 BufferParams const & doc_bp = doc_buf.params();
485 string const & lang = doc_bp.language->lang();
486 string const & doc_class = doc_bp.documentClass().name();
487 Buffer & dest_buf = dest_bv.buffer();
488 dest_buf.params().setLanguage(lang);
489 dest_buf.params().setBaseClass(doc_class);
490 dest_buf.params().makeDocumentClass();
491 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
495 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
497 LYXERR(Debug::DEBUG, "showEvent()" << endl);
498 BufferView * bv = view_.documentBufferView();
500 copy_params(*bv, find_work_area_->bufferView());
501 copy_params(*bv, replace_work_area_->bufferView());
504 find_work_area_->installEventFilter(this);
505 replace_work_area_->installEventFilter(this);
507 view_.setCurrentWorkArea(find_work_area_);
508 LYXERR(Debug::FIND, "Selecting entire find buffer");
509 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
510 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
514 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
516 replace_work_area_->removeEventFilter(this);
517 find_work_area_->removeEventFilter(this);
518 this->QWidget::hideEvent(ev);
522 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
528 void FindAndReplace::updateView()
530 widget_->updateGUI();
534 FindAndReplace::FindAndReplace(GuiView & parent,
535 Qt::DockWidgetArea area, Qt::WindowFlags flags)
536 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
539 widget_ = new FindAndReplaceWidget(parent);
541 setFocusProxy(widget_);
545 FindAndReplace::~FindAndReplace()
552 bool FindAndReplace::initialiseParams(std::string const & params)
554 return widget_->initialiseParams(params);
558 void FindAndReplaceWidget::updateGUI()
560 bool replace_enabled = view_.documentBufferView()
561 && !view_.documentBufferView()->buffer().isReadonly();
562 replace_work_area_->setEnabled(replace_enabled);
563 replacePB->setEnabled(replace_enabled);
564 replaceallPB->setEnabled(replace_enabled);
568 Dialog * createGuiSearchAdv(GuiView & lv)
570 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
572 // On Mac show and floating
573 gui->setFloating(true);
579 } // namespace frontend
583 #include "moc_FindAndReplace.cpp"