]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
One more comment.
[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()->loadDocument(fname, false);
263                 buf = theBufferList().getBuffer(fname);
264                 break;
265         }
266         return restarted;
267 }
268
269
270 /** Find the finest question message to post to the user */
271 docstring question_string(FindAndReplaceOptions const & opt)
272 {
273         docstring cur_pos = opt.forward ? _("End") : _("Begin");
274         docstring new_pos = opt.forward ? _("begin") : _("end");
275         docstring scope;
276         switch (opt.scope) {
277         case FindAndReplaceOptions::S_BUFFER:
278                 scope = _("file");
279                 break;
280         case FindAndReplaceOptions::S_DOCUMENT:
281                 scope = _("master document");
282                 break;
283         case FindAndReplaceOptions::S_OPEN_BUFFERS:
284                 scope = _("open files");
285                 break;
286         case FindAndReplaceOptions::S_ALL_MANUALS:
287                 scope = _("manuals");
288                 break;
289         }
290         docstring dir = opt.forward ? _("forward") : _("backwards");
291         return cur_pos + _(" of ") + scope
292                 + _(" reached while searching ") + dir + ".\n"
293                 + "\n"
294                 + _("Continue searching from ") + new_pos + " ?";
295 }
296
297
298 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt) {
299         int wrap_answer = -1;
300         ostringstream oss;
301         oss << opt;
302         FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
303         BufferView * bv = view_.documentBufferView();
304         Buffer * buf = &bv->buffer();
305
306         Buffer * buf_orig = &bv->buffer();
307         Cursor cur_orig(bv->cursor());
308
309         if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
310                 vector<string> const & v = allManualsFiles();
311                 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
312                         FileName const & fname = FileName(*v.begin());
313                         if (!theBufferList().exists(fname))
314                                 guiApp->currentView()->loadDocument(fname, false);
315                         buf = theBufferList().getBuffer(fname);
316                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
317                                                   buf->absFileName()));
318                         bv = view_.documentBufferView();
319                         bv->cursor().clear();
320                         bv->cursor().push_back(CursorSlice(buf->inset()));
321                 }
322         }
323
324         do {
325                 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
326                 dispatch(cmd);
327                 if (bv->cursor().result().dispatched()) {
328                         // Match found, selected and replaced if needed
329                         return;
330                 }
331
332                 // No match found in current buffer: select next buffer in scope, if any
333                 bool prompt = next_prev_buffer(buf, opt);
334                 if (prompt) {
335                         if (wrap_answer != -1)
336                                 break;
337                         docstring q = question_string(opt);
338                         wrap_answer = frontend::Alert::prompt(
339                                 _("Wrap search?"), q,
340                                 0, 1, _("&Yes"), _("&No"));
341                         if (wrap_answer == 1)
342                                 break;
343                 }
344                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
345                                           buf->absFileName()));
346                 bv = view_.documentBufferView();
347                 if (opt.forward) {
348                         bv->cursor().clear();
349                         bv->cursor().push_back(CursorSlice(buf->inset()));
350                 } else {
351                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
352                         bv->cursor().setCursor(doc_iterator_end(buf));
353                         bv->cursor().backwardPos();
354                         LYXERR(Debug::FIND, "findBackAdv5: cur: " << bv->cursor());
355                 }
356                 bv->clearSelection();
357         } while (wrap_answer != 1);
358         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
359                                   buf_orig->absFileName()));
360         bv = view_.documentBufferView();
361         bv->cursor() = cur_orig;
362 }
363
364
365 void FindAndReplaceWidget::findAndReplace(
366         bool casesensitive, bool matchword, bool backwards,
367         bool expandmacros, bool ignoreformat, bool replace,
368         bool keep_case)
369 {
370         Buffer & buffer = find_work_area_->bufferView().buffer();
371         docstring searchString;
372         if (!ignoreformat) {
373                 searchString = buffer_to_latex(buffer);
374         } else {
375                 ParIterator it = buffer.par_iterator_begin();
376                 ParIterator end = buffer.par_iterator_end();
377                 OutputParams runparams(&buffer.params().encoding());
378                 odocstringstream os;
379                 runparams.nice = true;
380                 runparams.flavor = OutputParams::LATEX;
381                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
382                 runparams.dryrun = true;
383                 for (; it != end; ++it) {
384                         LYXERR(Debug::FIND, "Adding to search string: '" << it->asString(false) << "'");
385                         searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
386                 }
387         }
388         if (to_utf8(searchString).empty()) {
389                 buffer.message(_("Nothing to search"));
390                 return;
391         }
392         bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
393         docstring replaceString;
394         if (replace) {
395                 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
396                 ostringstream oss;
397                 repl_buffer.write(oss);
398                 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
399         } else {
400                 replaceString = from_utf8(LYX_FR_NULL_STRING);
401         }
402         FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
403         if (CurrentDocument->isChecked())
404                 scope = FindAndReplaceOptions::S_BUFFER;
405         else if (MasterDocument->isChecked())
406                 scope = FindAndReplaceOptions::S_DOCUMENT;
407         else if (OpenDocuments->isChecked())
408                 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
409         else if (AllManualsRB->isChecked())
410                 scope = FindAndReplaceOptions::S_ALL_MANUALS;
411         else
412                 LASSERT(false, /**/);
413         LYXERR(Debug::FIND, "FindAndReplaceOptions: "
414                << "searchstring=" << searchString
415                << ", casesensitiv=" << casesensitive
416                << ", matchword=" << matchword
417                << ", backwards=" << backwards
418                << ", expandmacros=" << expandmacros
419                << ", ignoreformat=" << ignoreformat
420                << ", regexp=" << regexp
421                << ", replaceString" << replaceString
422                << ", keep_case=" << keep_case
423                << ", scope=" << scope);
424         FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
425                 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
426         findAndReplaceScope(opt);
427 }
428
429
430 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
431 {
432         if (! view_.currentMainWorkArea()) {
433                 view_.message(_("No open document(s) in which to search"));
434                 return;
435         }
436         // FIXME: create a Dialog::returnFocus() or something instead of this:
437         view_.setCurrentWorkArea(view_.currentMainWorkArea());
438         findAndReplace(caseCB->isChecked(),
439                 wordsCB->isChecked(),
440                 backwards,
441                 expandMacrosCB->isChecked(),
442                 ignoreFormatCB->isChecked(),
443                 replace,
444                 keepCaseCB->isChecked());
445 }
446
447
448 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
449 {
450         static char const * regexps[] = {
451                 ".*", ".+", "[a-z]+", "[0-9]+", ""
452         };
453         LYXERR(Debug::FIND, "Index: " << index);
454         if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
455                 find_work_area_->setFocus();
456                 Cursor & cur = find_work_area_->bufferView().cursor();
457                 if (! cur.inRegexped())
458                         dispatch(FuncRequest(LFUN_REGEXP_MODE));
459                 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
460                 regexpInsertCombo->setCurrentIndex(0);
461         }
462 }
463
464
465 void FindAndReplaceWidget::on_closePB_clicked()
466 {
467         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
468 }
469
470
471 void FindAndReplaceWidget::on_findNextPB_clicked() {
472         findAndReplace(false, false);
473         find_work_area_->setFocus();
474 }
475
476
477 void FindAndReplaceWidget::on_findPrevPB_clicked() {
478         findAndReplace(true, false);
479         find_work_area_->setFocus();
480 }
481
482
483 void FindAndReplaceWidget::on_replaceNextPB_clicked()
484 {
485         findAndReplace(false, true);
486         replace_work_area_->setFocus();
487 }
488
489
490 void FindAndReplaceWidget::on_replacePrevPB_clicked()
491 {
492         findAndReplace(true, true);
493         replace_work_area_->setFocus();
494 }
495
496
497 void FindAndReplaceWidget::on_replaceallPB_clicked()
498 {
499         replace_work_area_->setFocus();
500 }
501
502
503 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
504 {
505         view_.setCurrentWorkArea(find_work_area_);
506         LYXERR(Debug::FIND, "Selecting entire find buffer");
507         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
508         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
509         find_work_area_->installEventFilter(this);
510         replace_work_area_->installEventFilter(this);
511 }
512
513
514 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
515 {
516         replace_work_area_->removeEventFilter(this);
517         find_work_area_->removeEventFilter(this);
518         this->QWidget::hideEvent(ev);
519 }
520
521
522 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
523 {
524         return true;
525 }
526
527
528 FindAndReplace::FindAndReplace(GuiView & parent,
529                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
530         : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), 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         return new FindAndReplace(lv, Qt::RightDockWidgetArea);
554 }
555
556
557 } // namespace frontend
558 } // namespace lyx
559
560
561 #include "moc_FindAndReplace.cpp"