]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
f80f1a93fa7a881cf52d0dd31d6d6f71fbd5cb78
[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 cur_pos = opt.forward ? _("End") : _("Begin");
278         docstring new_pos = opt.forward ? _("begin") : _("end");
279         docstring scope;
280         switch (opt.scope) {
281         case FindAndReplaceOptions::S_BUFFER:
282                 scope = _("file");
283                 break;
284         case FindAndReplaceOptions::S_DOCUMENT:
285                 scope = _("master document");
286                 break;
287         case FindAndReplaceOptions::S_OPEN_BUFFERS:
288                 scope = _("open files");
289                 break;
290         case FindAndReplaceOptions::S_ALL_MANUALS:
291                 scope = _("manuals");
292                 break;
293         }
294         docstring dir = opt.forward ? _("forward") : _("backwards");
295
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);
299 }
300
301
302 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
303         int wrap_answer = -1;
304         ostringstream oss;
305         oss << opt;
306         FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
307         BufferView * bv = view_.documentBufferView();
308         Buffer * buf = &bv->buffer();
309
310         Buffer * buf_orig = &bv->buffer();
311         Cursor cur_orig(bv->cursor());
312
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);
321                         }
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()));
328                 }
329         }
330
331         do {
332                 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
333                 dispatch(cmd);
334                 if (bv->cursor().result().dispatched()) {
335                         // Match found, selected and replaced if needed
336                         return;
337                 }
338
339                 // No match found in current buffer: select next buffer in scope, if any
340                 bool prompt = next_prev_buffer(buf, opt);
341                 if (prompt) {
342                         if (wrap_answer != -1)
343                                 break;
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)
349                                 break;
350                 }
351                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
352                                           buf->absFileName()));
353                 bv = view_.documentBufferView();
354                 if (opt.forward) {
355                         bv->cursor().clear();
356                         bv->cursor().push_back(CursorSlice(buf->inset()));
357                 } else {
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());
362                 }
363                 bv->clearSelection();
364         } while (wrap_answer != 1);
365         if (buf != buf_orig)
366                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
367                                           buf_orig->absFileName()));
368         bv = view_.documentBufferView();
369         bv->cursor() = cur_orig;
370 }
371
372
373 void FindAndReplaceWidget::findAndReplace(
374         bool casesensitive, bool matchword, bool backwards,
375         bool expandmacros, bool ignoreformat, bool replace,
376         bool keep_case)
377 {
378         Buffer & buffer = find_work_area_->bufferView().buffer();
379         docstring searchString;
380         if (!ignoreformat) {
381                 searchString = buffer_to_latex(buffer);
382         } else {
383                 ParIterator it = buffer.par_iterator_begin();
384                 ParIterator end = buffer.par_iterator_end();
385                 OutputParams runparams(&buffer.params().encoding());
386                 odocstringstream os;
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);
394                 }
395         }
396         if (to_utf8(searchString).empty()) {
397                 buffer.message(_("Nothing to search"));
398                 return;
399         }
400         bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
401         docstring replaceString;
402         if (replace) {
403                 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
404                 ostringstream oss;
405                 repl_buffer.write(oss);
406                 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
407         } else {
408                 replaceString = from_utf8(LYX_FR_NULL_STRING);
409         }
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;
419         else
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);
434         view_.setBusy(true);
435         findAndReplaceScope(opt);
436         view_.setBusy(false);
437 }
438
439
440 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
441 {
442         if (! view_.currentMainWorkArea()) {
443                 view_.message(_("No open document(s) in which to search"));
444                 return;
445         }
446         // FIXME: create a Dialog::returnFocus() or something instead of this:
447         view_.setCurrentWorkArea(view_.currentMainWorkArea());
448         findAndReplace(caseCB->isChecked(),
449                 wordsCB->isChecked(),
450                 backwards,
451                 expandMacrosCB->isChecked(),
452                 ignoreFormatCB->isChecked(),
453                 replace,
454                 keepCaseCB->isChecked());
455 }
456
457
458 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
459 {
460         static char const * regexps[] = {
461                 ".*", ".+", "[a-z]+", "[0-9]+", ""
462         };
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);
471         }
472 }
473
474
475 void FindAndReplaceWidget::on_closePB_clicked()
476 {
477         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
478 }
479
480
481 void FindAndReplaceWidget::on_findNextPB_clicked() {
482         findAndReplace(false, false);
483         find_work_area_->setFocus();
484 }
485
486
487 void FindAndReplaceWidget::on_findPrevPB_clicked() {
488         findAndReplace(true, false);
489         find_work_area_->setFocus();
490 }
491
492
493 void FindAndReplaceWidget::on_replaceNextPB_clicked()
494 {
495         findAndReplace(false, true);
496         replace_work_area_->setFocus();
497 }
498
499
500 void FindAndReplaceWidget::on_replacePrevPB_clicked()
501 {
502         findAndReplace(true, true);
503         replace_work_area_->setFocus();
504 }
505
506
507 void FindAndReplaceWidget::on_replaceallPB_clicked()
508 {
509         replace_work_area_->setFocus();
510 }
511
512
513 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
514 {
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);
521 }
522
523
524 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
525 {
526         replace_work_area_->removeEventFilter(this);
527         find_work_area_->removeEventFilter(this);
528         this->QWidget::hideEvent(ev);
529 }
530
531
532 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
533 {
534         return true;
535 }
536
537
538 FindAndReplace::FindAndReplace(GuiView & parent,
539                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
540         : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
541 {
542         widget_ = new FindAndReplaceWidget(parent);
543         setWidget(widget_);
544         setFocusProxy(widget_);
545 }
546
547
548 FindAndReplace::~FindAndReplace()
549 {
550         setFocusProxy(0);
551         delete widget_;
552 }
553
554
555 bool FindAndReplace::initialiseParams(std::string const & params)
556 {
557         return widget_->initialiseParams(params);
558 }
559
560
561 Dialog * createGuiSearchAdv(GuiView & lv)
562 {
563         return new FindAndReplace(lv, Qt::RightDockWidgetArea);
564 }
565
566
567 } // namespace frontend
568 } // namespace lyx
569
570
571 #include "moc_FindAndReplace.cpp"