]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
38fcbfb4ec7274c4fecd22b545109de81ff33788
[lyx.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  * \author Tommaso Cucinotta
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyxfind.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/FileName.h"
50 #include "support/gettext.h"
51 #include "support/lassert.h"
52 #include "support/lstrings.h"
53
54 #include "support/regex.h"
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60
61 namespace {
62
63 bool parse_bool(docstring & howto)
64 {
65         if (howto.empty())
66                 return false;
67         docstring var;
68         howto = split(howto, var, ' ');
69         return var == "1";
70 }
71
72
73 class MatchString : public binary_function<Paragraph, pos_type, int>
74 {
75 public:
76         MatchString(docstring const & str, bool cs, bool mw)
77                 : str(str), case_sens(cs), whole_words(mw)
78         {}
79
80         // returns true if the specified string is at the specified position
81         // del specifies whether deleted strings in ct mode will be considered
82         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
83         {
84                 return par.find(str, case_sens, whole_words, pos, del);
85         }
86
87 private:
88         // search string
89         docstring str;
90         // case sensitive
91         bool case_sens;
92         // match whole words only
93         bool whole_words;
94 };
95
96
97 int findForward(DocIterator & cur, MatchString const & match,
98                 bool find_del = true)
99 {
100         for (; cur; cur.forwardChar())
101                 if (cur.inTexted()) {
102                         int len = match(cur.paragraph(), cur.pos(), find_del);
103                         if (len > 0)
104                                 return len;
105                 }
106         return 0;
107 }
108
109
110 int findBackwards(DocIterator & cur, MatchString const & match,
111                   bool find_del = true)
112 {
113         while (cur) {
114                 cur.backwardChar();
115                 if (cur.inTexted()) {
116                         int len = match(cur.paragraph(), cur.pos(), find_del);
117                         if (len > 0)
118                                 return len;
119                 }
120         }
121         return 0;
122 }
123
124
125 bool searchAllowed(docstring const & str)
126 {
127         if (str.empty()) {
128                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
129                 return false;
130         }
131         return true;
132 }
133
134
135 bool findOne(BufferView * bv, docstring const & searchstr,
136              bool case_sens, bool whole, bool forward,
137              bool find_del = true, bool check_wrap = false)
138 {
139         if (!searchAllowed(searchstr))
140                 return false;
141
142         DocIterator cur = forward
143                 ? bv->cursor().selectionEnd()
144                 : bv->cursor().selectionBegin();
145
146         MatchString const match(searchstr, case_sens, whole);
147
148         int match_len = forward
149                 ? findForward(cur, match, find_del)
150                 : findBackwards(cur, match, find_del);
151
152         if (match_len > 0)
153                 bv->putSelectionAt(cur, match_len, !forward);
154         else if (check_wrap) {
155                 DocIterator cur_orig(bv->cursor());
156                 docstring q;
157                 if (forward)
158                         q = _("End of file reached while searching forward.\n"
159                           "Continue searching from the beginning?");
160                 else
161                         q = _("Beginning of file reached while searching backward.\n"
162                           "Continue searching from the end?");
163                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
164                         q, 0, 1, _("&Yes"), _("&No"));
165                 if (wrap_answer == 0) {
166                         if (forward) {
167                                 bv->cursor().clear();
168                                 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
169                         } else {
170                                 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
171                                 bv->cursor().backwardPos();
172                         }
173                         bv->clearSelection();
174                         if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
175                                 return true;
176                 }
177                 bv->cursor().setCursor(cur_orig);
178                 return false;
179         }
180
181         return match_len > 0;
182 }
183
184
185 int replaceAll(BufferView * bv,
186                docstring const & searchstr, docstring const & replacestr,
187                bool case_sens, bool whole)
188 {
189         Buffer & buf = bv->buffer();
190
191         if (!searchAllowed(searchstr) || buf.isReadonly())
192                 return 0;
193
194         DocIterator cur_orig(bv->cursor());
195
196         MatchString const match(searchstr, case_sens, whole);
197         int num = 0;
198
199         int const rsize = replacestr.size();
200         int const ssize = searchstr.size();
201
202         Cursor cur(*bv);
203         cur.setCursor(doc_iterator_begin(&buf));
204         int match_len = findForward(cur, match, false);
205         while (match_len > 0) {
206                 // Backup current cursor position and font.
207                 pos_type const pos = cur.pos();
208                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
209                 cur.recordUndo();
210                 int striked = ssize -
211                         cur.paragraph().eraseChars(pos, pos + match_len,
212                                                    buf.params().track_changes);
213                 cur.paragraph().insert(pos, replacestr, font,
214                                        Change(buf.params().track_changes
215                                               ? Change::INSERTED
216                                               : Change::UNCHANGED));
217                 for (int i = 0; i < rsize + striked; ++i)
218                         cur.forwardChar();
219                 ++num;
220                 match_len = findForward(cur, match, false);
221         }
222
223         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
224
225         cur_orig.fixIfBroken();
226         bv->setCursor(cur_orig);
227
228         return num;
229 }
230
231
232 // the idea here is that we are going to replace the string that
233 // is selected IF it is the search string.
234 // if there is a selection, but it is not the search string, then
235 // we basically ignore it. (FIXME We ought to replace only within
236 // the selection.)
237 // if there is no selection, then:
238 //  (i) if some search string has been provided, then we find it.
239 //      (think of how the dialog works when you hit "replace" the
240 //      first time.)
241 // (ii) if no search string has been provided, then we treat the
242 //      word the cursor is in as the search string. (why? i have no
243 //      idea.) but this only works in text?
244 //
245 // returns the number of replacements made (one, if any) and
246 // whether anything at all was done.
247 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
248                            docstring const & replacestr, bool case_sens,
249                            bool whole, bool forward, bool findnext)
250 {
251         Cursor & cur = bv->cursor();
252         bool found = false;
253         if (!cur.selection()) {
254                 // no selection, non-empty search string: find it
255                 if (!searchstr.empty()) {
256                         found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
257                         return make_pair(found, 0);
258                 }
259                 // empty search string
260                 if (!cur.inTexted())
261                         // bail in math
262                         return make_pair(false, 0);
263                 // select current word and treat it as the search string.
264                 // This causes a minor bug as undo will restore this selection,
265                 // which the user did not create (#8986).
266                 cur.innerText()->selectWord(cur, WHOLE_WORD);
267                 searchstr = cur.selectionAsString(false);
268         }
269
270         // if we still don't have a search string, report the error
271         // and abort.
272         if (!searchAllowed(searchstr))
273                 return make_pair(false, 0);
274
275         bool have_selection = cur.selection();
276         docstring const selected = cur.selectionAsString(false);
277         bool match =
278                 case_sens
279                 ? searchstr == selected
280                 : compare_no_case(searchstr, selected) == 0;
281
282         // no selection or current selection is not search word:
283         // just find the search word
284         if (!have_selection || !match) {
285                 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
286                 return make_pair(found, 0);
287         }
288
289         // we're now actually ready to replace. if the buffer is
290         // read-only, we can't, though.
291         if (bv->buffer().isReadonly())
292                 return make_pair(false, 0);
293
294         cap::replaceSelectionWithString(cur, replacestr);
295         if (forward) {
296                 cur.pos() += replacestr.length();
297                 LASSERT(cur.pos() <= cur.lastpos(),
298                         cur.pos() = cur.lastpos());
299         }
300         if (findnext)
301                 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
302
303         return make_pair(true, 1);
304 }
305
306 } // namespace anon
307
308
309 docstring const find2string(docstring const & search,
310                             bool casesensitive, bool matchword, bool forward)
311 {
312         odocstringstream ss;
313         ss << search << '\n'
314            << int(casesensitive) << ' '
315            << int(matchword) << ' '
316            << int(forward);
317         return ss.str();
318 }
319
320
321 docstring const replace2string(docstring const & replace,
322                                docstring const & search,
323                                bool casesensitive, bool matchword,
324                                bool all, bool forward, bool findnext)
325 {
326         odocstringstream ss;
327         ss << replace << '\n'
328            << search << '\n'
329            << int(casesensitive) << ' '
330            << int(matchword) << ' '
331            << int(all) << ' '
332            << int(forward) << ' '
333            << int(findnext);
334         return ss.str();
335 }
336
337
338 bool lyxfind(BufferView * bv, FuncRequest const & ev)
339 {
340         if (!bv || ev.action() != LFUN_WORD_FIND)
341                 return false;
342
343         //lyxerr << "find called, cmd: " << ev << endl;
344
345         // data is of the form
346         // "<search>
347         //  <casesensitive> <matchword> <forward>"
348         docstring search;
349         docstring howto = split(ev.argument(), search, '\n');
350
351         bool casesensitive = parse_bool(howto);
352         bool matchword     = parse_bool(howto);
353         bool forward       = parse_bool(howto);
354
355         return findOne(bv, search, casesensitive, matchword, forward, true, true);
356 }
357
358
359 bool lyxreplace(BufferView * bv,
360                 FuncRequest const & ev, bool has_deleted)
361 {
362         if (!bv || ev.action() != LFUN_WORD_REPLACE)
363                 return false;
364
365         // data is of the form
366         // "<search>
367         //  <replace>
368         //  <casesensitive> <matchword> <all> <forward> <findnext>"
369         docstring search;
370         docstring rplc;
371         docstring howto = split(ev.argument(), rplc, '\n');
372         howto = split(howto, search, '\n');
373
374         bool casesensitive = parse_bool(howto);
375         bool matchword     = parse_bool(howto);
376         bool all           = parse_bool(howto);
377         bool forward       = parse_bool(howto);
378         bool findnext      = howto.empty() ? true : parse_bool(howto);
379
380         bool update = false;
381
382         if (!has_deleted) {
383                 int replace_count = 0;
384                 if (all) {
385                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
386                         update = replace_count > 0;
387                 } else {
388                         pair<bool, int> rv =
389                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
390                         update = rv.first;
391                         replace_count = rv.second;
392                 }
393
394                 Buffer const & buf = bv->buffer();
395                 if (!update) {
396                         // emit message signal.
397                         buf.message(_("String not found."));
398                 } else {
399                         if (replace_count == 0) {
400                                 buf.message(_("String found."));
401                         } else if (replace_count == 1) {
402                                 buf.message(_("String has been replaced."));
403                         } else {
404                                 docstring const str =
405                                         bformat(_("%1$d strings have been replaced."), replace_count);
406                                 buf.message(str);
407                         }
408                 }
409         } else if (findnext) {
410                 // if we have deleted characters, we do not replace at all, but
411                 // rather search for the next occurence
412                 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
413                         update = true;
414                 else
415                         bv->message(_("String not found."));
416         }
417         return update;
418 }
419
420
421 bool findNextChange(DocIterator & cur)
422 {
423         for (; cur; cur.forwardPos())
424                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
425                         return true;
426         return false;
427 }
428
429
430 bool findPreviousChange(DocIterator & cur)
431 {
432         for (cur.backwardPos(); cur; cur.backwardPos()) {
433                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
434                         return true;
435         }
436         return false;
437 }
438
439
440 bool selectChange(Cursor & cur, bool forward)
441 {
442         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
443                 return false;
444         Change ch = cur.paragraph().lookupChange(cur.pos());
445
446         CursorSlice tip1 = cur.top();
447         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
448                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
449                 if (!ch2.isSimilarTo(ch))
450                         break;
451         }
452         CursorSlice tip2 = cur.top();
453         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
454                 tip2.backwardPos();
455                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
456                 if (!ch2.isSimilarTo(ch)) {
457                         // take a step forward to correctly set the selection
458                         tip2.forwardPos();
459                         break;
460                 }
461         }
462         if (forward)
463                 swap(tip1, tip2);
464         cur.top() = tip1;
465         cur.bv().mouseSetCursor(cur, false);
466         cur.top() = tip2;
467         cur.bv().mouseSetCursor(cur, true);
468         return true;
469 }
470
471
472 namespace {
473
474
475 bool findChange(BufferView * bv, bool forward)
476 {
477         Cursor cur(*bv);
478         cur.setCursor(forward ? bv->cursor().selectionEnd()
479                       : bv->cursor().selectionBegin());
480         forward ? findNextChange(cur) : findPreviousChange(cur);
481         return selectChange(cur, forward);
482 }
483
484 }
485
486 bool findNextChange(BufferView * bv)
487 {
488         return findChange(bv, true);
489 }
490
491
492 bool findPreviousChange(BufferView * bv)
493 {
494         return findChange(bv, false);
495 }
496
497
498
499 namespace {
500
501 typedef vector<pair<string, string> > Escapes;
502
503 /// A map of symbols and their escaped equivalent needed within a regex.
504 /// @note Beware of order
505 Escapes const & get_regexp_escapes()
506 {
507         typedef std::pair<std::string, std::string> P;
508
509         static Escapes escape_map;
510         if (escape_map.empty()) {
511                 escape_map.push_back(P("$", "_x_$"));
512                 escape_map.push_back(P("{", "_x_{"));
513                 escape_map.push_back(P("}", "_x_}"));
514                 escape_map.push_back(P("[", "_x_["));
515                 escape_map.push_back(P("]", "_x_]"));
516                 escape_map.push_back(P("(", "_x_("));
517                 escape_map.push_back(P(")", "_x_)"));
518                 escape_map.push_back(P("+", "_x_+"));
519                 escape_map.push_back(P("*", "_x_*"));
520                 escape_map.push_back(P(".", "_x_."));
521                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
522                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
523                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
524                 escape_map.push_back(P("_x_", "\\"));
525         }
526         return escape_map;
527 }
528
529 /// A map of lyx escaped strings and their unescaped equivalent.
530 Escapes const & get_lyx_unescapes()
531 {
532         typedef std::pair<std::string, std::string> P;
533
534         static Escapes escape_map;
535         if (escape_map.empty()) {
536                 escape_map.push_back(P("\\%", "%"));
537                 escape_map.push_back(P("\\mathcircumflex ", "^"));
538                 escape_map.push_back(P("\\mathcircumflex", "^"));
539                 escape_map.push_back(P("\\backslash ", "\\"));
540                 escape_map.push_back(P("\\backslash", "\\"));
541                 escape_map.push_back(P("\\\\{", "_x_<"));
542                 escape_map.push_back(P("\\\\}", "_x_>"));
543                 escape_map.push_back(P("\\sim ", "~"));
544                 escape_map.push_back(P("\\sim", "~"));
545         }
546         return escape_map;
547 }
548
549 /// A map of escapes turning a regexp matching text to one matching latex.
550 Escapes const & get_regexp_latex_escapes()
551 {
552         typedef std::pair<std::string, std::string> P;
553
554         static Escapes escape_map;
555         if (escape_map.empty()) {
556                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\})"));
557                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
558                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
559                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
560                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
561                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
562                 escape_map.push_back(P("%", "\\\\\\%"));
563         }
564         return escape_map;
565 }
566
567 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
568  ** the found occurrence were escaped.
569  **/
570 string apply_escapes(string s, Escapes const & escape_map)
571 {
572         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
573         Escapes::const_iterator it;
574         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
575 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
576                 unsigned int pos = 0;
577                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
578                         s.replace(pos, it->first.length(), it->second);
579                         LYXERR(Debug::FIND, "After escape: " << s);
580                         pos += it->second.length();
581 //                      LYXERR(Debug::FIND, "pos: " << pos);
582                 }
583         }
584         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
585         return s;
586 }
587
588
589 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
590 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
591 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
592 string escape_for_regex(string s, bool match_latex)
593 {
594         size_t pos = 0;
595         while (pos < s.size()) {
596                 size_t new_pos = s.find("\\regexp{", pos);
597                 if (new_pos == string::npos)
598                         new_pos = s.size();
599                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
600                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
601                 LYXERR(Debug::FIND, "t [lyx]: " << t);
602                 t = apply_escapes(t, get_regexp_escapes());
603                 LYXERR(Debug::FIND, "t [rxp]: " << t);
604                 s.replace(pos, new_pos - pos, t);
605                 new_pos = pos + t.size();
606                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
607                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
608                 if (new_pos == s.size())
609                         break;
610                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
611                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
612                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
613                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
614                 LYXERR(Debug::FIND, "t in regexp      : " << t);
615                 t = apply_escapes(t, get_lyx_unescapes());
616                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
617                 if (match_latex) {
618                         t = apply_escapes(t, get_regexp_latex_escapes());
619                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
620                 }
621                 if (end_pos == s.size()) {
622                         s.replace(new_pos, end_pos - new_pos, t);
623                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
624                         break;
625                 }
626                 s.replace(new_pos, end_pos + 13 - new_pos, t);
627                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
628                 pos = new_pos + t.size();
629                 LYXERR(Debug::FIND, "pos: " << pos);
630         }
631         return s;
632 }
633
634
635 /// Wrapper for lyx::regex_replace with simpler interface
636 bool regex_replace(string const & s, string & t, string const & searchstr,
637                    string const & replacestr)
638 {
639         lyx::regex e(searchstr);
640         ostringstream oss;
641         ostream_iterator<char, char> it(oss);
642         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
643         // tolerate t and s be references to the same variable
644         bool rv = (s != oss.str());
645         t = oss.str();
646         return rv;
647 }
648
649
650 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
651  **
652  ** Verify that closed braces exactly match open braces. This avoids that, for example,
653  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
654  **
655  ** @param unmatched
656  ** Number of open braces that must remain open at the end for the verification to succeed.
657  **/
658 bool braces_match(string::const_iterator const & beg,
659                   string::const_iterator const & end,
660                   int unmatched = 0)
661 {
662         int open_pars = 0;
663         string::const_iterator it = beg;
664         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
665         for (; it != end; ++it) {
666                 // Skip escaped braces in the count
667                 if (*it == '\\') {
668                         ++it;
669                         if (it == end)
670                                 break;
671                 } else if (*it == '{') {
672                         ++open_pars;
673                 } else if (*it == '}') {
674                         if (open_pars == 0) {
675                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
676                                 return false;
677                         } else
678                                 --open_pars;
679                 }
680         }
681         if (open_pars != unmatched) {
682                 LYXERR(Debug::FIND, "Found " << open_pars
683                        << " instead of " << unmatched
684                        << " unmatched open braces at the end of count");
685                 return false;
686         }
687         LYXERR(Debug::FIND, "Braces match as expected");
688         return true;
689 }
690
691
692 /** The class performing a match between a position in the document and the FindAdvOptions.
693  **/
694 class MatchStringAdv {
695 public:
696         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
697
698         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
699          ** constructor as opt.search, under the opt.* options settings.
700          **
701          ** @param at_begin
702          **     If set, then match is searched only against beginning of text starting at cur.
703          **     If unset, then match is searched anywhere in text starting at cur.
704          **
705          ** @return
706          ** The length of the matching text, or zero if no match was found.
707          **/
708         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
709
710 public:
711         /// buffer
712         lyx::Buffer * p_buf;
713         /// first buffer on which search was started
714         lyx::Buffer * const p_first_buf;
715         /// options
716         FindAndReplaceOptions const & opt;
717
718 private:
719         /// Auxiliary find method (does not account for opt.matchword)
720         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
721
722         /** Normalize a stringified or latexified LyX paragraph.
723          **
724          ** Normalize means:
725          ** <ul>
726          **   <li>if search is not casesensitive, then lowercase the string;
727          **   <li>remove any newline at begin or end of the string;
728          **   <li>replace any newline in the middle of the string with a simple space;
729          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
730          ** </ul>
731          **
732          ** @todo Normalization should also expand macros, if the corresponding
733          ** search option was checked.
734          **/
735         string normalize(docstring const & s, bool hack_braces) const;
736         // normalized string to search
737         string par_as_string;
738         // regular expression to use for searching
739         lyx::regex regexp;
740         // same as regexp, but prefixed with a ".*"
741         lyx::regex regexp2;
742         // leading format material as string
743         string lead_as_string;
744         // par_as_string after removal of lead_as_string
745         string par_as_string_nolead;
746         // unmatched open braces in the search string/regexp
747         int open_braces;
748         // number of (.*?) subexpressions added at end of search regexp for closing
749         // environments, math mode, styles, etc...
750         int close_wildcards;
751         // Are we searching with regular expressions ?
752         bool use_regexp;
753 };
754
755
756 static docstring buffer_to_latex(Buffer & buffer)
757 {
758         OutputParams runparams(&buffer.params().encoding());
759         odocstringstream ods;
760         otexstream os(ods);
761         runparams.nice = true;
762         runparams.flavor = OutputParams::LATEX;
763         runparams.linelen = 80; //lyxrc.plaintext_linelen;
764         // No side effect of file copying and image conversion
765         runparams.dryrun = true;
766         pit_type const endpit = buffer.paragraphs().size();
767         for (pit_type pit = 0; pit != endpit; ++pit) {
768                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
769                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
770         }
771         return ods.str();
772 }
773
774
775 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
776 {
777         docstring str;
778         if (!opt.ignoreformat) {
779                 str = buffer_to_latex(buffer);
780         } else {
781                 OutputParams runparams(&buffer.params().encoding());
782                 runparams.nice = true;
783                 runparams.flavor = OutputParams::LATEX;
784                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
785                 runparams.dryrun = true;
786                 runparams.for_search = true;
787                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
788                         Paragraph const & par = buffer.paragraphs().at(pit);
789                         LYXERR(Debug::FIND, "Adding to search string: '"
790                                << par.asString(pos_type(0), par.size(),
791                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
792                                                &runparams)
793                                << "'");
794                         str += par.asString(pos_type(0), par.size(),
795                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
796                                             &runparams);
797                 }
798         }
799         return str;
800 }
801
802
803 /// Return separation pos between the leading material and the rest
804 static size_t identifyLeading(string const & s)
805 {
806         string t = s;
807         // @TODO Support \item[text]
808         while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
809                || regex_replace(t, t, "^\\$", "")
810                || regex_replace(t, t, "^\\\\\\[ ", "")
811                || regex_replace(t, t, "^\\\\item ", "")
812                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
813                 LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
814         return s.find(t);
815 }
816
817
818 // Remove trailing closure of math, macros and environments, so to catch parts of them.
819 static int identifyClosing(string & t)
820 {
821         int open_braces = 0;
822         do {
823                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
824                 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
825                         continue;
826                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
827                         continue;
828                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
829                         continue;
830                 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
831                         ++open_braces;
832                         continue;
833                 }
834                 break;
835         } while (true);
836         return open_braces;
837 }
838
839
840 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
841         : p_buf(&buf), p_first_buf(&buf), opt(opt)
842 {
843         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
844         docstring const & ds = stringifySearchBuffer(find_buf, opt);
845         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
846         // When using regexp, braces are hacked already by escape_for_regex()
847         par_as_string = normalize(ds, !use_regexp);
848         open_braces = 0;
849         close_wildcards = 0;
850
851         size_t lead_size = 0;
852         if (opt.ignoreformat) {
853                 if (!use_regexp) {
854                         // if par_as_string_nolead were emty,
855                         // the following call to findAux will always *find* the string
856                         // in the checked data, and thus always using the slow
857                         // examining of the current text part.
858                         par_as_string_nolead = par_as_string;
859                 }
860         } else {
861                 lead_size = identifyLeading(par_as_string);
862                 lead_as_string = par_as_string.substr(0, lead_size);
863                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
864         }
865
866         if (!use_regexp) {
867                 open_braces = identifyClosing(par_as_string);
868                 identifyClosing(par_as_string_nolead);
869                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
870                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
871         } else {
872                 string lead_as_regexp;
873                 if (lead_size > 0) {
874                         // @todo No need to search for \regexp{} insets in leading material
875                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
876                         par_as_string = par_as_string_nolead;
877                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
878                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
879                 }
880                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
881                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
882                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
883                 if (
884                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
885                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
886                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
887                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
888                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
889                         || regex_replace(par_as_string, par_as_string,
890                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
891                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
892                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
893                         ) {
894                         ++close_wildcards;
895                 }
896                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
897                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
898                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
899                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
900                 // If entered regexp must match at begin of searched string buffer
901                 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
902                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
903                 regexp = lyx::regex(regexp_str);
904
905                 // If entered regexp may match wherever in searched string buffer
906                 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
907                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
908                 regexp2 = lyx::regex(regexp2_str);
909         }
910 }
911
912
913 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
914 {
915         if (at_begin &&
916                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
917                 return 0;
918         docstring docstr = stringifyFromForSearch(opt, cur, len);
919         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
920         string str = normalize(docstr, true);
921         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
922         if (! use_regexp) {
923                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
924                 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
925                 if (at_begin) {
926                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
927                         if (str.substr(0, par_as_string.size()) == par_as_string)
928                                 return par_as_string.size();
929                 } else {
930                         size_t pos = str.find(par_as_string_nolead);
931                         if (pos != string::npos)
932                                 return par_as_string.size();
933                 }
934         } else {
935                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
936                 // Try all possible regexp matches,
937                 //until one that verifies the braces match test is found
938                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
939                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
940                 sregex_iterator re_it_end;
941                 for (; re_it != re_it_end; ++re_it) {
942                         match_results<string::const_iterator> const & m = *re_it;
943                         // Check braces on the segment that matched the entire regexp expression,
944                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
945                         if (!braces_match(m[0].first, m[0].second, open_braces))
946                                 return 0;
947                         // Check braces on segments that matched all (.*?) subexpressions,
948                         // except the last "padding" one inserted by lyx.
949                         for (size_t i = 1; i < m.size() - 1; ++i)
950                                 if (!braces_match(m[i].first, m[i].second))
951                                         return false;
952                         // Exclude from the returned match length any length
953                         // due to close wildcards added at end of regexp
954                         if (close_wildcards == 0)
955                                 return m[0].second - m[0].first;
956                         else
957                                 return m[m.size() - close_wildcards].first - m[0].first;
958                 }
959         }
960         return 0;
961 }
962
963
964 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
965 {
966         int res = findAux(cur, len, at_begin);
967         LYXERR(Debug::FIND,
968                "res=" << res << ", at_begin=" << at_begin
969                << ", matchword=" << opt.matchword
970                << ", inTexted=" << cur.inTexted());
971         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
972                 return res;
973         Paragraph const & par = cur.paragraph();
974         bool ws_left = (cur.pos() > 0)
975                 ? par.isWordSeparator(cur.pos() - 1)
976                 : true;
977         bool ws_right = (cur.pos() + res < par.size())
978                 ? par.isWordSeparator(cur.pos() + res)
979                 : true;
980         LYXERR(Debug::FIND,
981                "cur.pos()=" << cur.pos() << ", res=" << res
982                << ", separ: " << ws_left << ", " << ws_right
983                << endl);
984         if (ws_left && ws_right)
985                 return res;
986         return 0;
987 }
988
989
990 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
991 {
992         string t;
993         if (! opt.casesensitive)
994                 t = lyx::to_utf8(lowercase(s));
995         else
996                 t = lyx::to_utf8(s);
997         // Remove \n at begin
998         while (!t.empty() && t[0] == '\n')
999                 t = t.substr(1);
1000         // Remove \n at end
1001         while (!t.empty() && t[t.size() - 1] == '\n')
1002                 t = t.substr(0, t.size() - 1);
1003         size_t pos;
1004         // Replace all other \n with spaces
1005         while ((pos = t.find("\n")) != string::npos)
1006                 t.replace(pos, 1, " ");
1007         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1008         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1009         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
1010                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1011
1012         // FIXME - check what preceeds the brace
1013         if (hack_braces) {
1014                 if (opt.ignoreformat)
1015                         while (regex_replace(t, t, "\\{", "_x_<")
1016                                || regex_replace(t, t, "\\}", "_x_>"))
1017                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1018                 else
1019                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1020                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1021                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1022         }
1023
1024         return t;
1025 }
1026
1027
1028 docstring stringifyFromCursor(DocIterator const & cur, int len)
1029 {
1030         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1031         if (cur.inTexted()) {
1032                 Paragraph const & par = cur.paragraph();
1033                 // TODO what about searching beyond/across paragraph breaks ?
1034                 // TODO Try adding a AS_STR_INSERTS as last arg
1035                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1036                         int(par.size()) : cur.pos() + len;
1037                 OutputParams runparams(&cur.buffer()->params().encoding());
1038                 runparams.nice = true;
1039                 runparams.flavor = OutputParams::LATEX;
1040                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1041                 // No side effect of file copying and image conversion
1042                 runparams.dryrun = true;
1043                 LYXERR(Debug::FIND, "Stringifying with cur: "
1044                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1045                 return par.asString(cur.pos(), end,
1046                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1047                         &runparams);
1048         } else if (cur.inMathed()) {
1049                 docstring s;
1050                 CursorSlice cs = cur.top();
1051                 MathData md = cs.cell();
1052                 MathData::const_iterator it_end =
1053                         (( len == -1 || cs.pos() + len > int(md.size()))
1054                          ? md.end()
1055                          : md.begin() + cs.pos() + len );
1056                 for (MathData::const_iterator it = md.begin() + cs.pos();
1057                      it != it_end; ++it)
1058                         s = s + asString(*it);
1059                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1060                 return s;
1061         }
1062         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1063         return docstring();
1064 }
1065
1066
1067 /** Computes the LaTeX export of buf starting from cur and ending len positions
1068  * after cur, if len is positive, or at the paragraph or innermost inset end
1069  * if len is -1.
1070  */
1071 docstring latexifyFromCursor(DocIterator const & cur, int len)
1072 {
1073         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1074         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1075                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1076         Buffer const & buf = *cur.buffer();
1077         LBUFERR(buf.params().isLatex());
1078
1079         odocstringstream ods;
1080         otexstream os(ods);
1081         OutputParams runparams(&buf.params().encoding());
1082         runparams.nice = false;
1083         runparams.flavor = OutputParams::LATEX;
1084         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1085         // No side effect of file copying and image conversion
1086         runparams.dryrun = true;
1087
1088         if (cur.inTexted()) {
1089                 // @TODO what about searching beyond/across paragraph breaks ?
1090                 pos_type endpos = cur.paragraph().size();
1091                 if (len != -1 && endpos > cur.pos() + len)
1092                         endpos = cur.pos() + len;
1093                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1094                           string(), cur.pos(), endpos);
1095                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1096         } else if (cur.inMathed()) {
1097                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1098                 for (int s = cur.depth() - 1; s >= 0; --s) {
1099                         CursorSlice const & cs = cur[s];
1100                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1101                                 WriteStream ws(os);
1102                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1103                                 break;
1104                         }
1105                 }
1106
1107                 CursorSlice const & cs = cur.top();
1108                 MathData md = cs.cell();
1109                 MathData::const_iterator it_end =
1110                         ((len == -1 || cs.pos() + len > int(md.size()))
1111                          ? md.end()
1112                          : md.begin() + cs.pos() + len);
1113                 for (MathData::const_iterator it = md.begin() + cs.pos();
1114                      it != it_end; ++it)
1115                         ods << asString(*it);
1116
1117                 // Retrieve the math environment type, and add '$' or '$]'
1118                 // or others (\end{equation}) accordingly
1119                 for (int s = cur.depth() - 1; s >= 0; --s) {
1120                         CursorSlice const & cs = cur[s];
1121                         InsetMath * inset = cs.asInsetMath();
1122                         if (inset && inset->asHullInset()) {
1123                                 WriteStream ws(os);
1124                                 inset->asHullInset()->footer_write(ws);
1125                                 break;
1126                         }
1127                 }
1128                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1129         } else {
1130                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1131         }
1132         return ods.str();
1133 }
1134
1135
1136 /** Finalize an advanced find operation, advancing the cursor to the innermost
1137  ** position that matches, plus computing the length of the matching text to
1138  ** be selected
1139  **/
1140 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1141 {
1142         // Search the foremost position that matches (avoids find of entire math
1143         // inset when match at start of it)
1144         size_t d;
1145         DocIterator old_cur(cur.buffer());
1146         do {
1147                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1148                 d = cur.depth();
1149                 old_cur = cur;
1150                 cur.forwardPos();
1151         } while (cur && cur.depth() > d && match(cur) > 0);
1152         cur = old_cur;
1153         LASSERT(match(cur) > 0, return 0);
1154         LYXERR(Debug::FIND, "Ok");
1155
1156         // Compute the match length
1157         int len = 1;
1158         if (cur.pos() + len > cur.lastpos())
1159                 return 0;
1160         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1161         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1162                 ++len;
1163                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1164         }
1165         // Length of matched text (different from len param)
1166         int old_len = match(cur, len);
1167         int new_len;
1168         // Greedy behaviour while matching regexps
1169         while ((new_len = match(cur, len + 1)) > old_len) {
1170                 ++len;
1171                 old_len = new_len;
1172                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1173         }
1174         return len;
1175 }
1176
1177
1178 /// Finds forward
1179 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1180 {
1181         if (!cur)
1182                 return 0;
1183         while (!theApp()->longOperationCancelled() && cur) {
1184                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1185                 int match_len = match(cur, -1, false);
1186                 LYXERR(Debug::FIND, "match_len: " << match_len);
1187                 if (match_len) {
1188                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1189                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1190                                 int match_len = match(cur);
1191                                 LYXERR(Debug::FIND, "match_len: " << match_len);
1192                                 if (match_len) {
1193                                         // Sometimes in finalize we understand it wasn't a match
1194                                         // and we need to continue the outest loop
1195                                         int len = findAdvFinalize(cur, match);
1196                                         if (len > 0)
1197                                                 return len;
1198                                 }
1199                         }
1200                         if (!cur)
1201                                 return 0;
1202                 }
1203                 if (cur.pit() < cur.lastpit()) {
1204                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1205                         cur.forwardPar();
1206                 } else {
1207                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1208                         cur.pos() = cur.lastpos();
1209                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1210                         cur.forwardPos();
1211                 }
1212         }
1213         return 0;
1214 }
1215
1216
1217 /// Find the most backward consecutive match within same paragraph while searching backwards.
1218 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1219 {
1220         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1221         DocIterator tmp_cur = cur;
1222         int len = findAdvFinalize(tmp_cur, match);
1223         Inset & inset = cur.inset();
1224         for (; cur != cur_begin; cur.backwardPos()) {
1225                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1226                 DocIterator new_cur = cur;
1227                 new_cur.backwardPos();
1228                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1229                         break;
1230                 int new_len = findAdvFinalize(new_cur, match);
1231                 if (new_len == len)
1232                         break;
1233                 len = new_len;
1234         }
1235         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1236         return len;
1237 }
1238
1239
1240 /// Finds backwards
1241 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1242 {
1243         if (! cur)
1244                 return 0;
1245         // Backup of original position
1246         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1247         if (cur == cur_begin)
1248                 return 0;
1249         cur.backwardPos();
1250         DocIterator cur_orig(cur);
1251         bool pit_changed = false;
1252         do {
1253                 cur.pos() = 0;
1254                 bool found_match = match(cur, -1, false);
1255
1256                 if (found_match) {
1257                         if (pit_changed)
1258                                 cur.pos() = cur.lastpos();
1259                         else
1260                                 cur.pos() = cur_orig.pos();
1261                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1262                         DocIterator cur_prev_iter;
1263                         do {
1264                                 found_match = match(cur);
1265                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1266                                        << found_match << ", cur: " << cur);
1267                                 if (found_match)
1268                                         return findMostBackwards(cur, match);
1269
1270                                 // Stop if begin of document reached
1271                                 if (cur == cur_begin)
1272                                         break;
1273                                 cur_prev_iter = cur;
1274                                 cur.backwardPos();
1275                         } while (true);
1276                 }
1277                 if (cur == cur_begin)
1278                         break;
1279                 if (cur.pit() > 0)
1280                         --cur.pit();
1281                 else
1282                         cur.backwardPos();
1283                 pit_changed = true;
1284         } while (!theApp()->longOperationCancelled());
1285         return 0;
1286 }
1287
1288
1289 } // anonym namespace
1290
1291
1292 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1293                                  DocIterator const & cur, int len)
1294 {
1295         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1296                 return docstring());
1297         if (!opt.ignoreformat)
1298                 return latexifyFromCursor(cur, len);
1299         else
1300                 return stringifyFromCursor(cur, len);
1301 }
1302
1303
1304 FindAndReplaceOptions::FindAndReplaceOptions(
1305         docstring const & find_buf_name, bool casesensitive,
1306         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1307         docstring const & repl_buf_name, bool keep_case,
1308         SearchScope scope, SearchRestriction restr)
1309         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1310           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1311           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1312 {
1313 }
1314
1315
1316 namespace {
1317
1318
1319 /** Check if 'len' letters following cursor are all non-lowercase */
1320 static bool allNonLowercase(Cursor const & cur, int len)
1321 {
1322         pos_type beg_pos = cur.selectionBegin().pos();
1323         pos_type end_pos = cur.selectionBegin().pos() + len;
1324         if (len > cur.lastpos() + 1 - beg_pos) {
1325                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1326                 len = cur.lastpos() + 1 - beg_pos;
1327                 end_pos = beg_pos + len;
1328         }
1329         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1330                 if (isLowerCase(cur.paragraph().getChar(pos)))
1331                         return false;
1332         return true;
1333 }
1334
1335
1336 /** Check if first letter is upper case and second one is lower case */
1337 static bool firstUppercase(Cursor const & cur)
1338 {
1339         char_type ch1, ch2;
1340         pos_type pos = cur.selectionBegin().pos();
1341         if (pos >= cur.lastpos() - 1) {
1342                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1343                 return false;
1344         }
1345         ch1 = cur.paragraph().getChar(pos);
1346         ch2 = cur.paragraph().getChar(pos + 1);
1347         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1348         LYXERR(Debug::FIND, "firstUppercase(): "
1349                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1350                << ch2 << "(" << char(ch2) << ")"
1351                << ", result=" << result << ", cur=" << cur);
1352         return result;
1353 }
1354
1355
1356 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1357  **
1358  ** \fixme What to do with possible further paragraphs in replace buffer ?
1359  **/
1360 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1361 {
1362         ParagraphList::iterator pit = buffer.paragraphs().begin();
1363         LASSERT(pit->size() >= 1, /**/);
1364         pos_type right = pos_type(1);
1365         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1366         right = pit->size();
1367         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1368 }
1369
1370 } // anon namespace
1371
1372 ///
1373 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1374 {
1375         Cursor & cur = bv->cursor();
1376         if (opt.repl_buf_name == docstring())
1377                 return;
1378
1379         DocIterator sel_beg = cur.selectionBegin();
1380         DocIterator sel_end = cur.selectionEnd();
1381         if (&sel_beg.inset() != &sel_end.inset()
1382             || sel_beg.pit() != sel_end.pit()
1383             || sel_beg.idx() != sel_end.idx())
1384                 return;
1385         int sel_len = sel_end.pos() - sel_beg.pos();
1386         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1387                << ", sel_len: " << sel_len << endl);
1388         if (sel_len == 0)
1389                 return;
1390         LASSERT(sel_len > 0, return);
1391
1392         if (!matchAdv(sel_beg, sel_len))
1393                 return;
1394
1395         // Build a copy of the replace buffer, adapted to the KeepCase option
1396         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1397         ostringstream oss;
1398         repl_buffer_orig.write(oss);
1399         string lyx = oss.str();
1400         Buffer repl_buffer("", false);
1401         repl_buffer.setUnnamed(true);
1402         LASSERT(repl_buffer.readString(lyx), return);
1403         if (opt.keep_case && sel_len >= 2) {
1404                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1405                 if (cur.inTexted()) {
1406                         if (firstUppercase(cur))
1407                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1408                         else if (allNonLowercase(cur, sel_len))
1409                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1410                 }
1411         }
1412         cap::cutSelection(cur, false, false);
1413         if (cur.inTexted()) {
1414                 repl_buffer.changeLanguage(
1415                         repl_buffer.language(),
1416                         cur.getFont().language());
1417                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1418                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1419                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1420                                         repl_buffer.params().documentClassPtr(),
1421                                         bv->buffer().errorList("Paste"));
1422                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1423                 sel_len = repl_buffer.paragraphs().begin()->size();
1424         } else if (cur.inMathed()) {
1425                 odocstringstream ods;
1426                 otexstream os(ods);
1427                 OutputParams runparams(&repl_buffer.params().encoding());
1428                 runparams.nice = false;
1429                 runparams.flavor = OutputParams::LATEX;
1430                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1431                 runparams.dryrun = true;
1432                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1433                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1434                 docstring repl_latex = ods.str();
1435                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1436                 string s;
1437                 // false positive from coverity
1438                 // coverity[CHECKED_RETURN]
1439                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1440                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1441                 repl_latex = from_utf8(s);
1442                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1443                 MathData ar(cur.buffer());
1444                 asArray(repl_latex, ar, Parse::NORMAL);
1445                 cur.insert(ar);
1446                 sel_len = ar.size();
1447                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1448         }
1449         if (cur.pos() >= sel_len)
1450                 cur.pos() -= sel_len;
1451         else
1452                 cur.pos() = 0;
1453         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1454         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1455         bv->processUpdateFlags(Update::Force);
1456 }
1457
1458
1459 /// Perform a FindAdv operation.
1460 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1461 {
1462         DocIterator cur;
1463         int match_len = 0;
1464
1465         try {
1466                 MatchStringAdv matchAdv(bv->buffer(), opt);
1467                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1468                 if (length > 0)
1469                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1470                 findAdvReplace(bv, opt, matchAdv);
1471                 cur = bv->cursor();
1472                 if (opt.forward)
1473                         match_len = findForwardAdv(cur, matchAdv);
1474                 else
1475                         match_len = findBackwardsAdv(cur, matchAdv);
1476         } catch (...) {
1477                 // This may only be raised by lyx::regex()
1478                 bv->message(_("Invalid regular expression!"));
1479                 return false;
1480         }
1481
1482         if (match_len == 0) {
1483                 bv->message(_("Match not found!"));
1484                 return false;
1485         }
1486
1487         bv->message(_("Match found!"));
1488
1489         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1490         bv->putSelectionAt(cur, match_len, !opt.forward);
1491
1492         return true;
1493 }
1494
1495
1496 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1497 {
1498         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1499            << opt.casesensitive << ' '
1500            << opt.matchword << ' '
1501            << opt.forward << ' '
1502            << opt.expandmacros << ' '
1503            << opt.ignoreformat << ' '
1504            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1505            << opt.keep_case << ' '
1506            << int(opt.scope) << ' '
1507            << int(opt.restr);
1508
1509         LYXERR(Debug::FIND, "built: " << os.str());
1510
1511         return os;
1512 }
1513
1514
1515 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1516 {
1517         LYXERR(Debug::FIND, "parsing");
1518         string s;
1519         string line;
1520         getline(is, line);
1521         while (line != "EOSS") {
1522                 if (! s.empty())
1523                         s = s + "\n";
1524                 s = s + line;
1525                 if (is.eof())   // Tolerate malformed request
1526                         break;
1527                 getline(is, line);
1528         }
1529         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1530         opt.find_buf_name = from_utf8(s);
1531         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1532         is.get();       // Waste space before replace string
1533         s = "";
1534         getline(is, line);
1535         while (line != "EOSS") {
1536                 if (! s.empty())
1537                         s = s + "\n";
1538                 s = s + line;
1539                 if (is.eof())   // Tolerate malformed request
1540                         break;
1541                 getline(is, line);
1542         }
1543         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1544         opt.repl_buf_name = from_utf8(s);
1545         is >> opt.keep_case;
1546         int i;
1547         is >> i;
1548         opt.scope = FindAndReplaceOptions::SearchScope(i);
1549         is >> i;
1550         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1551
1552         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1553                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1554                << opt.scope << ' ' << opt.restr);
1555         return is;
1556 }
1557
1558 } // lyx namespace