]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
ProgressView minimal horizontal size.
[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         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
365                                   buf_orig->absFileName()));
366         bv = view_.documentBufferView();
367         bv->cursor() = cur_orig;
368 }
369
370
371 void FindAndReplaceWidget::findAndReplace(
372         bool casesensitive, bool matchword, bool backwards,
373         bool expandmacros, bool ignoreformat, bool replace,
374         bool keep_case)
375 {
376         Buffer & buffer = find_work_area_->bufferView().buffer();
377         docstring searchString;
378         if (!ignoreformat) {
379                 searchString = buffer_to_latex(buffer);
380         } else {
381                 ParIterator it = buffer.par_iterator_begin();
382                 ParIterator end = buffer.par_iterator_end();
383                 OutputParams runparams(&buffer.params().encoding());
384                 odocstringstream os;
385                 runparams.nice = true;
386                 runparams.flavor = OutputParams::LATEX;
387                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
388                 runparams.dryrun = true;
389                 for (; it != end; ++it) {
390                         LYXERR(Debug::FIND, "Adding to search string: '" << it->asString(false) << "'");
391                         searchString += it->stringify(pos_type(0), it->size(), AS_STR_INSETS, runparams);
392                 }
393         }
394         if (to_utf8(searchString).empty()) {
395                 buffer.message(_("Nothing to search"));
396                 return;
397         }
398         bool const regexp = to_utf8(searchString).find("\\regexp") != std::string::npos;
399         docstring replaceString;
400         if (replace) {
401                 Buffer & repl_buffer = replace_work_area_->bufferView().buffer();
402                 ostringstream oss;
403                 repl_buffer.write(oss);
404                 replaceString = from_utf8(oss.str()); //buffer_to_latex(replace_buffer);
405         } else {
406                 replaceString = from_utf8(LYX_FR_NULL_STRING);
407         }
408         FindAndReplaceOptions::SearchScope scope = FindAndReplaceOptions::S_BUFFER;
409         if (CurrentDocument->isChecked())
410                 scope = FindAndReplaceOptions::S_BUFFER;
411         else if (MasterDocument->isChecked())
412                 scope = FindAndReplaceOptions::S_DOCUMENT;
413         else if (OpenDocuments->isChecked())
414                 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
415         else if (AllManualsRB->isChecked())
416                 scope = FindAndReplaceOptions::S_ALL_MANUALS;
417         else
418                 LASSERT(false, /**/);
419         LYXERR(Debug::FIND, "FindAndReplaceOptions: "
420                << "searchstring=" << searchString
421                << ", casesensitiv=" << casesensitive
422                << ", matchword=" << matchword
423                << ", backwards=" << backwards
424                << ", expandmacros=" << expandmacros
425                << ", ignoreformat=" << ignoreformat
426                << ", regexp=" << regexp
427                << ", replaceString" << replaceString
428                << ", keep_case=" << keep_case
429                << ", scope=" << scope);
430         FindAndReplaceOptions opt(searchString, casesensitive, matchword, ! backwards,
431                 expandmacros, ignoreformat, regexp, replaceString, keep_case, scope);
432         view_.setBusy(true);
433         findAndReplaceScope(opt);
434         view_.setBusy(false);
435 }
436
437
438 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
439 {
440         if (! view_.currentMainWorkArea()) {
441                 view_.message(_("No open document(s) in which to search"));
442                 return;
443         }
444         // FIXME: create a Dialog::returnFocus() or something instead of this:
445         view_.setCurrentWorkArea(view_.currentMainWorkArea());
446         findAndReplace(caseCB->isChecked(),
447                 wordsCB->isChecked(),
448                 backwards,
449                 expandMacrosCB->isChecked(),
450                 ignoreFormatCB->isChecked(),
451                 replace,
452                 keepCaseCB->isChecked());
453 }
454
455
456 void FindAndReplaceWidget::on_regexpInsertCombo_currentIndexChanged(int index)
457 {
458         static char const * regexps[] = {
459                 ".*", ".+", "[a-z]+", "[0-9]+", ""
460         };
461         LYXERR(Debug::FIND, "Index: " << index);
462         if (index >= 1 && index < 1 + int(sizeof(regexps)/sizeof(regexps[0]))) {
463                 find_work_area_->setFocus();
464                 Cursor & cur = find_work_area_->bufferView().cursor();
465                 if (! cur.inRegexped())
466                         dispatch(FuncRequest(LFUN_REGEXP_MODE));
467                 dispatch(FuncRequest(LFUN_SELF_INSERT, regexps[index - 1]));
468                 regexpInsertCombo->setCurrentIndex(0);
469         }
470 }
471
472
473 void FindAndReplaceWidget::on_closePB_clicked()
474 {
475         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
476 }
477
478
479 void FindAndReplaceWidget::on_findNextPB_clicked() {
480         findAndReplace(false, false);
481         find_work_area_->setFocus();
482 }
483
484
485 void FindAndReplaceWidget::on_findPrevPB_clicked() {
486         findAndReplace(true, false);
487         find_work_area_->setFocus();
488 }
489
490
491 void FindAndReplaceWidget::on_replaceNextPB_clicked()
492 {
493         findAndReplace(false, true);
494         replace_work_area_->setFocus();
495 }
496
497
498 void FindAndReplaceWidget::on_replacePrevPB_clicked()
499 {
500         findAndReplace(true, true);
501         replace_work_area_->setFocus();
502 }
503
504
505 void FindAndReplaceWidget::on_replaceallPB_clicked()
506 {
507         replace_work_area_->setFocus();
508 }
509
510
511 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
512 {
513         view_.setCurrentWorkArea(find_work_area_);
514         LYXERR(Debug::FIND, "Selecting entire find buffer");
515         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
516         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
517         find_work_area_->installEventFilter(this);
518         replace_work_area_->installEventFilter(this);
519 }
520
521
522 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
523 {
524         replace_work_area_->removeEventFilter(this);
525         find_work_area_->removeEventFilter(this);
526         this->QWidget::hideEvent(ev);
527 }
528
529
530 bool FindAndReplaceWidget::initialiseParams(std::string const & /* params */)
531 {
532         return true;
533 }
534
535
536 FindAndReplace::FindAndReplace(GuiView & parent,
537                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
538         : DockView(parent, "Find LyX", qt_("Find LyX Dialog"), area, flags)
539 {
540         widget_ = new FindAndReplaceWidget(parent);
541         setWidget(widget_);
542         setFocusProxy(widget_);
543 }
544
545
546 FindAndReplace::~FindAndReplace()
547 {
548         setFocusProxy(0);
549         delete widget_;
550 }
551
552
553 bool FindAndReplace::initialiseParams(std::string const & params)
554 {
555         return widget_->initialiseParams(params);
556 }
557
558
559 Dialog * createGuiSearchAdv(GuiView & lv)
560 {
561         return new FindAndReplace(lv, Qt::RightDockWidgetArea);
562 }
563
564
565 } // namespace frontend
566 } // namespace lyx
567
568
569 #include "moc_FindAndReplace.cpp"