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) {
126 OutputParams runparams(&buffer.params().encoding());
128 runparams.nice = true;
129 runparams.flavor = OutputParams::LATEX;
130 runparams.linelen = 80; //lyxrc.plaintext_linelen;
131 // No side effect of file copying and image conversion
132 runparams.dryrun = true;
133 buffer.texrow().reset();
134 ParagraphList::const_iterator pit = buffer.paragraphs().begin();
135 ParagraphList::const_iterator const end = buffer.paragraphs().end();
136 for (; pit != end; ++pit) {
137 TeXOnePar(buffer, buffer.text(),
138 pit, os, buffer.texrow(), runparams);
139 LYXERR(Debug::FIND, "searchString up to here: "
146 static vector<string> const & allManualsFiles() {
147 static vector<string> v;
148 static const char * files[] = {
149 "Intro", "UserGuide", "Tutorial", "Additional",
150 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
151 "LFUNs", "LaTeXConfig"
155 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
156 fname = i18nLibFileSearch("doc", files[i], "lyx");
157 v.push_back(fname.absFileName());
164 /** Switch p_buf to point to next document buffer.
166 ** Return true if restarted from master-document buffer.
169 ** Not using p_buf->allRelatives() here, because I'm not sure
170 ** whether or not the returned order is independent of p_buf.
172 static bool next_document_buffer(Buffer * & p_buf) {
173 Buffer *p_master = p_buf;
177 p_master = const_cast<Buffer *>(p_master->masterBuffer());
178 LYXERR(Debug::FIND, "p_old="
182 } while (p_master != p_old);
183 LASSERT(p_master != NULL, /**/);
184 vector<Buffer *> v_children;
185 /* Root master added as first buffer in the vector */
186 v_children.push_back(p_master);
187 p_master->getChildren(v_children, true);
188 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
189 vector<Buffer *>::const_iterator it =
190 find(v_children.begin(), v_children.end(), p_buf);
191 LASSERT(it != v_children.end(), /**/)
193 if (it == v_children.end()) {
194 p_buf = *v_children.begin();
202 /** Switch p_buf to point to previous document buffer.
204 ** Return true if restarted from last child buffer.
207 ** Not using p_buf->allRelatives() here, because I'm not sure
208 ** whether or not the returned order is independent of p_buf.
210 static bool prev_document_buffer(Buffer * & p_buf) {
211 Buffer *p_master = p_buf;
215 p_master = const_cast<Buffer *>(p_master->masterBuffer());
218 << ", p_master=" << p_master);
219 } while (p_master != p_old);
220 LASSERT(p_master != NULL, /**/);
221 vector<Buffer *> v_children;
222 /* Root master added as first buffer in the vector */
223 v_children.push_back(p_master);
224 p_master->getChildren(v_children, true);
225 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
226 vector<Buffer *>::const_iterator it =
227 find(v_children.begin(), v_children.end(), p_buf);
228 LASSERT(it != v_children.end(), /**/)
229 if (it == v_children.begin()) {
230 it = v_children.end();
241 /** Switch buf to point to next or previous buffer in search scope.
243 ** Return true if restarted from scratch.
245 static bool next_prev_buffer(Buffer * & buf,
246 FindAndReplaceOptions const & opt)
248 bool restarted = false;
250 case FindAndReplaceOptions::S_BUFFER:
253 case FindAndReplaceOptions::S_DOCUMENT:
255 restarted = next_document_buffer(buf);
257 restarted = prev_document_buffer(buf);
259 case FindAndReplaceOptions::S_OPEN_BUFFERS:
261 buf = theBufferList().next(buf);
262 restarted = buf == *theBufferList().begin();
264 buf = theBufferList().previous(buf);
265 restarted = buf == *(theBufferList().end() - 1);
268 case FindAndReplaceOptions::S_ALL_MANUALS:
269 vector<string> const & v = allManualsFiles();
270 vector<string>::const_iterator it =
271 find(v.begin(), v.end(), buf->absFileName());
274 } else if (opt.forward) {
281 if (it == v.begin()) {
287 FileName const & fname = FileName(*it);
288 if (!theBufferList().exists(fname)) {
289 guiApp->currentView()->setBusy(false);
290 guiApp->currentView()->loadDocument(fname, false);
291 guiApp->currentView()->setBusy(true);
293 buf = theBufferList().getBuffer(fname);
300 /** Find the finest question message to post to the user */
301 docstring question_string(FindAndReplaceOptions const & opt)
305 case FindAndReplaceOptions::S_BUFFER:
306 scope = _("file[[scope]]");
308 case FindAndReplaceOptions::S_DOCUMENT:
309 scope = _("master document[[scope]]");
311 case FindAndReplaceOptions::S_OPEN_BUFFERS:
312 scope = _("open files[[scope]]");
314 case FindAndReplaceOptions::S_ALL_MANUALS:
315 scope = _("manuals[[scope]]");
318 docstring message = opt.forward ?
319 bformat(_("End of %1$s reached while searching forward.\n"
320 "Continue searching from the beginning?"),
322 bformat(_("Beginning of %1$s reached while searching backward.\n"
323 "Continue searching from the end?"),
330 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt)
332 int wrap_answer = -1;
335 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
336 BufferView * bv = view_.documentBufferView();
337 Buffer * buf = &bv->buffer();
339 Buffer * buf_orig = &bv->buffer();
340 DocIterator cur_orig(bv->cursor());
342 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
343 vector<string> const & v = allManualsFiles();
344 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
345 FileName const & fname = FileName(*v.begin());
346 if (!theBufferList().exists(fname)) {
347 guiApp->currentView()->setBusy(false);
348 guiApp->currentView()->loadDocument(fname, false);
349 guiApp->currentView()->setBusy(true);
351 buf = theBufferList().getBuffer(fname);
352 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
353 buf->absFileName()));
354 bv = view_.documentBufferView();
355 bv->cursor().clear();
356 bv->cursor().push_back(CursorSlice(buf->inset()));
361 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
363 LYXERR(Debug::FIND, "dispatched");
364 if (bv->cursor().result().dispatched()) {
365 // Match found, selected and replaced if needed
369 // No match found in current buffer:
370 // select next buffer in scope, if any
371 bool prompt = next_prev_buffer(buf, opt);
373 if (wrap_answer != -1)
375 docstring q = question_string(opt);
376 wrap_answer = frontend::Alert::prompt(
377 _("Wrap search?"), q,
378 0, 1, _("&Yes"), _("&No"));
379 if (wrap_answer == 1)
382 if (buf != &view_.documentBufferView()->buffer())
383 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
384 buf->absFileName()));
385 bv = view_.documentBufferView();
387 bv->cursor().clear();
388 bv->cursor().push_back(CursorSlice(buf->inset()));
390 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
391 bv->cursor().setCursor(doc_iterator_end(buf));
392 bv->cursor().backwardPos();
393 LYXERR(Debug::FIND, "findBackAdv5: cur: "
396 bv->clearSelection();
397 } while (wrap_answer != 1);
398 if (buf_orig != &view_.documentBufferView()->buffer())
399 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
400 buf_orig->absFileName()));
401 bv = view_.documentBufferView();
402 bv->cursor().setCursor(cur_orig);
406 void FindAndReplaceWidget::findAndReplace(
407 bool casesensitive, bool matchword, bool backwards,
408 bool expandmacros, bool ignoreformat, bool replace,
411 Buffer & buffer = find_work_area_->bufferView().buffer();
412 docstring searchString;
414 searchString = buffer_to_latex(buffer);
416 ParIterator it = buffer.par_iterator_begin();
417 ParIterator end = buffer.par_iterator_end();
418 OutputParams runparams(&buffer.params().encoding());
420 runparams.nice = true;
421 runparams.flavor = OutputParams::LATEX;
422 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
423 runparams.dryrun = true;
424 for (; it != end; ++it) {
425 LYXERR(Debug::FIND, "Adding to search string: '"
426 << it->asString(false)
429 it->stringify(pos_type(0), it->size(),
430 AS_STR_INSETS, runparams);
433 if (to_utf8(searchString).empty()) {
434 buffer.message(_("Nothing to search"));
438 to_utf8(searchString).find("\\regexp") != std::string::npos;
439 docstring replaceString;
441 Buffer & repl_buffer =
442 replace_work_area_->bufferView().buffer();
444 repl_buffer.write(oss);
445 //buffer_to_latex(replace_buffer);
446 replaceString = from_utf8(oss.str());
448 replaceString = from_utf8(LYX_FR_NULL_STRING);
450 FindAndReplaceOptions::SearchScope scope =
451 FindAndReplaceOptions::S_BUFFER;
452 if (CurrentDocument->isChecked())
453 scope = FindAndReplaceOptions::S_BUFFER;
454 else if (MasterDocument->isChecked())
455 scope = FindAndReplaceOptions::S_DOCUMENT;
456 else if (OpenDocuments->isChecked())
457 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
458 else if (AllManualsRB->isChecked())
459 scope = FindAndReplaceOptions::S_ALL_MANUALS;
461 LASSERT(false, /**/);
462 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
463 << "searchstring=" << searchString
464 << ", casesensitiv=" << casesensitive
465 << ", matchword=" << matchword
466 << ", backwards=" << backwards
467 << ", expandmacros=" << expandmacros
468 << ", ignoreformat=" << ignoreformat
469 << ", regexp=" << regexp
470 << ", replaceString" << replaceString
471 << ", keep_case=" << keep_case
472 << ", scope=" << scope);
473 FindAndReplaceOptions opt(searchString, casesensitive, matchword,
474 !backwards, expandmacros, ignoreformat,
475 regexp, replaceString, keep_case, scope);
477 findAndReplaceScope(opt);
478 view_.setBusy(false);
482 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
484 if (! view_.currentMainWorkArea()) {
485 view_.message(_("No open document(s) in which to search"));
488 // FIXME: create a Dialog::returnFocus()
489 // or something instead of this:
490 view_.setCurrentWorkArea(view_.currentMainWorkArea());
491 findAndReplace(caseCB->isChecked(),
492 wordsCB->isChecked(),
494 expandMacrosCB->isChecked(),
495 ignoreFormatCB->isChecked(),
497 keepCaseCB->isChecked());
501 void FindAndReplaceWidget::hideDialog()
503 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
507 void FindAndReplaceWidget::on_findNextPB_clicked()
509 findAndReplace(searchbackCB->isChecked(), false);
510 find_work_area_->setFocus();
514 void FindAndReplaceWidget::on_replacePB_clicked()
516 findAndReplace(searchbackCB->isChecked(), true);
517 replace_work_area_->setFocus();
521 void FindAndReplaceWidget::on_replaceallPB_clicked()
523 replace_work_area_->setFocus();
527 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
529 view_.setCurrentWorkArea(find_work_area_);
530 LYXERR(Debug::FIND, "Selecting entire find buffer");
531 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
532 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
533 find_work_area_->installEventFilter(this);
534 replace_work_area_->installEventFilter(this);
538 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
540 replace_work_area_->removeEventFilter(this);
541 find_work_area_->removeEventFilter(this);
542 this->QWidget::hideEvent(ev);
546 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
552 FindAndReplace::FindAndReplace(GuiView & parent,
553 Qt::DockWidgetArea area, Qt::WindowFlags flags)
554 : DockView(parent, "Find LyX", qt_("Advanced Find and Replace"),
557 widget_ = new FindAndReplaceWidget(parent);
559 setFocusProxy(widget_);
563 FindAndReplace::~FindAndReplace()
570 bool FindAndReplace::initialiseParams(std::string const & params)
572 return widget_->initialiseParams(params);
576 Dialog * createGuiSearchAdv(GuiView & lv)
578 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
580 // On Mac show and floating
581 gui->setFloating(true);
587 } // namespace frontend
591 #include "moc_FindAndReplace.cpp"