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)
277 docstring cur_pos = opt.forward ? _("End") : _("Begin");
278 docstring new_pos = opt.forward ? _("begin") : _("end");
281 case FindAndReplaceOptions::S_BUFFER:
284 case FindAndReplaceOptions::S_DOCUMENT:
285 scope = _("master document");
287 case FindAndReplaceOptions::S_OPEN_BUFFERS:
288 scope = _("open files");
290 case FindAndReplaceOptions::S_ALL_MANUALS:
291 scope = _("manuals");
294 docstring dir = opt.forward ? _("forward") : _("backwards");
296 return bformat(_("%1$s of %2$s reached while searching %3$s.\n\n"
297 "Continue searching from %4$s?"),
298 cur_pos, scope, dir, new_pos);
302 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
303 int wrap_answer = -1;
306 FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
307 BufferView * bv = view_.documentBufferView();
308 Buffer * buf = &bv->buffer();
310 Buffer * buf_orig = &bv->buffer();
311 Cursor cur_orig(bv->cursor());
313 if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
314 vector<string> const & v = allManualsFiles();
315 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
316 FileName const & fname = FileName(*v.begin());
317 if (!theBufferList().exists(fname)) {
318 guiApp->currentView()->setBusy(false);
319 guiApp->currentView()->loadDocument(fname, false);
320 guiApp->currentView()->setBusy(true);
322 buf = theBufferList().getBuffer(fname);
323 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
324 buf->absFileName()));
325 bv = view_.documentBufferView();
326 bv->cursor().clear();
327 bv->cursor().push_back(CursorSlice(buf->inset()));
332 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
334 if (bv->cursor().result().dispatched()) {
335 // Match found, selected and replaced if needed
339 // No match found in current buffer: select next buffer in scope, if any
340 bool prompt = next_prev_buffer(buf, opt);
342 if (wrap_answer != -1)
344 docstring q = question_string(opt);
345 wrap_answer = frontend::Alert::prompt(
346 _("Wrap search?"), q,
347 0, 1, _("&Yes"), _("&No"));
348 if (wrap_answer == 1)
351 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
352 buf->absFileName()));
353 bv = view_.documentBufferView();
355 bv->cursor().clear();
356 bv->cursor().push_back(CursorSlice(buf->inset()));
358 lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
359 bv->cursor().setCursor(doc_iterator_end(buf));
360 bv->cursor().backwardPos();
361 LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
363 bv->clearSelection();
364 } while (wrap_answer != 1);
366 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
367 buf_orig->absFileName()));
368 bv = view_.documentBufferView();
369 bv->cursor() = cur_orig;
373 void FindAndReplaceWidget::findAndReplace(
374 bool casesensitive, bool matchword, bool backwards,
375 bool expandmacros, bool ignoreformat, bool replace,
378 Buffer & buffer = find_work_area_->bufferView().buffer();
379 docstring searchString;
381 searchString = buffer_to_latex(buffer);
383 ParIterator it = buffer.par_iterator_begin();
384 ParIterator end = buffer.par_iterator_end();
385 OutputParams runparams(&buffer.params().encoding());
387 runparams.nice = true;
388 runparams.flavor = OutputParams::LATEX;
389 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
390 runparams.dryrun = true;
391 for (; it != end; ++it) {
392 LYXERR(Debug::FIND, "Adding to search string: '" << it->asString(false) << "'");
393 searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
396 if (to_utf8(searchString).empty()) {
397 buffer.message(_("Nothing to search"));
400 bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
401 docstring replaceString;
403 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
405 repl_buffer.write(oss);
406 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
408 replaceString = from_utf8(LYX_FR_NULL_STRING);
410 FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
411 if (CurrentDocument->isChecked())
412 scope = FindAndReplaceOptions::S_BUFFER;
413 else if (MasterDocument->isChecked())
414 scope = FindAndReplaceOptions::S_DOCUMENT;
415 else if (OpenDocuments->isChecked())
416 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
417 else if (AllManualsRB->isChecked())
418 scope = FindAndReplaceOptions::S_ALL_MANUALS;
420 LASSERT(false, /**/);
421 LYXERR(Debug::FIND, "FindAndReplaceOptions: "
422 << "searchstring=" << searchString
423 << ", casesensitiv=" << casesensitive
424 << ", matchword=" << matchword
425 << ", backwards=" << backwards
426 << ", expandmacros=" << expandmacros
427 << ", ignoreformat=" << ignoreformat
428 << ", regexp=" << regexp
429 << ", replaceString" << replaceString
430 << ", keep_case=" << keep_case
431 << ", scope=" << scope);
432 FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
433 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
435 findAndReplaceScope(opt);
436 view_.setBusy(false);
440 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
442 if (! view_.currentMainWorkArea()) {
443 view_.message(_("No open document(s) in which to search"));
446 // FIXME: create a Dialog::returnFocus() or something instead of this:
447 view_.setCurrentWorkArea(view_.currentMainWorkArea());
448 findAndReplace(caseCB->isChecked(),
449 wordsCB->isChecked(),
451 expandMacrosCB->isChecked(),
452 ignoreFormatCB->isChecked(),
454 keepCaseCB->isChecked());
458 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
460 static char const * regexps[] = {
461 ".*", ".+", "[a-z]+", "[0-9]+", ""
463 LYXERR(Debug::FIND, "Index: " << index);
464 if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
465 find_work_area_->setFocus();
466 Cursor & cur = find_work_area_->bufferView().cursor();
467 if (! cur.inRegexped())
468 dispatch(FuncRequest(LFUN_REGEXP_MODE));
469 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
470 regexpInsertCombo->setCurrentIndex(0);
475 void FindAndReplaceWidget::on_closePB_clicked()
477 dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
481 void FindAndReplaceWidget::on_findNextPB_clicked() {
482 findAndReplace(false, false);
483 find_work_area_->setFocus();
487 void FindAndReplaceWidget::on_findPrevPB_clicked() {
488 findAndReplace(true, false);
489 find_work_area_->setFocus();
493 void FindAndReplaceWidget::on_replaceNextPB_clicked()
495 findAndReplace(false, true);
496 replace_work_area_->setFocus();
500 void FindAndReplaceWidget::on_replacePrevPB_clicked()
502 findAndReplace(true, true);
503 replace_work_area_->setFocus();
507 void FindAndReplaceWidget::on_replaceallPB_clicked()
509 replace_work_area_->setFocus();
513 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
515 view_.setCurrentWorkArea(find_work_area_);
516 LYXERR(Debug::FIND, "Selecting entire find buffer");
517 dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
518 dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
519 find_work_area_->installEventFilter(this);
520 replace_work_area_->installEventFilter(this);
524 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
526 replace_work_area_->removeEventFilter(this);
527 find_work_area_->removeEventFilter(this);
528 this->QWidget::hideEvent(ev);
532 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
538 FindAndReplace::FindAndReplace(GuiView & parent,
539 Qt::DockWidgetArea area, Qt::WindowFlags flags)
540 : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
542 widget_ = new FindAndReplaceWidget(parent);
544 setFocusProxy(widget_);
548 FindAndReplace::~FindAndReplace()
555 bool FindAndReplace::initialiseParams(std::string const & params)
557 return widget_->initialiseParams(params);
561 Dialog * createGuiSearchAdv(GuiView & lv)
563 return new FindAndReplace(lv, Qt::RightDockWidgetArea);
567 } // namespace frontend
571 #include "moc_FindAndReplace.cpp"