]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
Fix bug #7106: iterator out of range while copying multi-row math.
[lyx.git] / src / frontends / qt4 / FindAndReplace.cpp
1 /**
2  * \file FindAndReplace.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Tommaso Cucinotta
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "FindAndReplace.h"
14
15 #include "Lexer.h"
16 #include "GuiApplication.h"
17 #include "GuiView.h"
18 #include "GuiWorkArea.h"
19 #include "qt_helpers.h"
20 #include "Language.h"
21
22 #include "buffer_funcs.h"
23 #include "BufferParams.h"
24 #include "BufferList.h"
25 #include "Cursor.h"
26 #include "FuncRequest.h"
27 #include "lyxfind.h"
28 #include "output_latex.h"
29 #include "OutputParams.h"
30 #include "TexRow.h"
31
32 #include "frontends/alert.h"
33
34 #include "support/debug.h"
35 #include "support/filetools.h"
36 #include "support/FileName.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
40
41 #include <QCloseEvent>
42 #include <QLineEdit>
43 #include <QMenu>
44
45 #include <iostream>
46
47 using namespace std;
48 using namespace lyx::support;
49
50 namespace lyx {
51 namespace frontend {
52
53
54 /// Apply to buf the parameters supplied through bp
55 static void ApplyParams(Buffer &buf, BufferParams const & bp) {
56         ostringstream ss;
57         ss << "\\begin_header\n";
58         bp.writeFile(ss);
59         ss << "\\end_header\n";
60         istringstream iss(ss.str());
61         Lexer lex;
62         lex.setStream(iss);
63         int unknown_tokens = buf.readHeader(lex);
64         LASSERT(unknown_tokens == 0, /* */);
65 }
66
67
68 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
69         :       view_(view)
70 {
71         setupUi(this);
72         find_work_area_->setGuiView(view_);
73         find_work_area_->init();
74         find_work_area_->setFrameStyle(QFrame::StyledPanel);
75
76         setFocusProxy(find_work_area_);
77         replace_work_area_->setGuiView(view_);
78         replace_work_area_->init();
79         replace_work_area_->setFrameStyle(QFrame::StyledPanel);
80
81         // We don't want two cursors blinking.
82         replace_work_area_->stopBlinkingCursor();
83 }
84
85
86 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
87 {
88         if (event->type() != QEvent::KeyPress
89                   || (obj != find_work_area_ && obj != replace_work_area_))
90                 return QWidget::eventFilter(obj, event);
91
92         QKeyEvent * e = static_cast<QKeyEvent *> (event);
93         switch (e->key()) {
94         case Qt::Key_Escape:
95                 if (e->modifiers() == Qt::NoModifier) {
96                         hideDialog();
97                         return true;
98                 }
99                 break;
100
101         case Qt::Key_Enter:
102         case Qt::Key_Return: {
103                 // with shift we (temporarily) change search/replace direction
104                 bool const searchback = searchbackCB->isChecked();
105                 if (e->modifiers() == Qt::ShiftModifier && !searchback)
106                         searchbackCB->setChecked(!searchback);
107
108                 if (obj == find_work_area_)
109                         on_findNextPB_clicked();
110                 else
111                         on_replacePB_clicked();
112                 // back to how it was
113                 searchbackCB->setChecked(searchback);
114                 return true;
115                 break;
116                 }
117         case Qt::Key_Tab:
118                 if (e->modifiers() == Qt::NoModifier) {
119                         if (obj == find_work_area_){
120                                 LYXERR(Debug::FIND, "Focusing replace WA");
121                                 replace_work_area_->setFocus();
122                                 return true;
123                         }
124                 }
125                 break;
126
127         case Qt::Key_Backtab:
128                 if (obj == replace_work_area_) {
129                         LYXERR(Debug::FIND, "Focusing find WA");
130                         find_work_area_->setFocus();
131                         return true;
132                 }
133                 break;
134
135         default:
136                 break;
137         }
138         // standard event processing
139         return QWidget::eventFilter(obj, event);
140 }
141
142
143 static docstring buffer_to_latex(Buffer & buffer) 
144 {
145         OutputParams runparams(&buffer.params().encoding());
146         odocstringstream os;
147         runparams.nice = true;
148         runparams.flavor = OutputParams::LATEX;
149         runparams.linelen = 80; //lyxrc.plaintext_linelen;
150         // No side effect of file copying and image conversion
151         runparams.dryrun = true;
152         buffer.texrow().reset();
153         pit_type const endpit = buffer.paragraphs().size();
154         for (pit_type pit = 0; pit != endpit; ++pit) {
155                 TeXOnePar(buffer, buffer.text(),
156                           pit, os, buffer.texrow(), runparams);
157                 LYXERR(Debug::FIND, "searchString up to here: "
158                         << os.str());
159         }
160         return os.str();
161 }
162
163
164 static vector<string> const & allManualsFiles() 
165 {
166         static vector<string> v;
167         static const char * files[] = {
168                 "Intro", "UserGuide", "Tutorial", "Additional",
169                 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
170                 "LFUNs", "LaTeXConfig"
171         };
172         if (v.empty()) {
173                 FileName fname;
174                 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
175                         fname = i18nLibFileSearch("doc", files[i], "lyx");
176                         v.push_back(fname.absFileName());
177                 }
178         }
179         return v;
180 }
181
182
183 /** Switch p_buf to point to next document buffer.
184  **
185  ** Return true if restarted from master-document buffer.
186  **/
187 static bool nextDocumentBuffer(Buffer * & buf) 
188 {
189         ListOfBuffers const children = buf->allRelatives();
190         LYXERR(Debug::FIND, "children.size()=" << children.size());
191         ListOfBuffers::const_iterator it =
192                 find(children.begin(), children.end(), buf);
193         LASSERT(it != children.end(), /**/)
194         ++it;
195         if (it == children.end()) {
196                 buf = *children.begin();
197                 return true;
198         }
199         buf = *it;
200         return false;
201 }
202
203
204 /** Switch p_buf to point to previous document buffer.
205  **
206  ** Return true if restarted from last child buffer.
207  **/
208 static bool prevDocumentBuffer(Buffer * & buf) 
209 {
210         ListOfBuffers const children = buf->allRelatives();
211         LYXERR(Debug::FIND, "children.size()=" << children.size());
212         ListOfBuffers::const_iterator it =
213                 find(children.begin(), children.end(), buf);
214         LASSERT(it != children.end(), /**/)
215         if (it == children.begin()) {
216                 it = children.end();
217                 --it;
218                 buf = *it;
219                 return true;
220         }
221         --it;
222         buf = *it;
223         return false;
224 }
225
226
227 /** Switch buf to point to next or previous buffer in search scope.
228  **
229  ** Return true if restarted from scratch.
230  **/
231 static bool nextPrevBuffer(Buffer * & buf,
232                              FindAndReplaceOptions const & opt)
233 {
234         bool restarted = false;
235         switch (opt.scope) {
236         case FindAndReplaceOptions::S_BUFFER:
237                 restarted = true;
238                 break;
239         case FindAndReplaceOptions::S_DOCUMENT:
240                 if (opt.forward)
241                         restarted = nextDocumentBuffer(buf);
242                 else
243                         restarted = prevDocumentBuffer(buf);
244                 break;
245         case FindAndReplaceOptions::S_OPEN_BUFFERS:
246                 if (opt.forward) {
247                         buf = theBufferList().next(buf);
248                         restarted = (buf == *theBufferList().begin());
249                 } else {
250                         buf = theBufferList().previous(buf);
251                         restarted = (buf == *(theBufferList().end() - 1));
252                 }
253                 break;
254         case FindAndReplaceOptions::S_ALL_MANUALS:
255                 vector<string> const & manuals = allManualsFiles();
256                 vector<string>::const_iterator it =
257                         find(manuals.begin(), manuals.end(), buf->absFileName());
258                 if (it == manuals.end())
259                         it = manuals.begin();
260                 else if (opt.forward) {
261                         ++it;
262                         if (it == manuals.end()) {
263                                 it = manuals.begin();
264                                 restarted = true;
265                         }
266                 } else {
267                         if (it == manuals.begin()) {
268                                 it = manuals.end();
269                                 restarted = true;
270                         }
271                         --it;
272                 }
273                 FileName const & fname = FileName(*it);
274                 if (!theBufferList().exists(fname)) {
275                         guiApp->currentView()->setBusy(false);
276                         guiApp->currentView()->loadDocument(fname, false);
277                         guiApp->currentView()->setBusy(true);
278                 }
279                 buf = theBufferList().getBuffer(fname);
280                 break;
281         }
282         return restarted;
283 }
284
285
286 /** Find the finest question message to post to the user */
287 docstring getQuestionString(FindAndReplaceOptions const & opt)
288 {
289         docstring scope;
290         switch (opt.scope) {
291         case FindAndReplaceOptions::S_BUFFER:
292                 scope = _("File");
293                 break;
294         case FindAndReplaceOptions::S_DOCUMENT:
295                 scope = _("Master document");
296                 break;
297         case FindAndReplaceOptions::S_OPEN_BUFFERS:
298                 scope = _("Open files");
299                 break;
300         case FindAndReplaceOptions::S_ALL_MANUALS:
301                 scope = _("Manuals");
302                 break;
303         }
304         docstring message = opt.forward ?
305                 bformat(_("%1$s: the end was reached while searching forward.\n"
306                           "Continue searching from the beginning?"),
307                         scope) : 
308                 bformat(_("%1$s: the beginning was reached while searching backward.\n"
309                           "Continue searching from the end?"),
310                         scope);
311
312         return message;
313 }
314
315
316 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt)
317 {
318         view_.setBusy(true);
319         int wrap_answer = -1;
320         ostringstream oss;
321         oss << opt;
322         FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
323         BufferView * bv = view_.documentBufferView();
324         Buffer * buf = &bv->buffer();
325
326         Buffer * buf_orig = &bv->buffer();
327         DocIterator cur_orig(bv->cursor());
328
329         if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
330                 vector<string> const & v = allManualsFiles();
331                 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
332                         FileName const & fname = FileName(*v.begin());
333                         if (!theBufferList().exists(fname)) {
334                                 guiApp->currentView()->setBusy(false);
335                                 guiApp->currentView()->loadDocument(fname, false);
336                                 guiApp->currentView()->setBusy(true);
337                         }
338                         buf = theBufferList().getBuffer(fname);
339                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
340                                                   buf->absFileName()));
341                         bv = view_.documentBufferView();
342                         bv->cursor().clear();
343                         bv->cursor().push_back(CursorSlice(buf->inset()));
344                 }
345         }
346
347         do {
348                 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
349                 dispatch(cmd);
350                 LYXERR(Debug::FIND, "dispatched");
351                 if (bv->cursor().result().dispatched()) {
352                         // New match found and selected (old selection replaced if needed)
353                         view_.setBusy(false);
354                         return;
355                 }
356
357                 // No match found in current buffer (however old selection might have been replaced)
358                 // select next buffer in scope, if any
359                 bool prompt = nextPrevBuffer(buf, opt);
360                 if (prompt) {
361                         if (wrap_answer != -1)
362                                 break;
363                         docstring q = getQuestionString(opt);
364                         view_.setBusy(false);
365                         wrap_answer = frontend::Alert::prompt(
366                                 _("Wrap search?"), q,
367                                 0, 1, _("&Yes"), _("&No"));
368                         view_.setBusy(true);
369                         if (wrap_answer == 1)
370                                 break;
371                 }
372                 if (buf != &view_.documentBufferView()->buffer())
373                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
374                                                   buf->absFileName()));
375                 bv = view_.documentBufferView();
376                 if (opt.forward) {
377                         bv->cursor().clear();
378                         bv->cursor().push_back(CursorSlice(buf->inset()));
379                 } else {
380                         //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
381                         bv->cursor().setCursor(doc_iterator_end(buf));
382                         bv->cursor().backwardPos();
383                         LYXERR(Debug::FIND, "findBackAdv5: cur: "
384                                 << bv->cursor());
385                 }
386                 bv->clearSelection();
387         } while (wrap_answer != 1);
388         if (buf_orig != &view_.documentBufferView()->buffer())
389                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
390                                           buf_orig->absFileName()));
391         bv = view_.documentBufferView();
392         // This may happen after a replace occurred
393         if (cur_orig.pos() > cur_orig.lastpos())
394                 cur_orig.pos() = cur_orig.lastpos();
395         bv->cursor().setCursor(cur_orig);
396         view_.setBusy(false);
397 }
398
399
400 void FindAndReplaceWidget::findAndReplace(
401         bool casesensitive, bool matchword, bool backwards,
402         bool expandmacros, bool ignoreformat, bool replace,
403         bool keep_case)
404 {
405         Buffer & buffer = find_work_area_->bufferView().buffer();
406         docstring searchString;
407         if (!ignoreformat) {
408                 searchString = buffer_to_latex(buffer);
409         } else {
410                 ParIterator it = buffer.par_iterator_begin();
411                 ParIterator end = buffer.par_iterator_end();
412                 OutputParams runparams(&buffer.params().encoding());
413                 odocstringstream os;
414                 runparams.nice = true;
415                 runparams.flavor = OutputParams::LATEX;
416                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
417                 runparams.dryrun = true;
418                 for (; it != end; ++it) {
419                         LYXERR(Debug::FIND, "Adding to search string: '"
420                                 << it->asString(false)
421                                 << "'");
422                         searchString +=
423                                 it->stringify(pos_type(0), it->size(),
424                                               AS_STR_INSETS, runparams);
425                 }
426         }
427         if (to_utf8(searchString).empty()) {
428                 buffer.message(_("Nothing to search"));
429                 return;
430         }
431         bool const regexp =
432                 to_utf8(searchString).find("\\regexp") != std::string::npos;
433         docstring replaceString;
434         if (replace) {
435                 Buffer & repl_buffer =
436                         replace_work_area_->bufferView().buffer();
437                 ostringstream oss;
438                 repl_buffer.write(oss);
439                 //buffer_to_latex(replace_buffer);
440                 replaceString = from_utf8(oss.str());
441         } else {
442                 replaceString = from_utf8(LYX_FR_NULL_STRING);
443         }
444         FindAndReplaceOptions::SearchScope scope =
445                 FindAndReplaceOptions::S_BUFFER;
446         if (CurrentDocument->isChecked())
447                 scope = FindAndReplaceOptions::S_BUFFER;
448         else if (MasterDocument->isChecked())
449                 scope = FindAndReplaceOptions::S_DOCUMENT;
450         else if (OpenDocuments->isChecked())
451                 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
452         else if (AllManualsRB->isChecked())
453                 scope = FindAndReplaceOptions::S_ALL_MANUALS;
454         else
455                 LASSERT(false, /**/);
456         LYXERR(Debug::FIND, "FindAndReplaceOptions: "
457                << "searchstring=" << searchString
458                << ", casesensitiv=" << casesensitive
459                << ", matchword=" << matchword
460                << ", backwards=" << backwards
461                << ", expandmacros=" << expandmacros
462                << ", ignoreformat=" << ignoreformat
463                << ", regexp=" << regexp
464                << ", replaceString" << replaceString
465                << ", keep_case=" << keep_case
466                << ", scope=" << scope);
467         FindAndReplaceOptions opt(searchString, casesensitive, matchword,
468                                   !backwards, expandmacros, ignoreformat,
469                                   regexp, replaceString, keep_case, scope);
470         findAndReplaceScope(opt);
471 }
472
473
474 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
475 {
476         if (! view_.currentMainWorkArea()) {
477                 view_.message(_("No open document(s) in which to search"));
478                 return;
479         }
480         // Finalize macros that are being typed, both in main document and in search or replacement WAs
481         if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
482                 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
483         if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
484                 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
485
486         // FIXME: create a Dialog::returnFocus()
487         // or something instead of this:
488         view_.setCurrentWorkArea(view_.currentMainWorkArea());
489         findAndReplace(caseCB->isChecked(),
490                 wordsCB->isChecked(),
491                 backwards,
492                 expandMacrosCB->isChecked(),
493                 ignoreFormatCB->isChecked(),
494                 replace,
495                 keepCaseCB->isChecked());
496 }
497
498
499 void FindAndReplaceWidget::hideDialog()
500 {
501         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
502 }
503
504
505 void FindAndReplaceWidget::on_findNextPB_clicked() 
506 {
507         findAndReplace(searchbackCB->isChecked(), false);
508         find_work_area_->setFocus();
509 }
510
511
512 void FindAndReplaceWidget::on_replacePB_clicked()
513 {
514         findAndReplace(searchbackCB->isChecked(), true);
515         replace_work_area_->setFocus();
516 }
517
518
519 void FindAndReplaceWidget::on_replaceallPB_clicked()
520 {
521         replace_work_area_->setFocus();
522 }
523
524
525 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
526 {
527         Buffer & doc_buf = view_.documentBufferView()->buffer();
528         BufferParams & doc_bp = doc_buf.params();
529         Buffer & find_buf = find_work_area_->bufferView().buffer();
530         LYXERR(Debug::FIND, "Applying document params to find buffer");
531         ApplyParams(find_buf, doc_bp);
532         Buffer & replace_buf = replace_work_area_->bufferView().buffer();
533         LYXERR(Debug::FIND, "Applying document params to replace buffer");
534         ApplyParams(replace_buf, doc_bp);
535
536         string lang = doc_bp.language->lang();
537         LYXERR(Debug::FIND, "Setting current editing language to " << lang << endl);
538         FuncRequest cmd(LFUN_LANGUAGE, lang);
539         find_buf.text().dispatch(find_work_area_->bufferView().cursor(), cmd);
540         replace_buf.text().dispatch(replace_work_area_->bufferView().cursor(), cmd);
541
542         view_.setCurrentWorkArea(find_work_area_);
543         LYXERR(Debug::FIND, "Selecting entire find buffer");
544         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
545         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
546         find_work_area_->installEventFilter(this);
547         replace_work_area_->installEventFilter(this);
548 }
549
550
551 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
552 {
553         replace_work_area_->removeEventFilter(this);
554         find_work_area_->removeEventFilter(this);
555         this->QWidget::hideEvent(ev);
556 }
557
558
559 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
560 {
561         return true;
562 }
563
564
565 FindAndReplace::FindAndReplace(GuiView & parent,
566                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
567         : DockView(parent, "Find LyX", qt_("Advanced Find and Replace"),
568                    area, flags)
569 {
570         widget_ = new FindAndReplaceWidget(parent);
571         setWidget(widget_);
572         setFocusProxy(widget_);
573 }
574
575
576 FindAndReplace::~FindAndReplace()
577 {
578         setFocusProxy(0);
579         delete widget_;
580 }
581
582
583 bool FindAndReplace::initialiseParams(std::string const & params)
584 {
585         return widget_->initialiseParams(params);
586 }
587
588
589 Dialog * createGuiSearchAdv(GuiView & lv)
590 {
591         FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
592 #ifdef Q_WS_MACX
593         // On Mac show and floating
594         gui->setFloating(true);
595 #endif
596         return gui;
597 }
598
599
600 } // namespace frontend
601 } // namespace lyx
602
603
604 #include "moc_FindAndReplace.cpp"