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"
38 #include <QCloseEvent>
44 using namespace lyx::support;
50 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
54 #if QT_VERSION < 0x040400
55 scrollArea->setWidget(scrollAreaWidgetContents);
57 find_work_area_->setGuiView(view_);
58 find_work_area_->init();
59 setFocusProxy(find_work_area_);
60 replace_work_area_->setGuiView(view_);
61 replace_work_area_->init();
62 // We don't want two cursors blinking.
63 replace_work_area_->stopBlinkingCursor();
67 bool FindAndReplaceWidget::eventFilter(QObject *obj, QEvent *event)
69 if (obj == find_work_area_ && event->type() == QEvent::KeyPress) {
70 QKeyEvent *e = static_cast<QKeyEvent *> (event);
71 if (e->key() == Qt::Key_Escape && e->modifiers() == Qt::NoModifier) {
74 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
75 if (e->modifiers() == Qt::ShiftModifier) {
76 on_findPrevPB_clicked();
78 } else if (e->modifiers() == Qt::NoModifier) {
79 on_findNextPB_clicked();
82 } else if (e->key() == Qt::Key_Tab && e->modifiers() == Qt::NoModifier) {
83 LYXERR(Debug::FIND, "Focusing replace WA");
84 replace_work_area_->setFocus();
88 if (obj == replace_work_area_ && event->type() == QEvent::KeyPress) {
89 QKeyEvent *e = static_cast<QKeyEvent *> (event);
90 if (e->key() == Qt::Key_Escape && e->modifiers() == Qt::NoModifier) {
93 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
94 if (e->modifiers() == Qt::ShiftModifier) {
95 on_replacePrevPB_clicked();
97 } else if (e->modifiers() == Qt::NoModifier) {
98 on_replaceNextPB_clicked();
101 } else if (e->key() == Qt::Key_Backtab) {
102 LYXERR(Debug::FIND, "Focusing find WA");
103 find_work_area_->setFocus();
107 // standard event processing
108 return QWidget::eventFilter(obj, event);
111 static docstring buffer_to_latex(Buffer & buffer) {
112 OutputParams runparams(&buffer.params().encoding());
114 runparams.nice = true;
115 runparams.flavor = OutputParams::LATEX;
116 runparams.linelen = 80; //lyxrc.plaintext_linelen;
117 // No side effect of file copying and image conversion
118 runparams.dryrun = true;
119 buffer.texrow().reset();
120 ParagraphList::const_iterator pit = buffer.paragraphs().begin();
121 ParagraphList::const_iterator const end = buffer.paragraphs().end();
122 for (; pit != end; ++pit) {
123 TeXOnePar(buffer, buffer.text(), pit, os, buffer.texrow(), runparams);
124 LYXERR(Debug::FIND, "searchString up to here: " << os.str());
130 static vector<string> const & allManualsFiles() {
131 static vector<string> v;
132 static const char * files[] = {
133 "Intro", "UserGuide", "Tutorial", "Additional", "EmbeddedObjects",
134 "Math", "Customization", "Shortcuts", "LFUNs", "LaTeXConfig"
138 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
139 fname = i18nLibFileSearch("doc", files[i], "lyx");
140 v.push_back(fname.absFilename());
147 /** Switch p_buf to point to next document buffer.
149 ** Return true if restarted from master-document buffer.
152 ** Not using p_buf->allRelatives() here, because I'm not sure
153 ** whether or not the returned order is independent of p_buf.
155 static bool next_document_buffer(Buffer * & p_buf) {
156 Buffer *p_master = p_buf;
160 p_master = const_cast<Buffer *>(p_master->masterBuffer());
161 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
162 } while (p_master != p_old);
163 LASSERT(p_master != NULL, /**/);
164 vector<Buffer *> v_children;
165 /* Root master added as first buffer in the vector */
166 v_children.push_back(p_master);
167 p_master->getChildren(v_children, true);
168 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
169 vector<Buffer *>::const_iterator it = find(v_children.begin(), v_children.end(), p_buf);
170 LASSERT(it != v_children.end(), /**/)
172 if (it == v_children.end()) {
173 p_buf = *v_children.begin();
181 /** Switch p_buf to point to previous document buffer.
183 ** Return true if restarted from last child buffer.
186 ** Not using p_buf->allRelatives() here, because I'm not sure
187 ** whether or not the returned order is independent of p_buf.
189 static bool prev_document_buffer(Buffer * & p_buf) {
190 Buffer *p_master = p_buf;
194 p_master = const_cast<Buffer *>(p_master->masterBuffer());
195 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
196 } while (p_master != p_old);
197 LASSERT(p_master != NULL, /**/);
198 vector<Buffer *> v_children;
199 /* Root master added as first buffer in the vector */
200 v_children.push_back(p_master);
201 p_master->getChildren(v_children, true);
202 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
203 vector<Buffer *>::const_iterator it = find(v_children.begin(), v_children.end(), p_buf);
204 LASSERT(it != v_children.end(), /**/)
205 if (it == v_children.begin()) {
206 it = v_children.end();
217 /** Switch buf to point to next or previous buffer in search scope.
219 ** Return true if restarted from scratch.
221 static bool next_prev_buffer(Buffer * & buf, FindAndReplaceOptions const & opt) {
222 bool restarted = false;
224 case FindAndReplaceOptions::S_BUFFER:
227 case FindAndReplaceOptions::S_DOCUMENT:
229 restarted = next_document_buffer(buf);
231 restarted = prev_document_buffer(buf);
233 case FindAndReplaceOptions::S_OPEN_BUFFERS:
235 buf = theBufferList().next(buf);
236 restarted = buf == *theBufferList().begin();
238 buf = theBufferList().previous(buf);
239 restarted = buf == *(theBufferList().end() - 1);
242 case FindAndReplaceOptions::S_ALL_MANUALS:
243 vector<string> const & v = allManualsFiles();
244 vector<string>::const_iterator it = find(v.begin(), v.end(), buf->absFileName());
247 } else if (opt.forward) {
254 if (it == v.begin()) {
260 FileName const & fname = FileName(*it);
261 if (!theBufferList().exists(fname))
262 guiApp->currentView()->loadDocument(fname, false);
263 buf = theBufferList().getBuffer(fname);
270 /** Find the finest question message to post to the user */
271 docstring question_string(FindAndReplaceOptions const & opt)
273 docstring cur_pos = opt.forward ? _("End") : _("Begin");
274 docstring new_pos = opt.forward ? _("begin") : _("end");
277 case FindAndReplaceOptions::S_BUFFER:
280 case FindAndReplaceOptions::S_DOCUMENT:
281 scope = _("master document");
283 case FindAndReplaceOptions::S_OPEN_BUFFERS:
284 scope = _("open files");
286 case FindAndReplaceOptions::S_ALL_MANUALS:
287 scope = _("manuals");
290 docstring dir = opt.forward ? _("forward") : _("backwards");
291 return cur_pos + _(" of ") + scope
292 + _(" reached while searching ") + dir + ".\n"
294 + _("Continue searching from ") + new_pos + " ?";
298 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
299 int wrap_answer = -1;
302 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
303 BufferView * bv = view_.documentBufferView();
304 Buffer * buf = &bv->buffer();
306 Buffer * buf_orig = &bv->buffer();
307 Cursor cur_orig(bv->cursor());
309 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
310 vector<string> const & v = allManualsFiles();
311 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
312 FileName const & fname = FileName(*v.begin());
313 if (!theBufferList().exists(fname))
314 guiApp->currentView()->loadDocument(fname, false);
315 buf = theBufferList().getBuffer(fname);
316 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
317 buf->absFileName()));
318 bv = view_.documentBufferView();
319 bv->cursor().clear();
320 bv->cursor().push_back(CursorSlice(buf->inset()));
325 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
327 if (bv->cursor().result().dispatched()) {
328 // Match found, selected and replaced if needed
332 // No match found in current buffer: select next buffer in scope, if any
333 bool prompt = next_prev_buffer(buf, opt);
335 if (wrap_answer != -1)
337 docstring q = question_string(opt);
338 wrap_answer = frontend::Alert::prompt(
339 _("Wrap search?"), q,
340 0, 1, _("&Yes"), _("&No"));
341 if (wrap_answer == 1)
344 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
345 buf->absFileName()));
346 bv = view_.documentBufferView();
348 bv->cursor().clear();
349 bv->cursor().push_back(CursorSlice(buf->inset()));
351 lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
352 bv->cursor().setCursor(doc_iterator_end(buf));
353 bv->cursor().backwardPos();
354 LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
356 bv->clearSelection();
357 } while (wrap_answer != 1);
358 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
359 buf_orig->absFileName()));
360 bv = view_.documentBufferView();
361 bv->cursor() = cur_orig;
365 void FindAndReplaceWidget::findAndReplace(
366 bool casesensitive, bool matchword, bool backwards,
367 bool expandmacros, bool ignoreformat, bool replace,
370 Buffer & buffer = find_work_area_->bufferView().buffer();
371 docstring searchString;
373 searchString = buffer_to_latex(buffer);
375 ParIterator it = buffer.par_iterator_begin();
376 ParIterator end = buffer.par_iterator_end();
377 OutputParams runparams(&buffer.params().encoding());
379 runparams.nice = true;
380 runparams.flavor = OutputParams::LATEX;
381 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
382 runparams.dryrun = true;
383 for (; it != end; ++it) {
384 LYXERR(Debug::FIND, "Adding to search string: '" << it->asString(false) << "'");
385 searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
388 if (to_utf8(searchString).empty()) {
389 buffer.message(_("Nothing to search"));
392 bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
393 docstring replaceString;
395 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
397 repl_buffer.write(oss);
398 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
400 replaceString = from_utf8(LYX_FR_NULL_STRING);
402 FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
403 if (CurrentDocument->isChecked())
404 scope = FindAndReplaceOptions::S_BUFFER;
405 else if (MasterDocument->isChecked())
406 scope = FindAndReplaceOptions::S_DOCUMENT;
407 else if (OpenDocuments->isChecked())
408 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
409 else if (AllManualsRB->isChecked())
410 scope = FindAndReplaceOptions::S_ALL_MANUALS;
412 LASSERT(false, /**/);
413 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
414 << "searchstring=" << searchString
415 << ", casesensitiv=" << casesensitive
416 << ", matchword=" << matchword
417 << ", backwards=" << backwards
418 << ", expandmacros=" << expandmacros
419 << ", ignoreformat=" << ignoreformat
420 << ", regexp=" << regexp
421 << ", replaceString" << replaceString
422 << ", keep_case=" << keep_case
423 << ", scope=" << scope);
424 FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
425 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
426 findAndReplaceScope(opt);
430 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
432 if (! view_.currentMainWorkArea()) {
433 view_.message(_("No open document(s) in which to search"));
436 // FIXME: create a Dialog::returnFocus() or something instead of this:
437 view_.setCurrentWorkArea(view_.currentMainWorkArea());
438 findAndReplace(caseCB->isChecked(),
439 wordsCB->isChecked(),
441 expandMacrosCB->isChecked(),
442 ignoreFormatCB->isChecked(),
444 keepCaseCB->isChecked());
448 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
450 static char const * regexps[] = {
451 ".*", ".+", "[a-z]+", "[0-9]+", ""
453 LYXERR(Debug::FIND, "Index: " << index);
454 if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
455 find_work_area_->setFocus();
456 Cursor & cur = find_work_area_->bufferView().cursor();
457 if (! cur.inRegexped())
458 dispatch(FuncRequest(LFUN_REGEXP_MODE));
459 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
460 regexpInsertCombo->setCurrentIndex(0);
465 void FindAndReplaceWidget::on_closePB_clicked()
467 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
471 void FindAndReplaceWidget::on_findNextPB_clicked() {
472 findAndReplace(false, false);
473 find_work_area_->setFocus();
477 void FindAndReplaceWidget::on_findPrevPB_clicked() {
478 findAndReplace(true, false);
479 find_work_area_->setFocus();
483 void FindAndReplaceWidget::on_replaceNextPB_clicked()
485 findAndReplace(false, true);
486 replace_work_area_->setFocus();
490 void FindAndReplaceWidget::on_replacePrevPB_clicked()
492 findAndReplace(true, true);
493 replace_work_area_->setFocus();
497 void FindAndReplaceWidget::on_replaceallPB_clicked()
499 replace_work_area_->setFocus();
503 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
505 view_.setCurrentWorkArea(find_work_area_);
506 LYXERR(Debug::FIND, "Selecting entire find buffer");
507 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
508 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
509 find_work_area_->installEventFilter(this);
510 replace_work_area_->installEventFilter(this);
514 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
516 replace_work_area_->removeEventFilter(this);
517 find_work_area_->removeEventFilter(this);
518 this->QWidget::hideEvent(ev);
522 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
528 FindAndReplace::FindAndReplace(GuiView & parent,
529 Qt::DockWidgetArea area, Qt::WindowFlags flags)
530 : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
532 widget_ = new FindAndReplaceWidget(parent);
534 setFocusProxy(widget_);
538 FindAndReplace::~FindAndReplace()
545 bool FindAndReplace::initialiseParams(std::string const & params)
547 return widget_->initialiseParams(params);
551 Dialog * createGuiSearchAdv(GuiView & lv)
553 return new FindAndReplace(lv, Qt::RightDockWidgetArea);
557 } // namespace frontend
561 #include "moc_FindAndReplace.cpp"