]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
4f4649a2e431dae12955af67d4289edcd5822e1a
[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
42 #include <iostream>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48 namespace frontend {
49
50
51 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
52         :       view_(view)
53 {
54         setupUi(this);
55 #if QT_VERSION < 0x040400
56         scrollArea->setWidget(scrollAreaWidgetContents);
57 #endif
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();
65 }
66
67
68 bool FindAndReplaceWidget::eventFilter(QObject *obj, QEvent *event)
69 {
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) {
73                         on_closePB_clicked();
74                         return true;
75                 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
76                         if (e->modifiers() == Qt::ShiftModifier) {
77                                 on_findPrevPB_clicked();
78                                 return true;
79                         } else if (e->modifiers() == Qt::NoModifier) {
80                                 on_findNextPB_clicked();
81                                 return true;
82                         }
83                 } else if (e->key() == Qt::Key_Tab && e->modifiers() == Qt::NoModifier) {
84                         LYXERR(Debug::FIND, "Focusing replace WA");
85                         replace_work_area_->setFocus();
86                         return true;
87                 }
88         }
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) {
92                         on_closePB_clicked();
93                         return true;
94                 } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
95                         if (e->modifiers() == Qt::ShiftModifier) {
96                                 on_replacePrevPB_clicked();
97                                 return true;
98                         } else if (e->modifiers() == Qt::NoModifier) {
99                                 on_replaceNextPB_clicked();
100                                 return true;
101                         }
102                 } else if (e->key() == Qt::Key_Backtab) {
103                         LYXERR(Debug::FIND, "Focusing find WA");
104                         find_work_area_->setFocus();
105                         return true;
106                 }
107         }
108         // standard event processing
109         return QWidget::eventFilter(obj, event);
110 }
111
112 static docstring buffer_to_latex(Buffer & buffer) {
113         OutputParams runparams(&buffer.params().encoding());
114         odocstringstream os;
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());
126         }
127         return os.str();
128 }
129
130
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"
136         };
137         if (v.empty()) {
138                 FileName fname;
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());
142                 }
143         }
144         return v;
145 }
146
147
148 /** Switch p_buf to point to next document buffer.
149  **
150  ** Return true if restarted from master-document buffer.
151  **
152  ** @note
153  ** Not using p_buf->allRelatives() here, because I'm not sure
154  ** whether or not the returned order is independent of p_buf.
155  **/
156 static bool next_document_buffer(Buffer * & p_buf) {
157         Buffer *p_master = p_buf;
158         Buffer *p_old;
159         do {
160                 p_old = p_master;
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(), /**/)
172         ++it;
173         if (it == v_children.end()) {
174                 p_buf = *v_children.begin();
175                 return true;
176         }
177         p_buf = *it;
178         return false;
179 }
180
181
182 /** Switch p_buf to point to previous document buffer.
183  **
184  ** Return true if restarted from last child buffer.
185  **
186  ** @note
187  ** Not using p_buf->allRelatives() here, because I'm not sure
188  ** whether or not the returned order is independent of p_buf.
189  **/
190 static bool prev_document_buffer(Buffer * & p_buf) {
191         Buffer *p_master = p_buf;
192         Buffer *p_old;
193         do {
194                 p_old = p_master;
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();
208                 --it;
209                 p_buf = *it;
210                 return true;
211         }
212         --it;
213         p_buf = *it;
214         return false;
215 }
216
217
218 /** Switch buf to point to next or previous buffer in search scope.
219  **
220  ** Return true if restarted from scratch.
221  **/
222 static bool next_prev_buffer(Buffer * & buf, FindAndReplaceOptions const & opt) {
223         bool restarted = false;
224         switch (opt.scope) {
225         case FindAndReplaceOptions::S_BUFFER:
226                 restarted = true;
227                 break;
228         case FindAndReplaceOptions::S_DOCUMENT:
229                 if (opt.forward)
230                         restarted = next_document_buffer(buf);
231                 else
232                         restarted = prev_document_buffer(buf);
233                 break;
234         case FindAndReplaceOptions::S_OPEN_BUFFERS:
235                 if (opt.forward) {
236                         buf = theBufferList().next(buf);
237                         restarted = buf == *theBufferList().begin();
238                 } else {
239                         buf = theBufferList().previous(buf);
240                         restarted = buf == *(theBufferList().end() - 1);
241                 }
242                 break;
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());
246                 if (it == v.end()) {
247                         it = v.begin();
248                 } else if (opt.forward) {
249                         ++it;
250                         if (it == v.end()) {
251                                 it = v.begin();
252                                 restarted = true;
253                         }
254                 } else {
255                         if (it == v.begin()) {
256                                 it = v.end();
257                                 restarted = true;
258                         }
259                         --it;
260                 }
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);
266                 }
267                 buf = theBufferList().getBuffer(fname);
268                 break;
269         }
270         return restarted;
271 }
272
273
274 /** Find the finest question message to post to the user */
275 docstring question_string(FindAndReplaceOptions const & opt)
276 {
277         docstring scope;
278         switch (opt.scope) {
279         case FindAndReplaceOptions::S_BUFFER:
280                 scope = _("file[[scope]]");
281                 break;
282         case FindAndReplaceOptions::S_DOCUMENT:
283                 scope = _("master document[[scope]]");
284                 break;
285         case FindAndReplaceOptions::S_OPEN_BUFFERS:
286                 scope = _("open files[[scope]]");
287                 break;
288         case FindAndReplaceOptions::S_ALL_MANUALS:
289                 scope = _("manuals[[scope]]");
290                 break;
291         }
292         docstring message = opt.forward ?
293                 bformat(_("End of %1$s reached while searching forward.\n"
294                           "Continue searching from begin?"),
295                         scope) : 
296                 bformat(_("Beginning of %1$s reached while searching backwards.\n"
297                           "Continue searching from end?"),
298                         scope);
299
300         return message;
301 }
302
303
304 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
305         int wrap_answer = -1;
306         ostringstream oss;
307         oss << opt;
308         FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
309         BufferView * bv = view_.documentBufferView();
310         Buffer * buf = &bv->buffer();
311
312         Buffer * buf_orig = &bv->buffer();
313         Cursor cur_orig(bv->cursor());
314
315         if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
316                 vector<string> const & v = allManualsFiles();
317                 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
318                         FileName const & fname = FileName(*v.begin());
319                         if (!theBufferList().exists(fname)) {
320                                 guiApp->currentView()->setBusy(false);
321                                 guiApp->currentView()->loadDocument(fname, false);
322                                 guiApp->currentView()->setBusy(true);
323                         }
324                         buf = theBufferList().getBuffer(fname);
325                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
326                                                   buf->absFileName()));
327                         bv = view_.documentBufferView();
328                         bv->cursor().clear();
329                         bv->cursor().push_back(CursorSlice(buf->inset()));
330                 }
331         }
332
333         do {
334                 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
335                 dispatch(cmd);
336                 if (bv->cursor().result().dispatched()) {
337                         // Match found, selected and replaced if needed
338                         return;
339                 }
340
341                 // No match found in current buffer: select next buffer in scope, if any
342                 bool prompt = next_prev_buffer(buf, opt);
343                 if (prompt) {
344                         if (wrap_answer != -1)
345                                 break;
346                         docstring q = question_string(opt);
347                         wrap_answer = frontend::Alert::prompt(
348                                 _("Wrap search?"), q,
349                                 0, 1, _("&Yes"), _("&No"));
350                         if (wrap_answer == 1)
351                                 break;
352                 }
353                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
354                                           buf->absFileName()));
355                 bv = view_.documentBufferView();
356                 if (opt.forward) {
357                         bv->cursor().clear();
358                         bv->cursor().push_back(CursorSlice(buf->inset()));
359                 } else {
360                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
361                         bv->cursor().setCursor(doc_iterator_end(buf));
362                         bv->cursor().backwardPos();
363                         LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
364                 }
365                 bv->clearSelection();
366         } while (wrap_answer != 1);
367         if (buf != buf_orig)
368                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
369                                           buf_orig->absFileName()));
370         bv = view_.documentBufferView();
371         bv->cursor() = 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: '" << it->asString(false) << "'");
395                         searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
396                 }
397         }
398         if (to_utf8(searchString).empty()) {
399                 buffer.message(_("Nothing to search"));
400                 return;
401         }
402         bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
403         docstring replaceString;
404         if (replace) {
405                 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
406                 ostringstream oss;
407                 repl_buffer.write(oss);
408                 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
409         } else {
410                 replaceString = from_utf8(LYX_FR_NULL_STRING);
411         }
412         FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
413         if (CurrentDocument->isChecked())
414                 scope = FindAndReplaceOptions::S_BUFFER;
415         else if (MasterDocument->isChecked())
416                 scope = FindAndReplaceOptions::S_DOCUMENT;
417         else if (OpenDocuments->isChecked())
418                 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
419         else if (AllManualsRB->isChecked())
420                 scope = FindAndReplaceOptions::S_ALL_MANUALS;
421         else
422                 LASSERT(false, /**/);
423         LYXERR(Debug::FIND, "FindAndReplaceOptions: "
424                << "searchstring=" << searchString
425                << ", casesensitiv=" << casesensitive
426                << ", matchword=" << matchword
427                << ", backwards=" << backwards
428                << ", expandmacros=" << expandmacros
429                << ", ignoreformat=" << ignoreformat
430                << ", regexp=" << regexp
431                << ", replaceString" << replaceString
432                << ", keep_case=" << keep_case
433                << ", scope=" << scope);
434         FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
435                 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
436         view_.setBusy(true);
437         findAndReplaceScope(opt);
438         view_.setBusy(false);
439 }
440
441
442 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
443 {
444         if (! view_.currentMainWorkArea()) {
445                 view_.message(_("No open document(s) in which to search"));
446                 return;
447         }
448         // FIXME: create a Dialog::returnFocus() or something instead of this:
449         view_.setCurrentWorkArea(view_.currentMainWorkArea());
450         findAndReplace(caseCB->isChecked(),
451                 wordsCB->isChecked(),
452                 backwards,
453                 expandMacrosCB->isChecked(),
454                 ignoreFormatCB->isChecked(),
455                 replace,
456                 keepCaseCB->isChecked());
457 }
458
459
460 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
461 {
462         static char const * regexps[] = {
463                 ".*", ".+", "[a-z]+", "[0-9]+", ""
464         };
465         LYXERR(Debug::FIND, "Index: " << index);
466         if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
467                 find_work_area_->setFocus();
468                 Cursor & cur = find_work_area_->bufferView().cursor();
469                 if (! cur.inRegexped())
470                         dispatch(FuncRequest(LFUN_REGEXP_MODE));
471                 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
472                 regexpInsertCombo->setCurrentIndex(0);
473         }
474 }
475
476
477 void FindAndReplaceWidget::on_closePB_clicked()
478 {
479         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
480 }
481
482
483 void FindAndReplaceWidget::on_findNextPB_clicked() {
484         findAndReplace(false, false);
485         find_work_area_->setFocus();
486 }
487
488
489 void FindAndReplaceWidget::on_findPrevPB_clicked() {
490         findAndReplace(true, false);
491         find_work_area_->setFocus();
492 }
493
494
495 void FindAndReplaceWidget::on_replaceNextPB_clicked()
496 {
497         findAndReplace(false, true);
498         replace_work_area_->setFocus();
499 }
500
501
502 void FindAndReplaceWidget::on_replacePrevPB_clicked()
503 {
504         findAndReplace(true, true);
505         replace_work_area_->setFocus();
506 }
507
508
509 void FindAndReplaceWidget::on_replaceallPB_clicked()
510 {
511         replace_work_area_->setFocus();
512 }
513
514
515 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
516 {
517         view_.setCurrentWorkArea(find_work_area_);
518         LYXERR(Debug::FIND, "Selecting entire find buffer");
519         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
520         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
521         find_work_area_->installEventFilter(this);
522         replace_work_area_->installEventFilter(this);
523 }
524
525
526 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
527 {
528         replace_work_area_->removeEventFilter(this);
529         find_work_area_->removeEventFilter(this);
530         this->QWidget::hideEvent(ev);
531 }
532
533
534 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
535 {
536         return true;
537 }
538
539
540 FindAndReplace::FindAndReplace(GuiView & parent,
541                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
542         : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
543 {
544         widget_ = new FindAndReplaceWidget(parent);
545         setWidget(widget_);
546         setFocusProxy(widget_);
547 }
548
549
550 FindAndReplace::~FindAndReplace()
551 {
552         setFocusProxy(0);
553         delete widget_;
554 }
555
556
557 bool FindAndReplace::initialiseParams(std::string const & params)
558 {
559         return widget_->initialiseParams(params);
560 }
561
562
563 Dialog * createGuiSearchAdv(GuiView & lv)
564 {
565         return new FindAndReplace(lv, Qt::RightDockWidgetArea);
566 }
567
568
569 } // namespace frontend
570 } // namespace lyx
571
572
573 #include "moc_FindAndReplace.cpp"