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()->setBusy(false);
263 guiApp->currentView()->loadDocument(fname, false);
264 guiApp->currentView()->setBusy(true);
266 buf = theBufferList().getBuffer(fname);
273 /** Find the finest question message to post to the user */
274 docstring question_string(FindAndReplaceOptions const & opt)
276 docstring cur_pos = opt.forward ? _("End") : _("Begin");
277 docstring new_pos = opt.forward ? _("begin") : _("end");
280 case FindAndReplaceOptions::S_BUFFER:
283 case FindAndReplaceOptions::S_DOCUMENT:
284 scope = _("master document");
286 case FindAndReplaceOptions::S_OPEN_BUFFERS:
287 scope = _("open files");
289 case FindAndReplaceOptions::S_ALL_MANUALS:
290 scope = _("manuals");
293 docstring dir = opt.forward ? _("forward") : _("backwards");
294 return cur_pos + _(" of ") + scope
295 + _(" reached while searching ") + dir + ".\n"
297 + _("Continue searching from ") + new_pos + " ?";
301 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
302 int wrap_answer = -1;
305 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
306 BufferView * bv = view_.documentBufferView();
307 Buffer * buf = &bv->buffer();
309 Buffer * buf_orig = &bv->buffer();
310 Cursor cur_orig(bv->cursor());
312 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
313 vector<string> const & v = allManualsFiles();
314 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
315 FileName const & fname = FileName(*v.begin());
316 if (!theBufferList().exists(fname)) {
317 guiApp->currentView()->setBusy(false);
318 guiApp->currentView()->loadDocument(fname, false);
319 guiApp->currentView()->setBusy(true);
321 buf = theBufferList().getBuffer(fname);
322 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
323 buf->absFileName()));
324 bv = view_.documentBufferView();
325 bv->cursor().clear();
326 bv->cursor().push_back(CursorSlice(buf->inset()));
331 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
333 if (bv->cursor().result().dispatched()) {
334 // Match found, selected and replaced if needed
338 // No match found in current buffer: select next buffer in scope, if any
339 bool prompt = next_prev_buffer(buf, opt);
341 if (wrap_answer != -1)
343 docstring q = question_string(opt);
344 wrap_answer = frontend::Alert::prompt(
345 _("Wrap search?"), q,
346 0, 1, _("&Yes"), _("&No"));
347 if (wrap_answer == 1)
350 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
351 buf->absFileName()));
352 bv = view_.documentBufferView();
354 bv->cursor().clear();
355 bv->cursor().push_back(CursorSlice(buf->inset()));
357 lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
358 bv->cursor().setCursor(doc_iterator_end(buf));
359 bv->cursor().backwardPos();
360 LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
362 bv->clearSelection();
363 } while (wrap_answer != 1);
364 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
365 buf_orig->absFileName()));
366 bv = view_.documentBufferView();
367 bv->cursor() = cur_orig;
371 void FindAndReplaceWidget::findAndReplace(
372 bool casesensitive, bool matchword, bool backwards,
373 bool expandmacros, bool ignoreformat, bool replace,
376 Buffer & buffer = find_work_area_->bufferView().buffer();
377 docstring searchString;
379 searchString = buffer_to_latex(buffer);
381 ParIterator it = buffer.par_iterator_begin();
382 ParIterator end = buffer.par_iterator_end();
383 OutputParams runparams(&buffer.params().encoding());
385 runparams.nice = true;
386 runparams.flavor = OutputParams::LATEX;
387 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
388 runparams.dryrun = true;
389 for (; it != end; ++it) {
390 LYXERR(Debug::FIND, "Adding to search string: '" << it->asString(false) << "'");
391 searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
394 if (to_utf8(searchString).empty()) {
395 buffer.message(_("Nothing to search"));
398 bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
399 docstring replaceString;
401 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
403 repl_buffer.write(oss);
404 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
406 replaceString = from_utf8(LYX_FR_NULL_STRING);
408 FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
409 if (CurrentDocument->isChecked())
410 scope = FindAndReplaceOptions::S_BUFFER;
411 else if (MasterDocument->isChecked())
412 scope = FindAndReplaceOptions::S_DOCUMENT;
413 else if (OpenDocuments->isChecked())
414 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
415 else if (AllManualsRB->isChecked())
416 scope = FindAndReplaceOptions::S_ALL_MANUALS;
418 LASSERT(false, /**/);
419 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
420 << "searchstring=" << searchString
421 << ", casesensitiv=" << casesensitive
422 << ", matchword=" << matchword
423 << ", backwards=" << backwards
424 << ", expandmacros=" << expandmacros
425 << ", ignoreformat=" << ignoreformat
426 << ", regexp=" << regexp
427 << ", replaceString" << replaceString
428 << ", keep_case=" << keep_case
429 << ", scope=" << scope);
430 FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
431 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
433 findAndReplaceScope(opt);
434 view_.setBusy(false);
438 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
440 if (! view_.currentMainWorkArea()) {
441 view_.message(_("No open document(s) in which to search"));
444 // FIXME: create a Dialog::returnFocus() or something instead of this:
445 view_.setCurrentWorkArea(view_.currentMainWorkArea());
446 findAndReplace(caseCB->isChecked(),
447 wordsCB->isChecked(),
449 expandMacrosCB->isChecked(),
450 ignoreFormatCB->isChecked(),
452 keepCaseCB->isChecked());
456 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
458 static char const * regexps[] = {
459 ".*", ".+", "[a-z]+", "[0-9]+", ""
461 LYXERR(Debug::FIND, "Index: " << index);
462 if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
463 find_work_area_->setFocus();
464 Cursor & cur = find_work_area_->bufferView().cursor();
465 if (! cur.inRegexped())
466 dispatch(FuncRequest(LFUN_REGEXP_MODE));
467 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
468 regexpInsertCombo->setCurrentIndex(0);
473 void FindAndReplaceWidget::on_closePB_clicked()
475 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
479 void FindAndReplaceWidget::on_findNextPB_clicked() {
480 findAndReplace(false, false);
481 find_work_area_->setFocus();
485 void FindAndReplaceWidget::on_findPrevPB_clicked() {
486 findAndReplace(true, false);
487 find_work_area_->setFocus();
491 void FindAndReplaceWidget::on_replaceNextPB_clicked()
493 findAndReplace(false, true);
494 replace_work_area_->setFocus();
498 void FindAndReplaceWidget::on_replacePrevPB_clicked()
500 findAndReplace(true, true);
501 replace_work_area_->setFocus();
505 void FindAndReplaceWidget::on_replaceallPB_clicked()
507 replace_work_area_->setFocus();
511 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
513 view_.setCurrentWorkArea(find_work_area_);
514 LYXERR(Debug::FIND, "Selecting entire find buffer");
515 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
516 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
517 find_work_area_->installEventFilter(this);
518 replace_work_area_->installEventFilter(this);
522 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
524 replace_work_area_->removeEventFilter(this);
525 find_work_area_->removeEventFilter(this);
526 this->QWidget::hideEvent(ev);
530 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
536 FindAndReplace::FindAndReplace(GuiView & parent,
537 Qt::DockWidgetArea area, Qt::WindowFlags flags)
538 : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
540 widget_ = new FindAndReplaceWidget(parent);
542 setFocusProxy(widget_);
546 FindAndReplace::~FindAndReplace()
553 bool FindAndReplace::initialiseParams(std::string const & params)
555 return widget_->initialiseParams(params);
559 Dialog * createGuiSearchAdv(GuiView & lv)
561 return new FindAndReplace(lv, Qt::RightDockWidgetArea);
565 } // namespace frontend
569 #include "moc_FindAndReplace.cpp"