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