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"
20 #include "buffer_funcs.h"
21 #include "BufferParams.h"
22 #include "BufferList.h"
24 #include "FuncRequest.h"
26 #include "output_latex.h"
27 #include "OutputParams.h"
30 #include "frontends/alert.h"
32 #include "support/debug.h"
33 #include "support/filetools.h"
34 #include "support/FileName.h"
35 #include "support/gettext.h"
36 #include "support/lassert.h"
37 #include "support/lstrings.h"
39 #include <QCloseEvent>
46 using namespace lyx::support;
52 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
56 find_work_area_->setGuiView(view_);
57 find_work_area_->init();
58 find_work_area_->setFrameStyle(QFrame::StyledPanel);
59 setFocusProxy(find_work_area_);
60 replace_work_area_->setGuiView(view_);
61 replace_work_area_->init();
62 replace_work_area_->setFrameStyle(QFrame::StyledPanel);
63 // We don't want two cursors blinking.
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();
109 case Qt::Key_Backtab:
110 if (obj == replace_work_area_) {
111 LYXERR(Debug::FIND, "Focusing find WA");
112 find_work_area_->setFocus();
120 // standard event processing
121 return QWidget::eventFilter(obj, event);
125 static docstring buffer_to_latex(Buffer & buffer)
127 OutputParams runparams(&buffer.params().encoding());
129 runparams.nice = true;
130 runparams.flavor = OutputParams::LATEX;
131 runparams.linelen = 80; //lyxrc.plaintext_linelen;
132 // No side effect of file copying and image conversion
133 runparams.dryrun = true;
134 buffer.texrow().reset();
135 ParagraphList::const_iterator pit = buffer.paragraphs().begin();
136 ParagraphList::const_iterator const end = buffer.paragraphs().end();
137 for (; pit != end; ++pit) {
138 TeXOnePar(buffer, buffer.text(),
139 pit, os, buffer.texrow(), runparams);
140 LYXERR(Debug::FIND, "searchString up to here: "
147 static vector<string> const & allManualsFiles()
149 static vector<string> v;
150 static const char * files[] = {
151 "Intro", "UserGuide", "Tutorial", "Additional",
152 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
153 "LFUNs", "LaTeXConfig"
157 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
158 fname = i18nLibFileSearch("doc", files[i], "lyx");
159 v.push_back(fname.absFileName());
166 /** Switch p_buf to point to next document buffer.
168 ** Return true if restarted from master-document buffer.
170 static bool nextDocumentBuffer(Buffer * & buf)
172 ListOfBuffers const children = buf->allRelatives();
173 LYXERR(Debug::FIND, "children.size()=" << children.size());
174 ListOfBuffers::const_iterator it =
175 find(children.begin(), children.end(), buf);
176 LASSERT(it != children.end(), /**/)
178 if (it == children.end()) {
179 buf = *children.begin();
187 /** Switch p_buf to point to previous document buffer.
189 ** Return true if restarted from last child buffer.
191 static bool prevDocumentBuffer(Buffer * & buf)
193 ListOfBuffers const children = buf->allRelatives();
194 LYXERR(Debug::FIND, "children.size()=" << children.size());
195 ListOfBuffers::const_iterator it =
196 find(children.begin(), children.end(), buf);
197 LASSERT(it != children.end(), /**/)
198 if (it == children.begin()) {
210 /** Switch buf to point to next or previous buffer in search scope.
212 ** Return true if restarted from scratch.
214 static bool nextPrevBuffer(Buffer * & buf,
215 FindAndReplaceOptions const & opt)
217 bool restarted = false;
219 case FindAndReplaceOptions::S_BUFFER:
222 case FindAndReplaceOptions::S_DOCUMENT:
224 restarted = nextDocumentBuffer(buf);
226 restarted = prevDocumentBuffer(buf);
228 case FindAndReplaceOptions::S_OPEN_BUFFERS:
230 buf = theBufferList().next(buf);
231 restarted = (buf == *theBufferList().begin());
233 buf = theBufferList().previous(buf);
234 restarted = (buf == *(theBufferList().end() - 1));
237 case FindAndReplaceOptions::S_ALL_MANUALS:
238 vector<string> const & manuals = allManualsFiles();
239 vector<string>::const_iterator it =
240 find(manuals.begin(), manuals.end(), buf->absFileName());
241 if (it == manuals.end())
242 it = manuals.begin();
243 else if (opt.forward) {
245 if (it == manuals.end()) {
246 it = manuals.begin();
250 if (it == manuals.begin()) {
256 FileName const & fname = FileName(*it);
257 if (!theBufferList().exists(fname)) {
258 guiApp->currentView()->setBusy(false);
259 guiApp->currentView()->loadDocument(fname, false);
260 guiApp->currentView()->setBusy(true);
262 buf = theBufferList().getBuffer(fname);
269 /** Find the finest question message to post to the user */
270 docstring getQuestionString(FindAndReplaceOptions const & opt)
274 case FindAndReplaceOptions::S_BUFFER:
277 case FindAndReplaceOptions::S_DOCUMENT:
278 scope = _("Master document");
280 case FindAndReplaceOptions::S_OPEN_BUFFERS:
281 scope = _("Open files");
283 case FindAndReplaceOptions::S_ALL_MANUALS:
284 scope = _("Manuals");
287 docstring message = opt.forward ?
288 bformat(_("%1$s: the end was reached while searching forward.\n"
289 "Continue searching from the beginning?"),
291 bformat(_("%1$s: the beginning was reached while searching backward.\n"
292 "Continue searching from the end?"),
299 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt)
301 int wrap_answer = -1;
304 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
305 BufferView * bv = view_.documentBufferView();
306 Buffer * buf = &bv->buffer();
308 Buffer * buf_orig = &bv->buffer();
309 DocIterator cur_orig(bv->cursor());
311 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
312 vector<string> const & v = allManualsFiles();
313 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
314 FileName const & fname = FileName(*v.begin());
315 if (!theBufferList().exists(fname)) {
316 guiApp->currentView()->setBusy(false);
317 guiApp->currentView()->loadDocument(fname, false);
318 guiApp->currentView()->setBusy(true);
320 buf = theBufferList().getBuffer(fname);
321 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
322 buf->absFileName()));
323 bv = view_.documentBufferView();
324 bv->cursor().clear();
325 bv->cursor().push_back(CursorSlice(buf->inset()));
330 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
332 LYXERR(Debug::FIND, "dispatched");
333 if (bv->cursor().result().dispatched()) {
334 // Match found, selected and replaced if needed
338 // No match found in current buffer:
339 // select next buffer in scope, if any
340 bool prompt = nextPrevBuffer(buf, opt);
342 if (wrap_answer != -1)
344 docstring q = getQuestionString(opt);
345 wrap_answer = frontend::Alert::prompt(
346 _("Wrap search?"), q,
347 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 bv->cursor().setCursor(cur_orig);
375 void FindAndReplaceWidget::findAndReplace(
376 bool casesensitive, bool matchword, bool backwards,
377 bool expandmacros, bool ignoreformat, bool replace,
380 Buffer & buffer = find_work_area_->bufferView().buffer();
381 docstring searchString;
383 searchString = buffer_to_latex(buffer);
385 ParIterator it = buffer.par_iterator_begin();
386 ParIterator end = buffer.par_iterator_end();
387 OutputParams runparams(&buffer.params().encoding());
389 runparams.nice = true;
390 runparams.flavor = OutputParams::LATEX;
391 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
392 runparams.dryrun = true;
393 for (; it != end; ++it) {
394 LYXERR(Debug::FIND, "Adding to search string: '"
395 << it->asString(false)
398 it->stringify(pos_type(0), it->size(),
399 AS_STR_INSETS, runparams);
402 if (to_utf8(searchString).empty()) {
403 buffer.message(_("Nothing to search"));
407 to_utf8(searchString).find("\\regexp") != std::string::npos;
408 docstring replaceString;
410 Buffer & repl_buffer =
411 replace_work_area_->bufferView().buffer();
413 repl_buffer.write(oss);
414 //buffer_to_latex(replace_buffer);
415 replaceString = from_utf8(oss.str());
417 replaceString = from_utf8(LYX_FR_NULL_STRING);
419 FindAndReplaceOptions::SearchScope scope =
420 FindAndReplaceOptions::S_BUFFER;
421 if (CurrentDocument->isChecked())
422 scope = FindAndReplaceOptions::S_BUFFER;
423 else if (MasterDocument->isChecked())
424 scope = FindAndReplaceOptions::S_DOCUMENT;
425 else if (OpenDocuments->isChecked())
426 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
427 else if (AllManualsRB->isChecked())
428 scope = FindAndReplaceOptions::S_ALL_MANUALS;
430 LASSERT(false, /**/);
431 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
432 << "searchstring=" << searchString
433 << ", casesensitiv=" << casesensitive
434 << ", matchword=" << matchword
435 << ", backwards=" << backwards
436 << ", expandmacros=" << expandmacros
437 << ", ignoreformat=" << ignoreformat
438 << ", regexp=" << regexp
439 << ", replaceString" << replaceString
440 << ", keep_case=" << keep_case
441 << ", scope=" << scope);
442 FindAndReplaceOptions opt(searchString, casesensitive, matchword,
443 !backwards, expandmacros, ignoreformat,
444 regexp, replaceString, keep_case, scope);
446 findAndReplaceScope(opt);
447 view_.setBusy(false);
451 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
453 if (! view_.currentMainWorkArea()) {
454 view_.message(_("No open document(s) in which to search"));
457 // Finalize macros that are being typed, both in main document and in search or replacement WAs
458 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
459 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
460 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
461 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
463 // FIXME: create a Dialog::returnFocus()
464 // or something instead of this:
465 view_.setCurrentWorkArea(view_.currentMainWorkArea());
466 findAndReplace(caseCB->isChecked(),
467 wordsCB->isChecked(),
469 expandMacrosCB->isChecked(),
470 ignoreFormatCB->isChecked(),
472 keepCaseCB->isChecked());
476 void FindAndReplaceWidget::hideDialog()
478 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
482 void FindAndReplaceWidget::on_findNextPB_clicked()
484 findAndReplace(searchbackCB->isChecked(), false);
485 find_work_area_->setFocus();
489 void FindAndReplaceWidget::on_replacePB_clicked()
491 findAndReplace(searchbackCB->isChecked(), true);
492 replace_work_area_->setFocus();
496 void FindAndReplaceWidget::on_replaceallPB_clicked()
498 replace_work_area_->setFocus();
502 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
504 view_.setCurrentWorkArea(find_work_area_);
505 LYXERR(Debug::FIND, "Selecting entire find buffer");
506 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
507 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
508 find_work_area_->installEventFilter(this);
509 replace_work_area_->installEventFilter(this);
513 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
515 replace_work_area_->removeEventFilter(this);
516 find_work_area_->removeEventFilter(this);
517 this->QWidget::hideEvent(ev);
521 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
527 FindAndReplace::FindAndReplace(GuiView & parent,
528 Qt::DockWidgetArea area, Qt::WindowFlags flags)
529 : DockView(parent, "Find LyX", qt_("Advanced Find and Replace"),
532 widget_ = new FindAndReplaceWidget(parent);
534 setFocusProxy(widget_);
538 FindAndReplace::~FindAndReplace()
545 bool FindAndReplace::initialiseParams(std::string const & params)
547 return widget_->initialiseParams(params);
551 Dialog * createGuiSearchAdv(GuiView & lv)
553 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
555 // On Mac show and floating
556 gui->setFloating(true);
562 } // namespace frontend
566 #include "moc_FindAndReplace.cpp"