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)
319 int wrap_answer = -1;
322 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
323 BufferView * bv = view_.documentBufferView();
324 Buffer * buf = &bv->buffer();
326 Buffer * buf_orig = &bv->buffer();
327 DocIterator cur_orig(bv->cursor());
329 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
330 vector<string> const & v = allManualsFiles();
331 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
332 FileName const & fname = FileName(*v.begin());
333 if (!theBufferList().exists(fname)) {
334 guiApp->currentView()->setBusy(false);
335 guiApp->currentView()->loadDocument(fname, false);
336 guiApp->currentView()->setBusy(true);
338 buf = theBufferList().getBuffer(fname);
339 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
340 buf->absFileName()));
341 bv = view_.documentBufferView();
342 bv->cursor().clear();
343 bv->cursor().push_back(CursorSlice(buf->inset()));
348 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
350 LYXERR(Debug::FIND, "dispatched");
351 if (bv->cursor().result().dispatched()) {
352 // New match found and selected (old selection replaced if needed)
353 view_.setBusy(false);
357 // No match found in current buffer (however old selection might have been replaced)
358 // select next buffer in scope, if any
359 bool prompt = nextPrevBuffer(buf, opt);
361 if (wrap_answer != -1)
363 docstring q = getQuestionString(opt);
364 view_.setBusy(false);
365 wrap_answer = frontend::Alert::prompt(
366 _("Wrap search?"), q,
367 0, 1, _("&Yes"), _("&No"));
369 if (wrap_answer == 1)
372 if (buf != &view_.documentBufferView()->buffer())
373 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
374 buf->absFileName()));
375 bv = view_.documentBufferView();
377 bv->cursor().clear();
378 bv->cursor().push_back(CursorSlice(buf->inset()));
380 //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
381 bv->cursor().setCursor(doc_iterator_end(buf));
382 bv->cursor().backwardPos();
383 LYXERR(Debug::FIND, "findBackAdv5: cur: "
386 bv->clearSelection();
387 } while (wrap_answer != 1);
388 if (buf_orig != &view_.documentBufferView()->buffer())
389 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
390 buf_orig->absFileName()));
391 bv = view_.documentBufferView();
392 // This may happen after a replace occurred
393 if (cur_orig.pos() > cur_orig.lastpos())
394 cur_orig.pos() = cur_orig.lastpos();
395 bv->cursor().setCursor(cur_orig);
396 view_.setBusy(false);
400 void FindAndReplaceWidget::findAndReplace(
401 bool casesensitive, bool matchword, bool backwards,
402 bool expandmacros, bool ignoreformat, bool replace,
405 Buffer & buffer = find_work_area_->bufferView().buffer();
406 docstring searchString;
408 searchString = buffer_to_latex(buffer);
410 ParIterator it = buffer.par_iterator_begin();
411 ParIterator end = buffer.par_iterator_end();
412 OutputParams runparams(&buffer.params().encoding());
414 runparams.nice = true;
415 runparams.flavor = OutputParams::LATEX;
416 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
417 runparams.dryrun = true;
418 for (; it != end; ++it) {
419 LYXERR(Debug::FIND, "Adding to search string: '"
420 << it->asString(false)
423 it->stringify(pos_type(0), it->size(),
424 AS_STR_INSETS, runparams);
427 if (to_utf8(searchString).empty()) {
428 buffer.message(_("Nothing to search"));
432 to_utf8(searchString).find("\\regexp") != std::string::npos;
433 docstring replaceString;
435 Buffer & repl_buffer =
436 replace_work_area_->bufferView().buffer();
438 repl_buffer.write(oss);
439 //buffer_to_latex(replace_buffer);
440 replaceString = from_utf8(oss.str());
442 replaceString = from_utf8(LYX_FR_NULL_STRING);
444 FindAndReplaceOptions::SearchScope scope =
445 FindAndReplaceOptions::S_BUFFER;
446 if (CurrentDocument->isChecked())
447 scope = FindAndReplaceOptions::S_BUFFER;
448 else if (MasterDocument->isChecked())
449 scope = FindAndReplaceOptions::S_DOCUMENT;
450 else if (OpenDocuments->isChecked())
451 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
452 else if (AllManualsRB->isChecked())
453 scope = FindAndReplaceOptions::S_ALL_MANUALS;
455 LASSERT(false, /**/);
456 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
457 << "searchstring=" << searchString
458 << ", casesensitiv=" << casesensitive
459 << ", matchword=" << matchword
460 << ", backwards=" << backwards
461 << ", expandmacros=" << expandmacros
462 << ", ignoreformat=" << ignoreformat
463 << ", regexp=" << regexp
464 << ", replaceString" << replaceString
465 << ", keep_case=" << keep_case
466 << ", scope=" << scope);
467 FindAndReplaceOptions opt(searchString, casesensitive, matchword,
468 !backwards, expandmacros, ignoreformat,
469 regexp, replaceString, keep_case, scope);
470 findAndReplaceScope(opt);
474 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
476 if (! view_.currentMainWorkArea()) {
477 view_.message(_("No open document(s) in which to search"));
480 // Finalize macros that are being typed, both in main document and in search or replacement WAs
481 if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
482 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
483 if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
484 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
486 // FIXME: create a Dialog::returnFocus()
487 // or something instead of this:
488 view_.setCurrentWorkArea(view_.currentMainWorkArea());
489 findAndReplace(caseCB->isChecked(),
490 wordsCB->isChecked(),
492 expandMacrosCB->isChecked(),
493 ignoreFormatCB->isChecked(),
495 keepCaseCB->isChecked());
499 void FindAndReplaceWidget::hideDialog()
501 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
505 void FindAndReplaceWidget::on_findNextPB_clicked()
507 findAndReplace(searchbackCB->isChecked(), false);
508 find_work_area_->setFocus();
512 void FindAndReplaceWidget::on_replacePB_clicked()
514 findAndReplace(searchbackCB->isChecked(), true);
515 replace_work_area_->setFocus();
519 void FindAndReplaceWidget::on_replaceallPB_clicked()
521 replace_work_area_->setFocus();
525 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
527 Buffer & doc_buf = view_.documentBufferView()->buffer();
528 BufferParams & doc_bp = doc_buf.params();
529 Buffer & find_buf = find_work_area_->bufferView().buffer();
530 LYXERR(Debug::FIND, "Applying document params to find buffer");
531 ApplyParams(find_buf, doc_bp);
532 Buffer & replace_buf = replace_work_area_->bufferView().buffer();
533 LYXERR(Debug::FIND, "Applying document params to replace buffer");
534 ApplyParams(replace_buf, doc_bp);
536 string lang = doc_bp.language->lang();
537 LYXERR(Debug::FIND, "Setting current editing language to " << lang << endl);
538 FuncRequest cmd(LFUN_LANGUAGE, lang);
539 find_buf.text().dispatch(find_work_area_->bufferView().cursor(), cmd);
540 replace_buf.text().dispatch(replace_work_area_->bufferView().cursor(), cmd);
542 view_.setCurrentWorkArea(find_work_area_);
543 LYXERR(Debug::FIND, "Selecting entire find buffer");
544 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
545 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
546 find_work_area_->installEventFilter(this);
547 replace_work_area_->installEventFilter(this);
551 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
553 replace_work_area_->removeEventFilter(this);
554 find_work_area_->removeEventFilter(this);
555 this->QWidget::hideEvent(ev);
559 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
565 FindAndReplace::FindAndReplace(GuiView & parent,
566 Qt::DockWidgetArea area, Qt::WindowFlags flags)
567 : DockView(parent, "Find LyX", qt_("Advanced Find and Replace"),
570 widget_ = new FindAndReplaceWidget(parent);
572 setFocusProxy(widget_);
576 FindAndReplace::~FindAndReplace()
583 bool FindAndReplace::initialiseParams(std::string const & params)
585 return widget_->initialiseParams(params);
589 Dialog * createGuiSearchAdv(GuiView & lv)
591 FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
593 // On Mac show and floating
594 gui->setFloating(true);
600 } // namespace frontend
604 #include "moc_FindAndReplace.cpp"