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 "buffer_funcs.h"
23 #include "BufferParams.h"
24 #include "BufferList.h"
26 #include "FuncRequest.h"
28 #include "output_latex.h"
29 #include "OutputParams.h"
32 #include "frontends/alert.h"
34 #include "support/debug.h"
35 #include "support/filetools.h"
36 #include "support/FileName.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
41 #include <QCloseEvent>
48 using namespace lyx::support;
54 /// Apply to buf the parameters supplied through bp
55 static void ApplyParams(Buffer &buf, BufferParams const & bp) {
57 ss << "\\begin_header\n";
59 ss << "\\end_header\n";
60 istringstream iss(ss.str());
63 int unknown_tokens = buf.readHeader(lex);
64 LASSERT(unknown_tokens == 0, /* */);
68 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
72 find_work_area_->setGuiView(view_);
73 find_work_area_->init();
74 find_work_area_->setFrameStyle(QFrame::StyledPanel);
76 setFocusProxy(find_work_area_);
77 replace_work_area_->setGuiView(view_);
78 replace_work_area_->init();
79 replace_work_area_->setFrameStyle(QFrame::StyledPanel);
81 // We don't want two cursors blinking.
82 replace_work_area_->stopBlinkingCursor();
86 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
88 if (event->type() != QEvent::KeyPress
89 || (obj != find_work_area_ && obj != replace_work_area_))
90 return QWidget::eventFilter(obj, event);
92 QKeyEvent * e = static_cast<QKeyEvent *> (event);
95 if (e->modifiers() == Qt::NoModifier) {
102 case Qt::Key_Return: {
103 // with shift we (temporarily) change search/replace direction
104 bool const searchback = searchbackCB->isChecked();
105 if (e->modifiers() == Qt::ShiftModifier && !searchback)
106 searchbackCB->setChecked(!searchback);
108 if (obj == find_work_area_)
109 on_findNextPB_clicked();
111 on_replacePB_clicked();
112 // back to how it was
113 searchbackCB->setChecked(searchback);
118 if (e->modifiers() == Qt::NoModifier) {
119 if (obj == find_work_area_){
120 LYXERR(Debug::FIND, "Focusing replace WA");
121 replace_work_area_->setFocus();
127 case Qt::Key_Backtab:
128 if (obj == replace_work_area_) {
129 LYXERR(Debug::FIND, "Focusing find WA");
130 find_work_area_->setFocus();
138 // standard event processing
139 return QWidget::eventFilter(obj, event);
143 static docstring buffer_to_latex(Buffer & buffer)
145 OutputParams runparams(&buffer.params().encoding());
147 runparams.nice = true;
148 runparams.flavor = OutputParams::LATEX;
149 runparams.linelen = 80; //lyxrc.plaintext_linelen;
150 // No side effect of file copying and image conversion
151 runparams.dryrun = true;
152 buffer.texrow().reset();
153 pit_type const endpit = buffer.paragraphs().size();
154 for (pit_type pit = 0; pit != endpit; ++pit) {
155 TeXOnePar(buffer, buffer.text(),
156 pit, os, buffer.texrow(), runparams);
157 LYXERR(Debug::FIND, "searchString up to here: "
164 static vector<string> const & allManualsFiles()
166 static vector<string> v;
167 static const char * files[] = {
168 "Intro", "UserGuide", "Tutorial", "Additional",
169 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
170 "LFUNs", "LaTeXConfig"
174 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
175 fname = i18nLibFileSearch("doc", files[i], "lyx");
176 v.push_back(fname.absFileName());
183 /** Switch p_buf to point to next document buffer.
185 ** Return true if restarted from master-document buffer.
187 static bool nextDocumentBuffer(Buffer * & buf)
189 ListOfBuffers const children = buf->allRelatives();
190 LYXERR(Debug::FIND, "children.size()=" << children.size());
191 ListOfBuffers::const_iterator it =
192 find(children.begin(), children.end(), buf);
193 LASSERT(it != children.end(), /**/)
195 if (it == children.end()) {
196 buf = *children.begin();
204 /** Switch p_buf to point to previous document buffer.
206 ** Return true if restarted from last child buffer.
208 static bool prevDocumentBuffer(Buffer * & buf)
210 ListOfBuffers const children = buf->allRelatives();
211 LYXERR(Debug::FIND, "children.size()=" << children.size());
212 ListOfBuffers::const_iterator it =
213 find(children.begin(), children.end(), buf);
214 LASSERT(it != children.end(), /**/)
215 if (it == children.begin()) {
227 /** Switch buf to point to next or previous buffer in search scope.
229 ** Return true if restarted from scratch.
231 static bool nextPrevBuffer(Buffer * & buf,
232 FindAndReplaceOptions const & opt)
234 bool restarted = false;
236 case FindAndReplaceOptions::S_BUFFER:
239 case FindAndReplaceOptions::S_DOCUMENT:
241 restarted = nextDocumentBuffer(buf);
243 restarted = prevDocumentBuffer(buf);
245 case FindAndReplaceOptions::S_OPEN_BUFFERS:
247 buf = theBufferList().next(buf);
248 restarted = (buf == *theBufferList().begin());
250 buf = theBufferList().previous(buf);
251 restarted = (buf == *(theBufferList().end() - 1));
254 case FindAndReplaceOptions::S_ALL_MANUALS:
255 vector<string> const & manuals = allManualsFiles();
256 vector<string>::const_iterator it =
257 find(manuals.begin(), manuals.end(), buf->absFileName());
258 if (it == manuals.end())
259 it = manuals.begin();
260 else if (opt.forward) {
262 if (it == manuals.end()) {
263 it = manuals.begin();
267 if (it == manuals.begin()) {
273 FileName const & fname = FileName(*it);
274 if (!theBufferList().exists(fname)) {
275 guiApp->currentView()->setBusy(false);
276 guiApp->currentView()->loadDocument(fname, false);
277 guiApp->currentView()->setBusy(true);
279 buf = theBufferList().getBuffer(fname);
286 /** Find the finest question message to post to the user */
287 docstring getQuestionString(FindAndReplaceOptions const & opt)
291 case FindAndReplaceOptions::S_BUFFER:
294 case FindAndReplaceOptions::S_DOCUMENT:
295 scope = _("Master document");
297 case FindAndReplaceOptions::S_OPEN_BUFFERS:
298 scope = _("Open files");
300 case FindAndReplaceOptions::S_ALL_MANUALS:
301 scope = _("Manuals");
304 docstring message = opt.forward ?
305 bformat(_("%1$s: the end was reached while searching forward.\n"
306 "Continue searching from the beginning?"),
308 bformat(_("%1$s: the beginning was reached while searching backward.\n"
309 "Continue searching from the end?"),
316 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt)
318 BufferView * bv = view_.documentBufferView();
321 Buffer * buf = &bv->buffer();
322 Buffer * buf_orig = &bv->buffer();
323 DocIterator cur_orig(bv->cursor());
324 int wrap_answer = -1;
327 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
330 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
331 vector<string> const & v = allManualsFiles();
332 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
333 FileName const & fname = FileName(*v.begin());
334 if (!theBufferList().exists(fname)) {
335 guiApp->currentView()->setBusy(false);
336 guiApp->currentView()->loadDocument(fname, false);
337 guiApp->currentView()->setBusy(true);
339 buf = theBufferList().getBuffer(fname);
340 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
341 buf->absFileName()));
342 bv = view_.documentBufferView();
343 bv->cursor().clear();
344 bv->cursor().push_back(CursorSlice(buf->inset()));
349 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
351 LYXERR(Debug::FIND, "dispatched");
352 if (bv->cursor().result().dispatched()) {
353 // New match found and selected (old selection replaced if needed)
354 view_.setBusy(false);
358 // No match found in current buffer (however old selection might have been replaced)
359 // select next buffer in scope, if any
360 bool prompt = nextPrevBuffer(buf, opt);
362 if (wrap_answer != -1)
364 docstring q = getQuestionString(opt);
365 view_.setBusy(false);
366 wrap_answer = frontend::Alert::prompt(
367 _("Wrap search?"), q,
368 0, 1, _("&Yes"), _("&No"));
370 if (wrap_answer == 1)
373 if (buf != &view_.documentBufferView()->buffer())
374 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
375 buf->absFileName()));
376 bv = view_.documentBufferView();
378 bv->cursor().clear();
379 bv->cursor().push_back(CursorSlice(buf->inset()));
381 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
382 bv->cursor().setCursor(doc_iterator_end(buf));
383 bv->cursor().backwardPos();
384 LYXERR(Debug::FIND, "findBackAdv5: cur: "
387 bv->clearSelection();
388 } while (wrap_answer != 1);
389 if (buf_orig != &view_.documentBufferView()->buffer())
390 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
391 buf_orig->absFileName()));
392 bv = view_.documentBufferView();
393 // This may happen after a replace occurred
394 if (cur_orig.pos() > cur_orig.lastpos())
395 cur_orig.pos() = cur_orig.lastpos();
396 bv->cursor().setCursor(cur_orig);
397 view_.setBusy(false);
401 void FindAndReplaceWidget::findAndReplace(
402 bool casesensitive, bool matchword, bool backwards,
403 bool expandmacros, bool ignoreformat, bool replace,
406 Buffer & buffer = find_work_area_->bufferView().buffer();
407 docstring searchString;
409 searchString = buffer_to_latex(buffer);
411 ParIterator it = buffer.par_iterator_begin();
412 ParIterator end = buffer.par_iterator_end();
413 OutputParams runparams(&buffer.params().encoding());
415 runparams.nice = true;
416 runparams.flavor = OutputParams::LATEX;
417 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
418 runparams.dryrun = true;
419 for (; it != end; ++it) {
420 LYXERR(Debug::FIND, "Adding to search string: '"
421 << it->asString(false)
424 it->stringify(pos_type(0), it->size(),
425 AS_STR_INSETS, runparams);
428 if (to_utf8(searchString).empty()) {
429 buffer.message(_("Nothing to search"));
433 to_utf8(searchString).find("\\regexp") != std::string::npos;
434 docstring replaceString;
436 Buffer & repl_buffer =
437 replace_work_area_->bufferView().buffer();
439 repl_buffer.write(oss);
440 //buffer_to_latex(replace_buffer);
441 replaceString = from_utf8(oss.str());
443 replaceString = from_utf8(LYX_FR_NULL_STRING);
445 FindAndReplaceOptions::SearchScope scope =
446 FindAndReplaceOptions::S_BUFFER;
447 if (CurrentDocument->isChecked())
448 scope = FindAndReplaceOptions::S_BUFFER;
449 else if (MasterDocument->isChecked())
450 scope = FindAndReplaceOptions::S_DOCUMENT;
451 else if (OpenDocuments->isChecked())
452 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
453 else if (AllManualsRB->isChecked())
454 scope = FindAndReplaceOptions::S_ALL_MANUALS;
456 LASSERT(false, /**/);
457 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
458 << "searchstring=" << searchString
459 << ", casesensitiv=" << casesensitive
460 << ", matchword=" << matchword
461 << ", backwards=" << backwards
462 << ", expandmacros=" << expandmacros
463 << ", ignoreformat=" << ignoreformat
464 << ", regexp=" << regexp
465 << ", replaceString" << replaceString
466 << ", keep_case=" << keep_case
467 << ", scope=" << scope);
468 FindAndReplaceOptions opt(searchString, casesensitive, matchword,
469 !backwards, expandmacros, ignoreformat,
470 regexp, replaceString, keep_case, scope);
471 findAndReplaceScope(opt);
475 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
477 if (! view_.currentMainWorkArea()) {
478 view_.message(_("No open document(s) in which to search"));
481 // Finalize macros that are being typed, both in main document and in search or replacement WAs
482 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
483 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
484 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
485 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
487 // FIXME: create a Dialog::returnFocus()
488 // or something instead of this:
489 view_.setCurrentWorkArea(view_.currentMainWorkArea());
490 findAndReplace(caseCB->isChecked(),
491 wordsCB->isChecked(),
493 expandMacrosCB->isChecked(),
494 ignoreFormatCB->isChecked(),
496 keepCaseCB->isChecked());
500 void FindAndReplaceWidget::hideDialog()
502 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
506 void FindAndReplaceWidget::on_findNextPB_clicked()
508 findAndReplace(searchbackCB->isChecked(), false);
509 find_work_area_->setFocus();
513 void FindAndReplaceWidget::on_replacePB_clicked()
515 findAndReplace(searchbackCB->isChecked(), true);
516 replace_work_area_->setFocus();
520 void FindAndReplaceWidget::on_replaceallPB_clicked()
522 replace_work_area_->setFocus();
526 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
528 BufferView * bv = view_.documentBufferView();
530 Buffer & doc_buf = bv->buffer();
531 BufferParams & doc_bp = doc_buf.params();
532 Buffer & find_buf = find_work_area_->bufferView().buffer();
533 LYXERR(Debug::FIND, "Applying document params to find buffer");
534 ApplyParams(find_buf, doc_bp);
535 Buffer & replace_buf = replace_work_area_->bufferView().buffer();
536 LYXERR(Debug::FIND, "Applying document params to replace buffer");
537 ApplyParams(replace_buf, doc_bp);
539 string lang = doc_bp.language->lang();
540 LYXERR(Debug::FIND, "Setting current editing language to " << lang << endl);
541 FuncRequest cmd(LFUN_LANGUAGE, lang);
542 find_buf.text().dispatch(find_work_area_->bufferView().cursor(), cmd);
543 replace_buf.text().dispatch(replace_work_area_->bufferView().cursor(), cmd);
545 view_.setCurrentWorkArea(find_work_area_);
546 LYXERR(Debug::FIND, "Selecting entire find buffer");
547 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
548 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
550 find_work_area_->installEventFilter(this);
551 replace_work_area_->installEventFilter(this);
555 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
557 replace_work_area_->removeEventFilter(this);
558 find_work_area_->removeEventFilter(this);
559 this->QWidget::hideEvent(ev);
563 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
569 FindAndReplace::FindAndReplace(GuiView & parent,
570 Qt::DockWidgetArea area, Qt::WindowFlags flags)
571 : DockView(parent, "findreplaceadv", qt_("Advanced Find and Replace"),
574 widget_ = new FindAndReplaceWidget(parent);
576 setFocusProxy(widget_);
580 FindAndReplace::~FindAndReplace()
587 bool FindAndReplace::initialiseParams(std::string const & params)
589 return widget_->initialiseParams(params);
593 Dialog * createGuiSearchAdv(GuiView & lv)
595 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
597 // On Mac show and floating
598 gui->setFloating(true);
604 } // namespace frontend
608 #include "moc_FindAndReplace.cpp"