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"
16 #include "qt_helpers.h"
18 #include "GuiWorkArea.h"
20 #include "buffer_funcs.h"
21 #include "BufferParams.h"
22 #include "BufferList.h"
24 #include "FuncRequest.h"
26 #include "OutputParams.h"
27 #include "output_latex.h"
31 #include "support/debug.h"
32 #include "support/FileName.h"
33 #include "support/gettext.h"
34 #include "support/lassert.h"
35 #include "support/filetools.h"
37 #include <QCloseEvent>
43 using namespace lyx::support;
49 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
53 #if QT_VERSION < 0x040400
54 scrollArea->setWidget(scrollAreaWidgetContents);
56 find_work_area_->setGuiView(view_);
57 find_work_area_->init();
58 setFocusProxy(find_work_area_);
59 replace_work_area_->setGuiView(view_);
60 replace_work_area_->init();
61 // We don't want two cursors blinking.
62 replace_work_area_->stopBlinkingCursor();
66 bool FindAndReplaceWidget::eventFilter(QObject *obj, QEvent *event)
68 if (obj == find_work_area_ && event->type() == QEvent::KeyPress) {
69 QKeyEvent *e = static_cast<QKeyEvent *> (event);
70 if (e->key() == Qt::Key_Escape && e->modifiers() == Qt::NoModifier) {
73 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
74 if (e->modifiers() == Qt::ShiftModifier) {
75 on_findPrevPB_clicked();
77 } else if (e->modifiers() == Qt::NoModifier) {
78 on_findNextPB_clicked();
81 } else if (e->key() == Qt::Key_Tab && e->modifiers() == Qt::NoModifier) {
82 LYXERR(Debug::FIND, "Focusing replace WA");
83 replace_work_area_->setFocus();
87 if (obj == replace_work_area_ && event->type() == QEvent::KeyPress) {
88 QKeyEvent *e = static_cast<QKeyEvent *> (event);
89 if (e->key() == Qt::Key_Escape && e->modifiers() == Qt::NoModifier) {
92 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
93 if (e->modifiers() == Qt::ShiftModifier) {
94 on_replacePrevPB_clicked();
96 } else if (e->modifiers() == Qt::NoModifier) {
97 on_replaceNextPB_clicked();
100 } else if (e->key() == Qt::Key_Backtab) {
101 LYXERR(Debug::FIND, "Focusing find WA");
102 find_work_area_->setFocus();
106 // standard event processing
107 return QWidget::eventFilter(obj, event);
110 static docstring buffer_to_latex(Buffer & buffer) {
111 OutputParams runparams(&buffer.params().encoding());
113 runparams.nice = true;
114 runparams.flavor = OutputParams::LATEX;
115 runparams.linelen = 80; //lyxrc.plaintext_linelen;
116 // No side effect of file copying and image conversion
117 runparams.dryrun = true;
118 buffer.texrow().reset();
119 ParagraphList::const_iterator pit = buffer.paragraphs().begin();
120 ParagraphList::const_iterator const end = buffer.paragraphs().end();
121 for (; pit != end; ++pit) {
122 TeXOnePar(buffer, buffer.text(), pit, os, buffer.texrow(), runparams);
123 LYXERR(Debug::FIND, "searchString up to here: " << os.str());
129 static vector<string> const & allManualsFiles() {
130 static vector<string> v;
131 static const char * files[] = {
132 "Intro", "UserGuide", "Tutorial", "Additional", "EmbeddedObjects",
133 "Math", "Customization", "Shortcuts", "LFUNs", "LaTeXConfig"
137 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
138 fname = i18nLibFileSearch("doc", files[i], "lyx");
139 v.push_back(fname.absFilename());
146 /** Switch p_buf to point to next document buffer.
148 ** Return true if restarted from master-document buffer.
151 ** Not using p_buf->allRelatives() here, because I'm not sure
152 ** whether or not the returned order is independent of p_buf.
154 static bool next_document_buffer(Buffer * & p_buf) {
155 Buffer *p_master = p_buf;
159 p_master = const_cast<Buffer *>(p_master->masterBuffer());
160 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
161 } while (p_master != p_old);
162 LASSERT(p_master != NULL, /**/);
163 vector<Buffer *> v_children;
164 /* Root master added as first buffer in the vector */
165 v_children.push_back(p_master);
166 p_master->getChildren(v_children, true);
167 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
168 vector<Buffer *>::const_iterator it = find(v_children.begin(), v_children.end(), p_buf);
169 LASSERT(it != v_children.end(), /**/)
171 if (it == v_children.end()) {
172 p_buf = *v_children.begin();
180 /** Switch p_buf to point to previous document buffer.
182 ** Return true if restarted from last child buffer.
185 ** Not using p_buf->allRelatives() here, because I'm not sure
186 ** whether or not the returned order is independent of p_buf.
188 static bool prev_document_buffer(Buffer * & p_buf) {
189 Buffer *p_master = p_buf;
193 p_master = const_cast<Buffer *>(p_master->masterBuffer());
194 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
195 } while (p_master != p_old);
196 LASSERT(p_master != NULL, /**/);
197 vector<Buffer *> v_children;
198 /* Root master added as first buffer in the vector */
199 v_children.push_back(p_master);
200 p_master->getChildren(v_children, true);
201 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
202 vector<Buffer *>::const_iterator it = find(v_children.begin(), v_children.end(), p_buf);
203 LASSERT(it != v_children.end(), /**/)
204 if (it == v_children.begin()) {
205 it = v_children.end();
216 /** Switch buf to point to next or previous buffer in search scope.
218 ** Return true if restarted from scratch.
220 static bool next_prev_buffer(Buffer * & buf, FindAndReplaceOptions const & opt) {
221 bool restarted = false;
223 case FindAndReplaceOptions::S_BUFFER:
226 case FindAndReplaceOptions::S_DOCUMENT:
228 restarted = next_document_buffer(buf);
230 restarted = prev_document_buffer(buf);
232 case FindAndReplaceOptions::S_OPEN_BUFFERS:
234 buf = theBufferList().next(buf);
235 restarted = buf == *theBufferList().begin();
237 buf = theBufferList().previous(buf);
238 restarted = buf == *(theBufferList().end() - 1);
241 case FindAndReplaceOptions::S_ALL_MANUALS:
242 vector<string> const & v = allManualsFiles();
243 vector<string>::const_iterator it = find(v.begin(), v.end(), buf->absFileName());
246 } else if (opt.forward) {
253 if (it == v.begin()) {
259 FileName const & fname = FileName(*it);
260 if (!theBufferList().exists(fname))
261 guiApp->currentView()->loadDocument(fname, false);
262 buf = theBufferList().getBuffer(fname);
269 /** Find the finest question message to post to the user */
270 docstring question_string(FindAndReplaceOptions const & opt)
272 docstring cur_pos = opt.forward ? _("End") : _("Begin");
273 docstring new_pos = opt.forward ? _("begin") : _("end");
276 case FindAndReplaceOptions::S_BUFFER:
279 case FindAndReplaceOptions::S_DOCUMENT:
280 scope = _("master document");
282 case FindAndReplaceOptions::S_OPEN_BUFFERS:
283 scope = _("open files");
285 case FindAndReplaceOptions::S_ALL_MANUALS:
286 scope = _("manuals");
289 docstring dir = opt.forward ? _("forward") : _("backwards");
290 return cur_pos + _(" of ") + scope
291 + _(" reached while searching ") + dir + ".\n"
293 + _("Continue searching from ") + new_pos + " ?";
297 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
298 int wrap_answer = -1;
301 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
302 BufferView * bv = view_.documentBufferView();
303 Buffer * buf = &bv->buffer();
305 Buffer * buf_orig = &bv->buffer();
306 Cursor cur_orig(bv->cursor());
308 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
309 vector<string> const & v = allManualsFiles();
310 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
311 FileName const & fname = FileName(*v.begin());
312 if (!theBufferList().exists(fname))
313 guiApp->currentView()->loadDocument(fname, false);
314 buf = theBufferList().getBuffer(fname);
315 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
316 buf->absFileName()));
317 bv = view_.documentBufferView();
318 bv->cursor().clear();
319 bv->cursor().push_back(CursorSlice(buf->inset()));
324 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
326 if (bv->cursor().result().dispatched()) {
327 // Match found, selected and replaced if needed
331 // No match found in current buffer: select next buffer in scope, if any
332 bool prompt = next_prev_buffer(buf, opt);
334 if (wrap_answer != -1)
336 docstring q = question_string(opt);
337 wrap_answer = frontend::Alert::prompt(
338 _("Wrap search?"), q,
339 0, 1, _("&Yes"), _("&No"));
340 if (wrap_answer == 1)
343 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
344 buf->absFileName()));
345 bv = view_.documentBufferView();
347 bv->cursor().clear();
348 bv->cursor().push_back(CursorSlice(buf->inset()));
350 lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
351 bv->cursor().setCursor(doc_iterator_end(buf));
352 bv->cursor().backwardPos();
353 LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
355 bv->clearSelection();
356 } while (wrap_answer != 1);
357 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
358 buf_orig->absFileName()));
359 bv = view_.documentBufferView();
360 bv->cursor() = cur_orig;
364 void FindAndReplaceWidget::findAndReplace(
365 bool casesensitive, bool matchword, bool backwards,
366 bool expandmacros, bool ignoreformat, bool replace,
369 Buffer & buffer = find_work_area_->bufferView().buffer();
370 docstring searchString;
372 searchString = buffer_to_latex(buffer);
374 ParIterator it = buffer.par_iterator_begin();
375 ParIterator end = buffer.par_iterator_end();
376 OutputParams runparams(&buffer.params().encoding());
378 runparams.nice = true;
379 runparams.flavor = OutputParams::LATEX;
380 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
381 runparams.dryrun = true;
382 for (; it != end; ++it) {
383 LYXERR(Debug::FIND, "Adding to search string: '" << it->asString(false) << "'");
384 searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
387 if (to_utf8(searchString).empty()) {
388 buffer.message(_("Nothing to search"));
391 bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
392 docstring replaceString;
394 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
396 repl_buffer.write(oss);
397 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
399 replaceString = from_utf8(LYX_FR_NULL_STRING);
401 FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
402 if (CurrentDocument->isChecked())
403 scope = FindAndReplaceOptions::S_BUFFER;
404 else if (MasterDocument->isChecked())
405 scope = FindAndReplaceOptions::S_DOCUMENT;
406 else if (OpenDocuments->isChecked())
407 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
408 else if (AllManualsRB->isChecked())
409 scope = FindAndReplaceOptions::S_ALL_MANUALS;
411 LASSERT(false, /**/);
412 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
413 << "searchstring=" << searchString
414 << ", casesensitiv=" << casesensitive
415 << ", matchword=" << matchword
416 << ", backwards=" << backwards
417 << ", expandmacros=" << expandmacros
418 << ", ignoreformat=" << ignoreformat
419 << ", regexp=" << regexp
420 << ", replaceString" << replaceString
421 << ", keep_case=" << keep_case
422 << ", scope=" << scope);
423 FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
424 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
425 findAndReplaceScope(opt);
429 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
431 if (! view_.currentMainWorkArea()) {
432 view_.message(_("No open document(s) in which to search"));
435 // FIXME: create a Dialog::returnFocus() or something instead of this:
436 view_.setCurrentWorkArea(view_.currentMainWorkArea());
437 findAndReplace(caseCB->isChecked(),
438 wordsCB->isChecked(),
440 expandMacrosCB->isChecked(),
441 ignoreFormatCB->isChecked(),
443 keepCaseCB->isChecked());
447 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
449 static char const * regexps[] = {
450 ".*", ".+", "[a-z]+", "[0-9]+", ""
452 LYXERR(Debug::FIND, "Index: " << index);
453 if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
454 find_work_area_->setFocus();
455 Cursor & cur = find_work_area_->bufferView().cursor();
456 if (! cur.inRegexped())
457 dispatch(FuncRequest(LFUN_REGEXP_MODE));
458 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
459 regexpInsertCombo->setCurrentIndex(0);
464 void FindAndReplaceWidget::on_closePB_clicked()
466 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
470 void FindAndReplaceWidget::on_findNextPB_clicked() {
471 findAndReplace(false, false);
472 find_work_area_->setFocus();
476 void FindAndReplaceWidget::on_findPrevPB_clicked() {
477 findAndReplace(true, false);
478 find_work_area_->setFocus();
482 void FindAndReplaceWidget::on_replaceNextPB_clicked()
484 findAndReplace(false, true);
485 replace_work_area_->setFocus();
489 void FindAndReplaceWidget::on_replacePrevPB_clicked()
491 findAndReplace(true, 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_("Find LyX Dialog"), area, flags)
531 widget_ = new FindAndReplaceWidget(parent);
533 setFocusProxy(widget_);
537 FindAndReplace::~FindAndReplace()
544 bool FindAndReplace::initialiseParams(std::string const & params)
546 return widget_->initialiseParams(params);
550 Dialog * createGuiSearchAdv(GuiView & lv)
552 return new FindAndReplace(lv, Qt::RightDockWidgetArea);
556 } // namespace frontend
560 #include "moc_FindAndReplace.cpp"