]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/FindAndReplace.cpp
Also copying the document language to the find/replace WA cursors' current language...
[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 "Lexer.h"
16 #include "GuiApplication.h"
17 #include "GuiView.h"
18 #include "GuiWorkArea.h"
19 #include "qt_helpers.h"
20 #include "Language.h"
21
22 #include "buffer_funcs.h"
23 #include "BufferParams.h"
24 #include "BufferList.h"
25 #include "Cursor.h"
26 #include "FuncRequest.h"
27 #include "lyxfind.h"
28 #include "output_latex.h"
29 #include "OutputParams.h"
30 #include "TexRow.h"
31
32 #include "frontends/alert.h"
33
34 #include "support/debug.h"
35 #include "support/filetools.h"
36 #include "support/FileName.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
40
41 #include <QCloseEvent>
42 #include <QLineEdit>
43 #include <QMenu>
44
45 #include <iostream>
46
47 using namespace std;
48 using namespace lyx::support;
49
50 namespace lyx {
51 namespace frontend {
52
53
54 /// Apply to buf the parameters supplied through bp
55 static void ApplyParams(Buffer &buf, BufferParams const & bp) {
56         ostringstream ss;
57         ss << "\\begin_header\n";
58         bp.writeFile(ss);
59         ss << "\\end_header\n";
60         istringstream iss(ss.str());
61         Lexer lex;
62         lex.setStream(iss);
63         int unknown_tokens = buf.readHeader(lex);
64         LASSERT(unknown_tokens == 0, /* */);
65 }
66
67
68 FindAndReplaceWidget::FindAndReplaceWidget(GuiView & view)
69         :       view_(view)
70 {
71         setupUi(this);
72         find_work_area_->setGuiView(view_);
73         find_work_area_->init();
74         find_work_area_->setFrameStyle(QFrame::StyledPanel);
75
76         setFocusProxy(find_work_area_);
77         replace_work_area_->setGuiView(view_);
78         replace_work_area_->init();
79         replace_work_area_->setFrameStyle(QFrame::StyledPanel);
80
81         // We don't want two cursors blinking.
82         replace_work_area_->stopBlinkingCursor();
83 }
84
85
86 bool FindAndReplaceWidget::eventFilter(QObject * obj, QEvent * event)
87 {
88         if (event->type() != QEvent::KeyPress
89                   || (obj != find_work_area_ && obj != replace_work_area_))
90                 return QWidget::eventFilter(obj, event);
91
92         QKeyEvent * e = static_cast<QKeyEvent *> (event);
93         switch (e->key()) {
94         case Qt::Key_Escape:
95                 if (e->modifiers() == Qt::NoModifier) {
96                         hideDialog();
97                         return true;
98                 }
99                 break;
100
101         case Qt::Key_Enter:
102         case Qt::Key_Return: {
103                 // with shift we (temporarily) change search/replace direction
104                 bool const searchback = searchbackCB->isChecked();
105                 if (e->modifiers() == Qt::ShiftModifier && !searchback)
106                         searchbackCB->setChecked(!searchback);
107
108                 if (obj == find_work_area_)
109                         on_findNextPB_clicked();
110                 else
111                         on_replacePB_clicked();
112                 // back to how it was
113                 searchbackCB->setChecked(searchback);
114                 return true;
115                 break;
116                 }
117         case Qt::Key_Tab:
118                 if (e->modifiers() == Qt::NoModifier) {
119                         if (obj == find_work_area_){
120                                 LYXERR(Debug::FIND, "Focusing replace WA");
121                                 replace_work_area_->setFocus();
122                                 return true;
123                         }
124                 }
125                 break;
126
127         case Qt::Key_Backtab:
128                 if (obj == replace_work_area_) {
129                         LYXERR(Debug::FIND, "Focusing find WA");
130                         find_work_area_->setFocus();
131                         return true;
132                 }
133                 break;
134
135         default:
136                 break;
137         }
138         // standard event processing
139         return QWidget::eventFilter(obj, event);
140 }
141
142
143 static docstring buffer_to_latex(Buffer & buffer) 
144 {
145         OutputParams runparams(&buffer.params().encoding());
146         odocstringstream os;
147         runparams.nice = true;
148         runparams.flavor = OutputParams::LATEX;
149         runparams.linelen = 80; //lyxrc.plaintext_linelen;
150         // No side effect of file copying and image conversion
151         runparams.dryrun = true;
152         buffer.texrow().reset();
153         pit_type const endpit = buffer.paragraphs().size();
154         for (pit_type pit = 0; pit != endpit; ++pit) {
155                 TeXOnePar(buffer, buffer.text(),
156                           pit, os, buffer.texrow(), runparams);
157                 LYXERR(Debug::FIND, "searchString up to here: "
158                         << os.str());
159         }
160         return os.str();
161 }
162
163
164 static vector<string> const & allManualsFiles() 
165 {
166         static vector<string> v;
167         static const char * files[] = {
168                 "Intro", "UserGuide", "Tutorial", "Additional",
169                 "EmbeddedObjects", "Math", "Customization", "Shortcuts",
170                 "LFUNs", "LaTeXConfig"
171         };
172         if (v.empty()) {
173                 FileName fname;
174                 for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); ++i) {
175                         fname = i18nLibFileSearch("doc", files[i], "lyx");
176                         v.push_back(fname.absFileName());
177                 }
178         }
179         return v;
180 }
181
182
183 /** Switch p_buf to point to next document buffer.
184  **
185  ** Return true if restarted from master-document buffer.
186  **/
187 static bool nextDocumentBuffer(Buffer * & buf) 
188 {
189         ListOfBuffers const children = buf->allRelatives();
190         LYXERR(Debug::FIND, "children.size()=" << children.size());
191         ListOfBuffers::const_iterator it =
192                 find(children.begin(), children.end(), buf);
193         LASSERT(it != children.end(), /**/)
194         ++it;
195         if (it == children.end()) {
196                 buf = *children.begin();
197                 return true;
198         }
199         buf = *it;
200         return false;
201 }
202
203
204 /** Switch p_buf to point to previous document buffer.
205  **
206  ** Return true if restarted from last child buffer.
207  **/
208 static bool prevDocumentBuffer(Buffer * & buf) 
209 {
210         ListOfBuffers const children = buf->allRelatives();
211         LYXERR(Debug::FIND, "children.size()=" << children.size());
212         ListOfBuffers::const_iterator it =
213                 find(children.begin(), children.end(), buf);
214         LASSERT(it != children.end(), /**/)
215         if (it == children.begin()) {
216                 it = children.end();
217                 --it;
218                 buf = *it;
219                 return true;
220         }
221         --it;
222         buf = *it;
223         return false;
224 }
225
226
227 /** Switch buf to point to next or previous buffer in search scope.
228  **
229  ** Return true if restarted from scratch.
230  **/
231 static bool nextPrevBuffer(Buffer * & buf,
232                              FindAndReplaceOptions const & opt)
233 {
234         bool restarted = false;
235         switch (opt.scope) {
236         case FindAndReplaceOptions::S_BUFFER:
237                 restarted = true;
238                 break;
239         case FindAndReplaceOptions::S_DOCUMENT:
240                 if (opt.forward)
241                         restarted = nextDocumentBuffer(buf);
242                 else
243                         restarted = prevDocumentBuffer(buf);
244                 break;
245         case FindAndReplaceOptions::S_OPEN_BUFFERS:
246                 if (opt.forward) {
247                         buf = theBufferList().next(buf);
248                         restarted = (buf == *theBufferList().begin());
249                 } else {
250                         buf = theBufferList().previous(buf);
251                         restarted = (buf == *(theBufferList().end() - 1));
252                 }
253                 break;
254         case FindAndReplaceOptions::S_ALL_MANUALS:
255                 vector<string> const & manuals = allManualsFiles();
256                 vector<string>::const_iterator it =
257                         find(manuals.begin(), manuals.end(), buf->absFileName());
258                 if (it == manuals.end())
259                         it = manuals.begin();
260                 else if (opt.forward) {
261                         ++it;
262                         if (it == manuals.end()) {
263                                 it = manuals.begin();
264                                 restarted = true;
265                         }
266                 } else {
267                         if (it == manuals.begin()) {
268                                 it = manuals.end();
269                                 restarted = true;
270                         }
271                         --it;
272                 }
273                 FileName const & fname = FileName(*it);
274                 if (!theBufferList().exists(fname)) {
275                         guiApp->currentView()->setBusy(false);
276                         guiApp->currentView()->loadDocument(fname, false);
277                         guiApp->currentView()->setBusy(true);
278                 }
279                 buf = theBufferList().getBuffer(fname);
280                 break;
281         }
282         return restarted;
283 }
284
285
286 /** Find the finest question message to post to the user */
287 docstring getQuestionString(FindAndReplaceOptions const & opt)
288 {
289         docstring scope;
290         switch (opt.scope) {
291         case FindAndReplaceOptions::S_BUFFER:
292                 scope = _("File");
293                 break;
294         case FindAndReplaceOptions::S_DOCUMENT:
295                 scope = _("Master document");
296                 break;
297         case FindAndReplaceOptions::S_OPEN_BUFFERS:
298                 scope = _("Open files");
299                 break;
300         case FindAndReplaceOptions::S_ALL_MANUALS:
301                 scope = _("Manuals");
302                 break;
303         }
304         docstring message = opt.forward ?
305                 bformat(_("%1$s: the end was reached while searching forward.\n"
306                           "Continue searching from the beginning?"),
307                         scope) : 
308                 bformat(_("%1$s: the beginning was reached while searching backward.\n"
309                           "Continue searching from the end?"),
310                         scope);
311
312         return message;
313 }
314
315
316 void FindAndReplaceWidget::findAndReplaceScope(FindAndReplaceOptions & opt)
317 {
318         int wrap_answer = -1;
319         ostringstream oss;
320         oss << opt;
321         FuncRequest cmd(LFUN_WORD_FINDADV, from_utf8(oss.str()));
322         BufferView * bv = view_.documentBufferView();
323         Buffer * buf = &bv->buffer();
324
325         Buffer * buf_orig = &bv->buffer();
326         DocIterator cur_orig(bv->cursor());
327
328         if (opt.scope == FindAndReplaceOptions::S_ALL_MANUALS) {
329                 vector<string> const & v = allManualsFiles();
330                 if (std::find(v.begin(), v.end(), buf->absFileName()) == v.end()) {
331                         FileName const & fname = FileName(*v.begin());
332                         if (!theBufferList().exists(fname)) {
333                                 guiApp->currentView()->setBusy(false);
334                                 guiApp->currentView()->loadDocument(fname, false);
335                                 guiApp->currentView()->setBusy(true);
336                         }
337                         buf = theBufferList().getBuffer(fname);
338                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
339                                                   buf->absFileName()));
340                         bv = view_.documentBufferView();
341                         bv->cursor().clear();
342                         bv->cursor().push_back(CursorSlice(buf->inset()));
343                 }
344         }
345
346         do {
347                 LYXERR(Debug::FIND, "Dispatching LFUN_WORD_FINDADV");
348                 dispatch(cmd);
349                 LYXERR(Debug::FIND, "dispatched");
350                 if (bv->cursor().result().dispatched()) {
351                         // New match found and selected (old selection replaced if needed)
352                         return;
353                 }
354
355                 // No match found in current buffer (however old selection might have been replaced)
356                 // select next buffer in scope, if any
357                 bool prompt = nextPrevBuffer(buf, opt);
358                 if (prompt) {
359                         if (wrap_answer != -1)
360                                 break;
361                         docstring q = getQuestionString(opt);
362                         wrap_answer = frontend::Alert::prompt(
363                                 _("Wrap search?"), q,
364                                 0, 1, _("&Yes"), _("&No"));
365                         if (wrap_answer == 1)
366                                 break;
367                 }
368                 if (buf != &view_.documentBufferView()->buffer())
369                         lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
370                                                   buf->absFileName()));
371                 bv = view_.documentBufferView();
372                 if (opt.forward) {
373                         bv->cursor().clear();
374                         bv->cursor().push_back(CursorSlice(buf->inset()));
375                 } else {
376                         //lyx::dispatch(FuncRequest(LFUN_BUFFER_END));
377                         bv->cursor().setCursor(doc_iterator_end(buf));
378                         bv->cursor().backwardPos();
379                         LYXERR(Debug::FIND, "findBackAdv5: cur: "
380                                 << bv->cursor());
381                 }
382                 bv->clearSelection();
383         } while (wrap_answer != 1);
384         if (buf_orig != &view_.documentBufferView()->buffer())
385                 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
386                                           buf_orig->absFileName()));
387         bv = view_.documentBufferView();
388         // This may happen after a replace occurred
389         if (cur_orig.pos() > cur_orig.lastpos())
390                 cur_orig.pos() = cur_orig.lastpos();
391         bv->cursor().setCursor(cur_orig);
392 }
393
394
395 void FindAndReplaceWidget::findAndReplace(
396         bool casesensitive, bool matchword, bool backwards,
397         bool expandmacros, bool ignoreformat, bool replace,
398         bool keep_case)
399 {
400         Buffer & buffer = find_work_area_->bufferView().buffer();
401         docstring searchString;
402         if (!ignoreformat) {
403                 searchString = buffer_to_latex(buffer);
404         } else {
405                 ParIterator it = buffer.par_iterator_begin();
406                 ParIterator end = buffer.par_iterator_end();
407                 OutputParams runparams(&buffer.params().encoding());
408                 odocstringstream os;
409                 runparams.nice = true;
410                 runparams.flavor = OutputParams::LATEX;
411                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
412                 runparams.dryrun = true;
413                 for (; it != end; ++it) {
414                         LYXERR(Debug::FIND, "Adding to search string: '"
415                                 << it->asString(false)
416                                 << "'");
417                         searchString +=
418                                 it->stringify(pos_type(0), it->size(),
419                                               AS_STR_INSETS, runparams);
420                 }
421         }
422         if (to_utf8(searchString).empty()) {
423                 buffer.message(_("Nothing to search"));
424                 return;
425         }
426         bool const regexp =
427                 to_utf8(searchString).find("\\regexp") != std::string::npos;
428         docstring replaceString;
429         if (replace) {
430                 Buffer & repl_buffer =
431                         replace_work_area_->bufferView().buffer();
432                 ostringstream oss;
433                 repl_buffer.write(oss);
434                 //buffer_to_latex(replace_buffer);
435                 replaceString = from_utf8(oss.str());
436         } else {
437                 replaceString = from_utf8(LYX_FR_NULL_STRING);
438         }
439         FindAndReplaceOptions::SearchScope scope =
440                 FindAndReplaceOptions::S_BUFFER;
441         if (CurrentDocument->isChecked())
442                 scope = FindAndReplaceOptions::S_BUFFER;
443         else if (MasterDocument->isChecked())
444                 scope = FindAndReplaceOptions::S_DOCUMENT;
445         else if (OpenDocuments->isChecked())
446                 scope = FindAndReplaceOptions::S_OPEN_BUFFERS;
447         else if (AllManualsRB->isChecked())
448                 scope = FindAndReplaceOptions::S_ALL_MANUALS;
449         else
450                 LASSERT(false, /**/);
451         LYXERR(Debug::FIND, "FindAndReplaceOptions: "
452                << "searchstring=" << searchString
453                << ", casesensitiv=" << casesensitive
454                << ", matchword=" << matchword
455                << ", backwards=" << backwards
456                << ", expandmacros=" << expandmacros
457                << ", ignoreformat=" << ignoreformat
458                << ", regexp=" << regexp
459                << ", replaceString" << replaceString
460                << ", keep_case=" << keep_case
461                << ", scope=" << scope);
462         FindAndReplaceOptions opt(searchString, casesensitive, matchword,
463                                   !backwards, expandmacros, ignoreformat,
464                                   regexp, replaceString, keep_case, scope);
465         view_.setBusy(true);
466         findAndReplaceScope(opt);
467         view_.setBusy(false);
468 }
469
470
471 void FindAndReplaceWidget::findAndReplace(bool backwards, bool replace)
472 {
473         if (! view_.currentMainWorkArea()) {
474                 view_.message(_("No open document(s) in which to search"));
475                 return;
476         }
477         // Finalize macros that are being typed, both in main document and in search or replacement WAs
478         if (view_.currentWorkArea()->bufferView().cursor().macroModeClose())
479                 view_.currentWorkArea()->bufferView().processUpdateFlags(Update::Force);
480         if (view_.currentMainWorkArea()->bufferView().cursor().macroModeClose())
481                 view_.currentMainWorkArea()->bufferView().processUpdateFlags(Update::Force);
482
483         // FIXME: create a Dialog::returnFocus()
484         // or something instead of this:
485         view_.setCurrentWorkArea(view_.currentMainWorkArea());
486         findAndReplace(caseCB->isChecked(),
487                 wordsCB->isChecked(),
488                 backwards,
489                 expandMacrosCB->isChecked(),
490                 ignoreFormatCB->isChecked(),
491                 replace,
492                 keepCaseCB->isChecked());
493 }
494
495
496 void FindAndReplaceWidget::hideDialog()
497 {
498         dispatch(FuncRequest(LFUN_DIALOG_TOGGLE, "findreplaceadv"));
499 }
500
501
502 void FindAndReplaceWidget::on_findNextPB_clicked() 
503 {
504         findAndReplace(searchbackCB->isChecked(), false);
505         find_work_area_->setFocus();
506 }
507
508
509 void FindAndReplaceWidget::on_replacePB_clicked()
510 {
511         findAndReplace(searchbackCB->isChecked(), true);
512         replace_work_area_->setFocus();
513 }
514
515
516 void FindAndReplaceWidget::on_replaceallPB_clicked()
517 {
518         replace_work_area_->setFocus();
519 }
520
521
522 void FindAndReplaceWidget::showEvent(QShowEvent * /* ev */)
523 {
524         Buffer & doc_buf = view_.documentBufferView()->buffer();
525         BufferParams & doc_bp = doc_buf.params();
526         Buffer & find_buf = find_work_area_->bufferView().buffer();
527         LYXERR(Debug::FIND, "Applying document params to find buffer");
528         ApplyParams(find_buf, doc_bp);
529         Buffer & replace_buf = replace_work_area_->bufferView().buffer();
530         LYXERR(Debug::FIND, "Applying document params to replace buffer");
531         ApplyParams(replace_buf, doc_bp);
532
533         string lang = doc_bp.language->lang();
534         LYXERR(Debug::FIND, "Setting current editing language to " << lang << endl);
535         FuncRequest cmd(LFUN_LANGUAGE, lang);
536         find_buf.text().dispatch(find_work_area_->bufferView().cursor(), cmd);
537         replace_buf.text().dispatch(replace_work_area_->bufferView().cursor(), cmd);
538
539         view_.setCurrentWorkArea(find_work_area_);
540         LYXERR(Debug::FIND, "Selecting entire find buffer");
541         dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
542         dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
543         find_work_area_->installEventFilter(this);
544         replace_work_area_->installEventFilter(this);
545 }
546
547
548 void FindAndReplaceWidget::hideEvent(QHideEvent *ev)
549 {
550         replace_work_area_->removeEventFilter(this);
551         find_work_area_->removeEventFilter(this);
552         this->QWidget::hideEvent(ev);
553 }
554
555
556 bool FindAndReplaceWidget::initialiseParams(std::string const & /*params*/)
557 {
558         return true;
559 }
560
561
562 FindAndReplace::FindAndReplace(GuiView & parent,
563                 Qt::DockWidgetArea area, Qt::WindowFlags flags)
564         : DockView(parent, "Find LyX", qt_("Advanced Find and Replace"),
565                    area, flags)
566 {
567         widget_ = new FindAndReplaceWidget(parent);
568         setWidget(widget_);
569         setFocusProxy(widget_);
570 }
571
572
573 FindAndReplace::~FindAndReplace()
574 {
575         setFocusProxy(0);
576         delete widget_;
577 }
578
579
580 bool FindAndReplace::initialiseParams(std::string const & params)
581 {
582         return widget_->initialiseParams(params);
583 }
584
585
586 Dialog * createGuiSearchAdv(GuiView & lv)
587 {
588         FindAndReplace * gui = new FindAndReplace(lv, Qt::RightDockWidgetArea);
589 #ifdef Q_WS_MACX
590         // On Mac show and floating
591         gui->setFloating(true);
592 #endif
593         return gui;
594 }
595
596
597 } // namespace frontend
598 } // namespace lyx
599
600
601 #include "moc_FindAndReplace.cpp"