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