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