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 bool replace_enabled = view_.documentBufferView() && !view_.documentBufferView()->buffer().isReadonly();
71 replace_work_area_->setEnabled(replace_enabled);
72 replacePB->setEnabled(replace_enabled);
73 replaceallPB->setEnabled(replace_enabled);
75 if (event->type() != QEvent::KeyPress
76 || (obj != find_work_area_ && obj != replace_work_area_))
77 return QWidget::eventFilter(obj, event);
79 QKeyEvent * e = static_cast<QKeyEvent *> (event);
82 if (e->modifiers() == Qt::NoModifier) {
89 case Qt::Key_Return: {
90 // with shift we (temporarily) change search/replace direction
91 bool const searchback = searchbackCB->isChecked();
92 if (e->modifiers() == Qt::ShiftModifier && !searchback)
93 searchbackCB->setChecked(!searchback);
95 if (obj == find_work_area_)
96 on_findNextPB_clicked();
98 on_replacePB_clicked();
100 searchbackCB->setChecked(searchback);
105 if (e->modifiers() == Qt::NoModifier) {
106 if (obj == find_work_area_){
107 LYXERR(Debug::FIND, "Focusing replace WA");
108 replace_work_area_->setFocus();
109 LYXERR(Debug::FIND, "Selecting entire replace buffer");
110 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
111 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
117 case Qt::Key_Backtab:
118 if (obj == replace_work_area_) {
119 LYXERR(Debug::FIND, "Focusing find WA");
120 find_work_area_->setFocus();
121 LYXERR(Debug::FIND, "Selecting entire find buffer");
122 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
123 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
131 // standard event processing
132 return QWidget::eventFilter(obj, event);
136 static vector<string> const & allManualsFiles()
138 static vector<string> v;
139 static const char * files[] = {
140 "Intro", "UserGuide", "Tutorial", "Additional",
141 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
142 "LFUNs", "LaTeXConfig"
146 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
147 fname = i18nLibFileSearch("doc", files[i], "lyx");
148 v.push_back(fname.absFileName());
155 /** Switch p_buf to point to next document buffer.
157 ** Return true if restarted from master-document buffer.
159 static bool nextDocumentBuffer(Buffer * & buf)
161 ListOfBuffers const children = buf->allRelatives();
162 LYXERR(Debug::FIND, "children.size()=" << children.size());
163 ListOfBuffers::const_iterator it =
164 find(children.begin(), children.end(), buf);
165 LASSERT(it != children.end(), /**/);
167 if (it == children.end()) {
168 buf = *children.begin();
176 /** Switch p_buf to point to previous document buffer.
178 ** Return true if restarted from last child buffer.
180 static bool prevDocumentBuffer(Buffer * & buf)
182 ListOfBuffers const children = buf->allRelatives();
183 LYXERR(Debug::FIND, "children.size()=" << children.size());
184 ListOfBuffers::const_iterator it =
185 find(children.begin(), children.end(), buf);
186 LASSERT(it != children.end(), /**/)
187 if (it == children.begin()) {
199 /** Switch buf to point to next or previous buffer in search scope.
201 ** Return true if restarted from scratch.
203 static bool nextPrevBuffer(Buffer * & buf,
204 FindAndReplaceOptions const & opt)
206 bool restarted = false;
208 case FindAndReplaceOptions::S_BUFFER:
211 case FindAndReplaceOptions::S_DOCUMENT:
213 restarted = nextDocumentBuffer(buf);
215 restarted = prevDocumentBuffer(buf);
217 case FindAndReplaceOptions::S_OPEN_BUFFERS:
219 buf = theBufferList().next(buf);
220 restarted = (buf == *theBufferList().begin());
222 buf = theBufferList().previous(buf);
223 restarted = (buf == *(theBufferList().end() - 1));
226 case FindAndReplaceOptions::S_ALL_MANUALS:
227 vector<string> const & manuals = allManualsFiles();
228 vector<string>::const_iterator it =
229 find(manuals.begin(), manuals.end(), buf->absFileName());
230 if (it == manuals.end())
231 it = manuals.begin();
232 else if (opt.forward) {
234 if (it == manuals.end()) {
235 it = manuals.begin();
239 if (it == manuals.begin()) {
245 FileName const & fname = FileName(*it);
246 if (!theBufferList().exists(fname)) {
247 guiApp->currentView()->setBusy(false);
248 guiApp->currentView()->loadDocument(fname, false);
249 guiApp->currentView()->setBusy(true);
251 buf = theBufferList().getBuffer(fname);
258 /** Find the finest question message to post to the user */
259 docstring getQuestionString(FindAndReplaceOptions const & opt)
263 case FindAndReplaceOptions::S_BUFFER:
266 case FindAndReplaceOptions::S_DOCUMENT:
267 scope = _("Master document");
269 case FindAndReplaceOptions::S_OPEN_BUFFERS:
270 scope = _("Open files");
272 case FindAndReplaceOptions::S_ALL_MANUALS:
273 scope = _("Manuals");
276 docstring message = opt.forward ?
277 bformat(_("%1$s: the end was reached while searching forward.\n"
278 "Continue searching from the beginning?"),
280 bformat(_("%1$s: the beginning was reached while searching backward.\n"
281 "Continue searching from the end?"),
288 /// Return true if a match was found
289 bool FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt, bool replace_all)
291 BufferView * bv = view_.documentBufferView();
294 Buffer * buf = &bv->buffer();
295 Buffer * buf_orig = &bv->buffer();
296 DocIterator cur_orig(bv->cursor());
297 int wrap_answer = -1;
300 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
303 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
304 vector<string> const & v = allManualsFiles();
305 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
306 FileName const & fname = FileName(*v.begin());
307 if (!theBufferList().exists(fname)) {
308 guiApp->currentView()->setBusy(false);
309 guiApp->currentView()->loadDocument(fname, false);
310 guiApp->currentView()->setBusy(true);
312 buf = theBufferList().getBuffer(fname);
314 view_.setBusy(false);
318 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
319 buf->absFileName()));
320 bv = view_.documentBufferView();
321 bv->cursor().clear();
322 bv->cursor().push_back(CursorSlice(buf->inset()));
327 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
329 LYXERR(Debug::FIND, "dispatched");
330 if (bv->cursor().result().dispatched()) {
331 // New match found and selected (old selection replaced if needed)
334 view_.setBusy(false);
336 } else if (replace_all)
337 bv->clearSelection();
339 // No match found in current buffer (however old selection might have been replaced)
340 // select next buffer in scope, if any
341 bool const prompt = nextPrevBuffer(buf, opt);
345 if (wrap_answer != -1)
347 docstring q = getQuestionString(opt);
348 view_.setBusy(false);
349 wrap_answer = frontend::Alert::prompt(
350 _("Wrap search?"), q,
351 0, 1, _("&Yes"), _("&No"));
353 if (wrap_answer == 1)
356 if (buf != &view_.documentBufferView()->buffer())
357 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
358 buf->absFileName()));
359 bv = view_.documentBufferView();
361 bv->cursor().clear();
362 bv->cursor().push_back(CursorSlice(buf->inset()));
364 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
365 bv->cursor().setCursor(doc_iterator_end(buf));
366 bv->cursor().backwardPos();
367 LYXERR(Debug::FIND, "findBackAdv5: cur: "
370 bv->clearSelection();
371 } while (wrap_answer != 1);
372 if (buf_orig != &view_.documentBufferView()->buffer())
373 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
374 buf_orig->absFileName()));
375 bv = view_.documentBufferView();
376 // This may happen after a replace occurred
377 if (cur_orig.pos() > cur_orig.lastpos())
378 cur_orig.pos() = cur_orig.lastpos();
379 bv->cursor().setCursor(cur_orig);
380 view_.setBusy(false);
385 /// Return true if a match was found
386 bool FindAndReplaceWidget::findAndReplace(
387 bool casesensitive, bool matchword, bool backwards,
388 bool expandmacros, bool ignoreformat, bool replace,
389 bool keep_case, bool replace_all)
391 Buffer & find_buf = find_work_area_->bufferView().buffer();
392 docstring const & find_buf_name = find_buf.fileName().absoluteFilePath();
394 if (find_buf.text().empty()) {
395 view_.message(_("Nothing to search"));
399 Buffer & repl_buf = replace_work_area_->bufferView().buffer();
400 docstring const & repl_buf_name = replace ?
401 repl_buf.fileName().absoluteFilePath() : docstring();
403 FindAndReplaceOptions::SearchScope scope =
404 FindAndReplaceOptions::S_BUFFER;
405 if (CurrentDocument->isChecked())
406 scope = FindAndReplaceOptions::S_BUFFER;
407 else if (MasterDocument->isChecked())
408 scope = FindAndReplaceOptions::S_DOCUMENT;
409 else if (OpenDocuments->isChecked())
410 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
411 else if (AllManualsRB->isChecked())
412 scope = FindAndReplaceOptions::S_ALL_MANUALS;
414 LASSERT(false, /**/);
415 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
416 << "find_buf_name=" << find_buf_name
417 << ", casesensitiv=" << casesensitive
418 << ", matchword=" << matchword
419 << ", backwards=" << backwards
420 << ", expandmacros=" << expandmacros
421 << ", ignoreformat=" << ignoreformat
422 << ", repl_buf_name" << repl_buf_name
423 << ", keep_case=" << keep_case
424 << ", scope=" << scope);
425 FindAndReplaceOptions opt(find_buf_name, casesensitive, matchword,
426 !backwards, expandmacros, ignoreformat,
427 repl_buf_name, keep_case, scope);
428 return findAndReplaceScope(opt, replace_all);
432 bool FindAndReplaceWidget::findAndReplace(bool backwards, bool replace, bool replace_all)
434 if (! view_.currentMainWorkArea()) {
435 view_.message(_("No open document(s) in which to search"));
438 // Finalize macros that are being typed, both in main document and in search or replacement WAs
439 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
440 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
441 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
442 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
444 // FIXME: create a Dialog::returnFocus()
445 // or something instead of this:
446 view_.setCurrentWorkArea(view_.currentMainWorkArea());
447 return findAndReplace(caseCB->isChecked(),
448 wordsCB->isChecked(),
450 expandMacrosCB->isChecked(),
451 ignoreFormatCB->isChecked(),
453 keepCaseCB->isChecked(),
458 void FindAndReplaceWidget::hideDialog()
460 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
464 void FindAndReplaceWidget::on_findNextPB_clicked()
466 findAndReplace(searchbackCB->isChecked(), false);
467 find_work_area_->setFocus();
471 void FindAndReplaceWidget::on_replacePB_clicked()
473 findAndReplace(searchbackCB->isChecked(), true);
474 replace_work_area_->setFocus();
478 void FindAndReplaceWidget::on_replaceallPB_clicked()
480 findAndReplace(searchbackCB->isChecked(), true, true);
481 replace_work_area_->setFocus();
485 /** Copy selected elements from bv's BufferParams to the dest_bv's one
486 ** We don't want to copy'em all, e.g., not the default master **/
487 static void copy_params(BufferView const & bv, BufferView & dest_bv) {
488 Buffer const & doc_buf = bv.buffer();
489 BufferParams const & doc_bp = doc_buf.params();
490 string const & lang = doc_bp.language->lang();
491 string const & doc_class = doc_bp.documentClass().name();
492 Buffer & dest_buf = dest_bv.buffer();
493 dest_buf.params().setLanguage(lang);
494 dest_buf.params().setBaseClass(doc_class);
495 dest_buf.params().makeDocumentClass();
496 dest_bv.cursor().current_font.setLanguage(doc_bp.language);
500 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
502 LYXERR(Debug::DEBUG, "showEvent()" << endl);
503 BufferView * bv = view_.documentBufferView();
505 copy_params(*bv, find_work_area_->bufferView());
506 copy_params(*bv, replace_work_area_->bufferView());
509 find_work_area_->installEventFilter(this);
510 replace_work_area_->installEventFilter(this);
512 view_.setCurrentWorkArea(find_work_area_);
513 LYXERR(Debug::FIND, "Selecting entire find buffer");
514 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
515 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
519 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
521 replace_work_area_->removeEventFilter(this);
522 find_work_area_->removeEventFilter(this);
523 this->QWidget::hideEvent(ev);
527 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
533 FindAndReplace::FindAndReplace(GuiView & parent,
534 Qt::DockWidgetArea area, Qt::WindowFlags flags)
535 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
538 widget_ = new FindAndReplaceWidget(parent);
540 setFocusProxy(widget_);
544 FindAndReplace::~FindAndReplace()
551 bool FindAndReplace::initialiseParams(std::string const & params)
553 return widget_->initialiseParams(params);
557 Dialog * createGuiSearchAdv(GuiView & lv)
559 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
561 // On Mac show and floating
562 gui->setFloating(true);
568 } // namespace frontend
572 #include "moc_FindAndReplace.cpp"