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>
45 using namespace lyx::support;
51 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
55 #if QT_VERSION < 0x040400
56 scrollArea->setWidget(scrollAreaWidgetContents);
58 find_work_area_->setGuiView(view_);
59 find_work_area_->init();
60 setFocusProxy(find_work_area_);
61 replace_work_area_->setGuiView(view_);
62 replace_work_area_->init();
63 // We don't want two cursors blinking.
64 replace_work_area_->stopBlinkingCursor();
68 bool FindAndReplaceWidget::eventFilter(QObject *obj, QEvent *event)
70 if (obj == find_work_area_ && event->type() == QEvent::KeyPress) {
71 QKeyEvent *e = static_cast<QKeyEvent *> (event);
72 if (e->key() == Qt::Key_Escape && e->modifiers() == Qt::NoModifier) {
75 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
76 if (e->modifiers() == Qt::ShiftModifier) {
77 on_findPrevPB_clicked();
79 } else if (e->modifiers() == Qt::NoModifier) {
80 on_findNextPB_clicked();
83 } else if (e->key() == Qt::Key_Tab && e->modifiers() == Qt::NoModifier) {
84 LYXERR(Debug::FIND, "Focusing replace WA");
85 replace_work_area_->setFocus();
89 if (obj == replace_work_area_ && event->type() == QEvent::KeyPress) {
90 QKeyEvent *e = static_cast<QKeyEvent *> (event);
91 if (e->key() == Qt::Key_Escape && e->modifiers() == Qt::NoModifier) {
94 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
95 if (e->modifiers() == Qt::ShiftModifier) {
96 on_replacePrevPB_clicked();
98 } else if (e->modifiers() == Qt::NoModifier) {
99 on_replaceNextPB_clicked();
102 } else if (e->key() == Qt::Key_Backtab) {
103 LYXERR(Debug::FIND, "Focusing find WA");
104 find_work_area_->setFocus();
108 // standard event processing
109 return QWidget::eventFilter(obj, event);
112 static docstring buffer_to_latex(Buffer & buffer) {
113 OutputParams runparams(&buffer.params().encoding());
115 runparams.nice = true;
116 runparams.flavor = OutputParams::LATEX;
117 runparams.linelen = 80; //lyxrc.plaintext_linelen;
118 // No side effect of file copying and image conversion
119 runparams.dryrun = true;
120 buffer.texrow().reset();
121 ParagraphList::const_iterator pit = buffer.paragraphs().begin();
122 ParagraphList::const_iterator const end = buffer.paragraphs().end();
123 for (; pit != end; ++pit) {
124 TeXOnePar(buffer, buffer.text(), pit, os, buffer.texrow(), runparams);
125 LYXERR(Debug::FIND, "searchString up to here: " << os.str());
131 static vector<string> const & allManualsFiles() {
132 static vector<string> v;
133 static const char * files[] = {
134 "Intro", "UserGuide", "Tutorial", "Additional", "EmbeddedObjects",
135 "Math", "Customization", "Shortcuts", "LFUNs", "LaTeXConfig"
139 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
140 fname = i18nLibFileSearch("doc", files[i], "lyx");
141 v.push_back(fname.absFilename());
148 /** Switch p_buf to point to next document buffer.
150 ** Return true if restarted from master-document buffer.
153 ** Not using p_buf->allRelatives() here, because I'm not sure
154 ** whether or not the returned order is independent of p_buf.
156 static bool next_document_buffer(Buffer * & p_buf) {
157 Buffer *p_master = p_buf;
161 p_master = const_cast<Buffer *>(p_master->masterBuffer());
162 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
163 } while (p_master != p_old);
164 LASSERT(p_master != NULL, /**/);
165 vector<Buffer *> v_children;
166 /* Root master added as first buffer in the vector */
167 v_children.push_back(p_master);
168 p_master->getChildren(v_children, true);
169 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
170 vector<Buffer *>::const_iterator it = find(v_children.begin(), v_children.end(), p_buf);
171 LASSERT(it != v_children.end(), /**/)
173 if (it == v_children.end()) {
174 p_buf = *v_children.begin();
182 /** Switch p_buf to point to previous document buffer.
184 ** Return true if restarted from last child buffer.
187 ** Not using p_buf->allRelatives() here, because I'm not sure
188 ** whether or not the returned order is independent of p_buf.
190 static bool prev_document_buffer(Buffer * & p_buf) {
191 Buffer *p_master = p_buf;
195 p_master = const_cast<Buffer *>(p_master->masterBuffer());
196 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
197 } while (p_master != p_old);
198 LASSERT(p_master != NULL, /**/);
199 vector<Buffer *> v_children;
200 /* Root master added as first buffer in the vector */
201 v_children.push_back(p_master);
202 p_master->getChildren(v_children, true);
203 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
204 vector<Buffer *>::const_iterator it = find(v_children.begin(), v_children.end(), p_buf);
205 LASSERT(it != v_children.end(), /**/)
206 if (it == v_children.begin()) {
207 it = v_children.end();
218 /** Switch buf to point to next or previous buffer in search scope.
220 ** Return true if restarted from scratch.
222 static bool next_prev_buffer(Buffer * & buf, FindAndReplaceOptions const & opt) {
223 bool restarted = false;
225 case FindAndReplaceOptions::S_BUFFER:
228 case FindAndReplaceOptions::S_DOCUMENT:
230 restarted = next_document_buffer(buf);
232 restarted = prev_document_buffer(buf);
234 case FindAndReplaceOptions::S_OPEN_BUFFERS:
236 buf = theBufferList().next(buf);
237 restarted = buf == *theBufferList().begin();
239 buf = theBufferList().previous(buf);
240 restarted = buf == *(theBufferList().end() - 1);
243 case FindAndReplaceOptions::S_ALL_MANUALS:
244 vector<string> const & v = allManualsFiles();
245 vector<string>::const_iterator it = find(v.begin(), v.end(), buf->absFileName());
248 } else if (opt.forward) {
255 if (it == v.begin()) {
261 FileName const & fname = FileName(*it);
262 if (!theBufferList().exists(fname)) {
263 guiApp->currentView()->setBusy(false);
264 guiApp->currentView()->loadDocument(fname, false);
265 guiApp->currentView()->setBusy(true);
267 buf = theBufferList().getBuffer(fname);
274 /** Find the finest question message to post to the user */
275 docstring question_string(FindAndReplaceOptions const & opt)
279 case FindAndReplaceOptions::S_BUFFER:
280 scope = _("file[[scope]]");
282 case FindAndReplaceOptions::S_DOCUMENT:
283 scope = _("master document[[scope]]");
285 case FindAndReplaceOptions::S_OPEN_BUFFERS:
286 scope = _("open files[[scope]]");
288 case FindAndReplaceOptions::S_ALL_MANUALS:
289 scope = _("manuals[[scope]]");
292 docstring message = opt.forward ?
293 bformat(_("End of %1$s reached while searching forward.\n"
294 "Continue searching from begin?"),
296 bformat(_("Beginning of %1$s reached while searching backwards.\n"
297 "Continue searching from end?"),
304 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
305 int wrap_answer = -1;
308 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
309 BufferView * bv = view_.documentBufferView();
310 Buffer * buf = &bv->buffer();
312 Buffer * buf_orig = &bv->buffer();
313 Cursor cur_orig(bv->cursor());
315 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
316 vector<string> const & v = allManualsFiles();
317 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
318 FileName const & fname = FileName(*v.begin());
319 if (!theBufferList().exists(fname)) {
320 guiApp->currentView()->setBusy(false);
321 guiApp->currentView()->loadDocument(fname, false);
322 guiApp->currentView()->setBusy(true);
324 buf = theBufferList().getBuffer(fname);
325 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
326 buf->absFileName()));
327 bv = view_.documentBufferView();
328 bv->cursor().clear();
329 bv->cursor().push_back(CursorSlice(buf->inset()));
334 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
336 if (bv->cursor().result().dispatched()) {
337 // Match found, selected and replaced if needed
341 // No match found in current buffer: select next buffer in scope, if any
342 bool prompt = next_prev_buffer(buf, opt);
344 if (wrap_answer != -1)
346 docstring q = question_string(opt);
347 wrap_answer = frontend::Alert::prompt(
348 _("Wrap search?"), q,
349 0, 1, _("&Yes"), _("&No"));
350 if (wrap_answer == 1)
353 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
354 buf->absFileName()));
355 bv = view_.documentBufferView();
357 bv->cursor().clear();
358 bv->cursor().push_back(CursorSlice(buf->inset()));
360 lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
361 bv->cursor().setCursor(doc_iterator_end(buf));
362 bv->cursor().backwardPos();
363 LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
365 bv->clearSelection();
366 } while (wrap_answer != 1);
368 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
369 buf_orig->absFileName()));
370 bv = view_.documentBufferView();
371 bv->cursor() = 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: '" << it->asString(false) << "'");
395 searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
398 if (to_utf8(searchString).empty()) {
399 buffer.message(_("Nothing to search"));
402 bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
403 docstring replaceString;
405 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
407 repl_buffer.write(oss);
408 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
410 replaceString = from_utf8(LYX_FR_NULL_STRING);
412 FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
413 if (CurrentDocument->isChecked())
414 scope = FindAndReplaceOptions::S_BUFFER;
415 else if (MasterDocument->isChecked())
416 scope = FindAndReplaceOptions::S_DOCUMENT;
417 else if (OpenDocuments->isChecked())
418 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
419 else if (AllManualsRB->isChecked())
420 scope = FindAndReplaceOptions::S_ALL_MANUALS;
422 LASSERT(false, /**/);
423 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
424 << "searchstring=" << searchString
425 << ", casesensitiv=" << casesensitive
426 << ", matchword=" << matchword
427 << ", backwards=" << backwards
428 << ", expandmacros=" << expandmacros
429 << ", ignoreformat=" << ignoreformat
430 << ", regexp=" << regexp
431 << ", replaceString" << replaceString
432 << ", keep_case=" << keep_case
433 << ", scope=" << scope);
434 FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
435 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
437 findAndReplaceScope(opt);
438 view_.setBusy(false);
442 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
444 if (! view_.currentMainWorkArea()) {
445 view_.message(_("No open document(s) in which to search"));
448 // FIXME: create a Dialog::returnFocus() or something instead of this:
449 view_.setCurrentWorkArea(view_.currentMainWorkArea());
450 findAndReplace(caseCB->isChecked(),
451 wordsCB->isChecked(),
453 expandMacrosCB->isChecked(),
454 ignoreFormatCB->isChecked(),
456 keepCaseCB->isChecked());
460 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
462 static char const * regexps[] = {
463 ".*", ".+", "[a-z]+", "[0-9]+", ""
465 LYXERR(Debug::FIND, "Index: " << index);
466 if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
467 find_work_area_->setFocus();
468 Cursor & cur = find_work_area_->bufferView().cursor();
469 if (! cur.inRegexped())
470 dispatch(FuncRequest(LFUN_REGEXP_MODE));
471 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
472 regexpInsertCombo->setCurrentIndex(0);
477 void FindAndReplaceWidget::on_closePB_clicked()
479 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
483 void FindAndReplaceWidget::on_findNextPB_clicked() {
484 findAndReplace(false, false);
485 find_work_area_->setFocus();
489 void FindAndReplaceWidget::on_findPrevPB_clicked() {
490 findAndReplace(true, false);
491 find_work_area_->setFocus();
495 void FindAndReplaceWidget::on_replaceNextPB_clicked()
497 findAndReplace(false, true);
498 replace_work_area_->setFocus();
502 void FindAndReplaceWidget::on_replacePrevPB_clicked()
504 findAndReplace(true, true);
505 replace_work_area_->setFocus();
509 void FindAndReplaceWidget::on_replaceallPB_clicked()
511 replace_work_area_->setFocus();
515 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
517 view_.setCurrentWorkArea(find_work_area_);
518 LYXERR(Debug::FIND, "Selecting entire find buffer");
519 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
520 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
521 find_work_area_->installEventFilter(this);
522 replace_work_area_->installEventFilter(this);
526 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
528 replace_work_area_->removeEventFilter(this);
529 find_work_area_->removeEventFilter(this);
530 this->QWidget::hideEvent(ev);
534 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
540 FindAndReplace::FindAndReplace(GuiView & parent,
541 Qt::DockWidgetArea area, Qt::WindowFlags flags)
542 : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
544 widget_ = new FindAndReplaceWidget(parent);
546 setFocusProxy(widget_);
550 FindAndReplace::~FindAndReplace()
557 bool FindAndReplace::initialiseParams(std::string const & params)
559 return widget_->initialiseParams(params);
563 Dialog * createGuiSearchAdv(GuiView & lv)
565 return new FindAndReplace(lv, Qt::RightDockWidgetArea);
569 } // namespace frontend
573 #include "moc_FindAndReplace.cpp"