]> git.lyx.org Git - features.git/blob - src/lyxfind.cpp
Advanced search with format: Prepare latex for find
[features.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 #include <map>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 namespace lyx {
61
62 namespace {
63
64 bool parse_bool(docstring & howto)
65 {
66         if (howto.empty())
67                 return false;
68         docstring var;
69         howto = split(howto, var, ' ');
70         return var == "1";
71 }
72
73
74 class MatchString : public binary_function<Paragraph, pos_type, int>
75 {
76 public:
77         MatchString(docstring const & str, bool cs, bool mw)
78                 : str(str), case_sens(cs), whole_words(mw)
79         {}
80
81         // returns true if the specified string is at the specified position
82         // del specifies whether deleted strings in ct mode will be considered
83         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
84         {
85                 return par.find(str, case_sens, whole_words, pos, del);
86         }
87
88 private:
89         // search string
90         docstring str;
91         // case sensitive
92         bool case_sens;
93         // match whole words only
94         bool whole_words;
95 };
96
97
98 int findForward(DocIterator & cur, MatchString const & match,
99                 bool find_del = true)
100 {
101         for (; cur; cur.forwardChar())
102                 if (cur.inTexted()) {
103                         int len = match(cur.paragraph(), cur.pos(), find_del);
104                         if (len > 0)
105                                 return len;
106                 }
107         return 0;
108 }
109
110
111 int findBackwards(DocIterator & cur, MatchString const & match,
112                   bool find_del = true)
113 {
114         while (cur) {
115                 cur.backwardChar();
116                 if (cur.inTexted()) {
117                         int len = match(cur.paragraph(), cur.pos(), find_del);
118                         if (len > 0)
119                                 return len;
120                 }
121         }
122         return 0;
123 }
124
125
126 bool searchAllowed(docstring const & str)
127 {
128         if (str.empty()) {
129                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
130                 return false;
131         }
132         return true;
133 }
134
135
136 bool findOne(BufferView * bv, docstring const & searchstr,
137              bool case_sens, bool whole, bool forward,
138              bool find_del = true, bool check_wrap = false)
139 {
140         if (!searchAllowed(searchstr))
141                 return false;
142
143         DocIterator cur = forward
144                 ? bv->cursor().selectionEnd()
145                 : bv->cursor().selectionBegin();
146
147         MatchString const match(searchstr, case_sens, whole);
148
149         int match_len = forward
150                 ? findForward(cur, match, find_del)
151                 : findBackwards(cur, match, find_del);
152
153         if (match_len > 0)
154                 bv->putSelectionAt(cur, match_len, !forward);
155         else if (check_wrap) {
156                 DocIterator cur_orig(bv->cursor());
157                 docstring q;
158                 if (forward)
159                         q = _("End of file reached while searching forward.\n"
160                           "Continue searching from the beginning?");
161                 else
162                         q = _("Beginning of file reached while searching backward.\n"
163                           "Continue searching from the end?");
164                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
165                         q, 0, 1, _("&Yes"), _("&No"));
166                 if (wrap_answer == 0) {
167                         if (forward) {
168                                 bv->cursor().clear();
169                                 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
170                         } else {
171                                 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
172                                 bv->cursor().backwardPos();
173                         }
174                         bv->clearSelection();
175                         if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
176                                 return true;
177                 }
178                 bv->cursor().setCursor(cur_orig);
179                 return false;
180         }
181
182         return match_len > 0;
183 }
184
185
186 int replaceAll(BufferView * bv,
187                docstring const & searchstr, docstring const & replacestr,
188                bool case_sens, bool whole)
189 {
190         Buffer & buf = bv->buffer();
191
192         if (!searchAllowed(searchstr) || buf.isReadonly())
193                 return 0;
194
195         DocIterator cur_orig(bv->cursor());
196
197         MatchString const match(searchstr, case_sens, whole);
198         int num = 0;
199
200         int const rsize = replacestr.size();
201         int const ssize = searchstr.size();
202
203         Cursor cur(*bv);
204         cur.setCursor(doc_iterator_begin(&buf));
205         int match_len = findForward(cur, match, false);
206         while (match_len > 0) {
207                 // Backup current cursor position and font.
208                 pos_type const pos = cur.pos();
209                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
210                 cur.recordUndo();
211                 int striked = ssize -
212                         cur.paragraph().eraseChars(pos, pos + match_len,
213                                                    buf.params().track_changes);
214                 cur.paragraph().insert(pos, replacestr, font,
215                                        Change(buf.params().track_changes
216                                               ? Change::INSERTED
217                                               : Change::UNCHANGED));
218                 for (int i = 0; i < rsize + striked; ++i)
219                         cur.forwardChar();
220                 ++num;
221                 match_len = findForward(cur, match, false);
222         }
223
224         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
225
226         cur_orig.fixIfBroken();
227         bv->setCursor(cur_orig);
228
229         return num;
230 }
231
232
233 // the idea here is that we are going to replace the string that
234 // is selected IF it is the search string.
235 // if there is a selection, but it is not the search string, then
236 // we basically ignore it. (FIXME We ought to replace only within
237 // the selection.)
238 // if there is no selection, then:
239 //  (i) if some search string has been provided, then we find it.
240 //      (think of how the dialog works when you hit "replace" the
241 //      first time.)
242 // (ii) if no search string has been provided, then we treat the
243 //      word the cursor is in as the search string. (why? i have no
244 //      idea.) but this only works in text?
245 //
246 // returns the number of replacements made (one, if any) and
247 // whether anything at all was done.
248 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
249                            docstring const & replacestr, bool case_sens,
250                            bool whole, bool forward, bool findnext)
251 {
252         Cursor & cur = bv->cursor();
253         bool found = false;
254         if (!cur.selection()) {
255                 // no selection, non-empty search string: find it
256                 if (!searchstr.empty()) {
257                         found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
258                         return make_pair(found, 0);
259                 }
260                 // empty search string
261                 if (!cur.inTexted())
262                         // bail in math
263                         return make_pair(false, 0);
264                 // select current word and treat it as the search string.
265                 // This causes a minor bug as undo will restore this selection,
266                 // which the user did not create (#8986).
267                 cur.innerText()->selectWord(cur, WHOLE_WORD);
268                 searchstr = cur.selectionAsString(false);
269         }
270
271         // if we still don't have a search string, report the error
272         // and abort.
273         if (!searchAllowed(searchstr))
274                 return make_pair(false, 0);
275
276         bool have_selection = cur.selection();
277         docstring const selected = cur.selectionAsString(false);
278         bool match =
279                 case_sens
280                 ? searchstr == selected
281                 : compare_no_case(searchstr, selected) == 0;
282
283         // no selection or current selection is not search word:
284         // just find the search word
285         if (!have_selection || !match) {
286                 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
287                 return make_pair(found, 0);
288         }
289
290         // we're now actually ready to replace. if the buffer is
291         // read-only, we can't, though.
292         if (bv->buffer().isReadonly())
293                 return make_pair(false, 0);
294
295         cap::replaceSelectionWithString(cur, replacestr);
296         if (forward) {
297                 cur.pos() += replacestr.length();
298                 LASSERT(cur.pos() <= cur.lastpos(),
299                         cur.pos() = cur.lastpos());
300         }
301         if (findnext)
302                 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
303
304         return make_pair(true, 1);
305 }
306
307 } // namespace
308
309
310 docstring const find2string(docstring const & search,
311                             bool casesensitive, bool matchword, bool forward)
312 {
313         odocstringstream ss;
314         ss << search << '\n'
315            << int(casesensitive) << ' '
316            << int(matchword) << ' '
317            << int(forward);
318         return ss.str();
319 }
320
321
322 docstring const replace2string(docstring const & replace,
323                                docstring const & search,
324                                bool casesensitive, bool matchword,
325                                bool all, bool forward, bool findnext)
326 {
327         odocstringstream ss;
328         ss << replace << '\n'
329            << search << '\n'
330            << int(casesensitive) << ' '
331            << int(matchword) << ' '
332            << int(all) << ' '
333            << int(forward) << ' '
334            << int(findnext);
335         return ss.str();
336 }
337
338
339 bool lyxfind(BufferView * bv, FuncRequest const & ev)
340 {
341         if (!bv || ev.action() != LFUN_WORD_FIND)
342                 return false;
343
344         //lyxerr << "find called, cmd: " << ev << endl;
345
346         // data is of the form
347         // "<search>
348         //  <casesensitive> <matchword> <forward>"
349         docstring search;
350         docstring howto = split(ev.argument(), search, '\n');
351
352         bool casesensitive = parse_bool(howto);
353         bool matchword     = parse_bool(howto);
354         bool forward       = parse_bool(howto);
355
356         return findOne(bv, search, casesensitive, matchword, forward, true, true);
357 }
358
359
360 bool lyxreplace(BufferView * bv,
361                 FuncRequest const & ev, bool has_deleted)
362 {
363         if (!bv || ev.action() != LFUN_WORD_REPLACE)
364                 return false;
365
366         // data is of the form
367         // "<search>
368         //  <replace>
369         //  <casesensitive> <matchword> <all> <forward> <findnext>"
370         docstring search;
371         docstring rplc;
372         docstring howto = split(ev.argument(), rplc, '\n');
373         howto = split(howto, search, '\n');
374
375         bool casesensitive = parse_bool(howto);
376         bool matchword     = parse_bool(howto);
377         bool all           = parse_bool(howto);
378         bool forward       = parse_bool(howto);
379         bool findnext      = howto.empty() ? true : parse_bool(howto);
380
381         bool update = false;
382
383         if (!has_deleted) {
384                 int replace_count = 0;
385                 if (all) {
386                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
387                         update = replace_count > 0;
388                 } else {
389                         pair<bool, int> rv =
390                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
391                         update = rv.first;
392                         replace_count = rv.second;
393                 }
394
395                 Buffer const & buf = bv->buffer();
396                 if (!update) {
397                         // emit message signal.
398                         buf.message(_("String not found."));
399                 } else {
400                         if (replace_count == 0) {
401                                 buf.message(_("String found."));
402                         } else if (replace_count == 1) {
403                                 buf.message(_("String has been replaced."));
404                         } else {
405                                 docstring const str =
406                                         bformat(_("%1$d strings have been replaced."), replace_count);
407                                 buf.message(str);
408                         }
409                 }
410         } else if (findnext) {
411                 // if we have deleted characters, we do not replace at all, but
412                 // rather search for the next occurence
413                 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
414                         update = true;
415                 else
416                         bv->message(_("String not found."));
417         }
418         return update;
419 }
420
421
422 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
423 {
424         for (; cur; cur.forwardPos())
425                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
426                         return true;
427
428         if (check_wrap) {
429                 DocIterator cur_orig(bv->cursor());
430                 docstring q = _("End of file reached while searching forward.\n"
431                           "Continue searching from the beginning?");
432                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
433                         q, 0, 1, _("&Yes"), _("&No"));
434                 if (wrap_answer == 0) {
435                         bv->cursor().clear();
436                         bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
437                         bv->clearSelection();
438                         cur.setCursor(bv->cursor().selectionBegin());
439                         if (findNextChange(bv, cur, false))
440                                 return true;
441                 }
442                 bv->cursor().setCursor(cur_orig);
443         }
444
445         return false;
446 }
447
448
449 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
450 {
451         for (cur.backwardPos(); cur; cur.backwardPos()) {
452                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
453                         return true;
454         }
455
456         if (check_wrap) {
457                 DocIterator cur_orig(bv->cursor());
458                 docstring q = _("Beginning of file reached while searching backward.\n"
459                           "Continue searching from the end?");
460                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
461                         q, 0, 1, _("&Yes"), _("&No"));
462                 if (wrap_answer == 0) {
463                         bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
464                         bv->cursor().backwardPos();
465                         bv->clearSelection();
466                         cur.setCursor(bv->cursor().selectionBegin());
467                         if (findPreviousChange(bv, cur, false))
468                                 return true;
469                 }
470                 bv->cursor().setCursor(cur_orig);
471         }
472
473         return false;
474 }
475
476
477 bool selectChange(Cursor & cur, bool forward)
478 {
479         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
480                 return false;
481         Change ch = cur.paragraph().lookupChange(cur.pos());
482
483         CursorSlice tip1 = cur.top();
484         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
485                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
486                 if (!ch2.isSimilarTo(ch))
487                         break;
488         }
489         CursorSlice tip2 = cur.top();
490         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
491                 tip2.backwardPos();
492                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
493                 if (!ch2.isSimilarTo(ch)) {
494                         // take a step forward to correctly set the selection
495                         tip2.forwardPos();
496                         break;
497                 }
498         }
499         if (forward)
500                 swap(tip1, tip2);
501         cur.top() = tip1;
502         cur.bv().mouseSetCursor(cur, false);
503         cur.top() = tip2;
504         cur.bv().mouseSetCursor(cur, true);
505         return true;
506 }
507
508
509 namespace {
510
511
512 bool findChange(BufferView * bv, bool forward)
513 {
514         Cursor cur(*bv);
515         cur.setCursor(forward ? bv->cursor().selectionEnd()
516                       : bv->cursor().selectionBegin());
517         forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
518         return selectChange(cur, forward);
519 }
520
521 } // namespace
522
523 bool findNextChange(BufferView * bv)
524 {
525         return findChange(bv, true);
526 }
527
528
529 bool findPreviousChange(BufferView * bv)
530 {
531         return findChange(bv, false);
532 }
533
534
535
536 namespace {
537
538 typedef vector<pair<string, string> > Escapes;
539
540 /// A map of symbols and their escaped equivalent needed within a regex.
541 /// @note Beware of order
542 Escapes const & get_regexp_escapes()
543 {
544         typedef std::pair<std::string, std::string> P;
545
546         static Escapes escape_map;
547         if (escape_map.empty()) {
548                 escape_map.push_back(P("$", "_x_$"));
549                 escape_map.push_back(P("{", "_x_{"));
550                 escape_map.push_back(P("}", "_x_}"));
551                 escape_map.push_back(P("[", "_x_["));
552                 escape_map.push_back(P("]", "_x_]"));
553                 escape_map.push_back(P("(", "_x_("));
554                 escape_map.push_back(P(")", "_x_)"));
555                 escape_map.push_back(P("+", "_x_+"));
556                 escape_map.push_back(P("*", "_x_*"));
557                 escape_map.push_back(P(".", "_x_."));
558                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
559                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
560                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
561                 escape_map.push_back(P("_x_", "\\"));
562         }
563         return escape_map;
564 }
565
566 /// A map of lyx escaped strings and their unescaped equivalent.
567 Escapes const & get_lyx_unescapes()
568 {
569         typedef std::pair<std::string, std::string> P;
570
571         static Escapes escape_map;
572         if (escape_map.empty()) {
573                 escape_map.push_back(P("\\%", "%"));
574                 escape_map.push_back(P("\\mathcircumflex ", "^"));
575                 escape_map.push_back(P("\\mathcircumflex", "^"));
576                 escape_map.push_back(P("\\backslash ", "\\"));
577                 escape_map.push_back(P("\\backslash", "\\"));
578                 escape_map.push_back(P("\\\\{", "_x_<"));
579                 escape_map.push_back(P("\\\\}", "_x_>"));
580                 escape_map.push_back(P("\\sim ", "~"));
581                 escape_map.push_back(P("\\sim", "~"));
582         }
583         return escape_map;
584 }
585
586 /// A map of escapes turning a regexp matching text to one matching latex.
587 Escapes const & get_regexp_latex_escapes()
588 {
589         typedef std::pair<std::string, std::string> P;
590
591         static Escapes escape_map;
592         if (escape_map.empty()) {
593                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
594                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
595                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
596                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
597                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
598                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
599                 escape_map.push_back(P("%", "\\\\\\%"));
600         }
601         return escape_map;
602 }
603
604 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
605  ** the found occurrence were escaped.
606  **/
607 string apply_escapes(string s, Escapes const & escape_map)
608 {
609         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
610         Escapes::const_iterator it;
611         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
612 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
613                 unsigned int pos = 0;
614                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
615                         s.replace(pos, it->first.length(), it->second);
616                         LYXERR(Debug::FIND, "After escape: " << s);
617                         pos += it->second.length();
618 //                      LYXERR(Debug::FIND, "pos: " << pos);
619                 }
620         }
621         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
622         return s;
623 }
624
625
626 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
627 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
628 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
629 string escape_for_regex(string s, bool match_latex)
630 {
631         size_t pos = 0;
632         while (pos < s.size()) {
633                 size_t new_pos = s.find("\\regexp{", pos);
634                 if (new_pos == string::npos)
635                         new_pos = s.size();
636                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
637                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
638                 LYXERR(Debug::FIND, "t [lyx]: " << t);
639                 t = apply_escapes(t, get_regexp_escapes());
640                 LYXERR(Debug::FIND, "t [rxp]: " << t);
641                 s.replace(pos, new_pos - pos, t);
642                 new_pos = pos + t.size();
643                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
644                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
645                 if (new_pos == s.size())
646                         break;
647                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
648                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
649                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
650                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
651                 LYXERR(Debug::FIND, "t in regexp      : " << t);
652                 t = apply_escapes(t, get_lyx_unescapes());
653                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
654                 if (match_latex) {
655                         t = apply_escapes(t, get_regexp_latex_escapes());
656                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
657                 }
658                 if (end_pos == s.size()) {
659                         s.replace(new_pos, end_pos - new_pos, t);
660                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
661                         break;
662                 }
663                 s.replace(new_pos, end_pos + 13 - new_pos, t);
664                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
665                 pos = new_pos + t.size();
666                 LYXERR(Debug::FIND, "pos: " << pos);
667         }
668         return s;
669 }
670
671
672 /// Wrapper for lyx::regex_replace with simpler interface
673 bool regex_replace(string const & s, string & t, string const & searchstr,
674                    string const & replacestr)
675 {
676         lyx::regex e(searchstr, regex_constants::ECMAScript);
677         ostringstream oss;
678         ostream_iterator<char, char> it(oss);
679         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
680         // tolerate t and s be references to the same variable
681         bool rv = (s != oss.str());
682         t = oss.str();
683         return rv;
684 }
685
686
687 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
688  **
689  ** Verify that closed braces exactly match open braces. This avoids that, for example,
690  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
691  **
692  ** @param unmatched
693  ** Number of open braces that must remain open at the end for the verification to succeed.
694  **/
695 bool braces_match(string::const_iterator const & beg,
696                   string::const_iterator const & end,
697                   int unmatched = 0)
698 {
699         int open_pars = 0;
700         string::const_iterator it = beg;
701         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
702         for (; it != end; ++it) {
703                 // Skip escaped braces in the count
704                 if (*it == '\\') {
705                         ++it;
706                         if (it == end)
707                                 break;
708                 } else if (*it == '{') {
709                         ++open_pars;
710                 } else if (*it == '}') {
711                         if (open_pars == 0) {
712                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
713                                 return false;
714                         } else
715                                 --open_pars;
716                 }
717         }
718         if (open_pars != unmatched) {
719                 LYXERR(Debug::FIND, "Found " << open_pars
720                        << " instead of " << unmatched
721                        << " unmatched open braces at the end of count");
722                 return false;
723         }
724         LYXERR(Debug::FIND, "Braces match as expected");
725         return true;
726 }
727
728
729 /** The class performing a match between a position in the document and the FindAdvOptions.
730  **/
731 class MatchStringAdv {
732 public:
733         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
734
735         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
736          ** constructor as opt.search, under the opt.* options settings.
737          **
738          ** @param at_begin
739          **     If set, then match is searched only against beginning of text starting at cur.
740          **     If unset, then match is searched anywhere in text starting at cur.
741          **
742          ** @return
743          ** The length of the matching text, or zero if no match was found.
744          **/
745         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
746
747 public:
748         /// buffer
749         lyx::Buffer * p_buf;
750         /// first buffer on which search was started
751         lyx::Buffer * const p_first_buf;
752         /// options
753         FindAndReplaceOptions const & opt;
754
755 private:
756         /// Auxiliary find method (does not account for opt.matchword)
757         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
758
759         /** Normalize a stringified or latexified LyX paragraph.
760          **
761          ** Normalize means:
762          ** <ul>
763          **   <li>if search is not casesensitive, then lowercase the string;
764          **   <li>remove any newline at begin or end of the string;
765          **   <li>replace any newline in the middle of the string with a simple space;
766          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
767          ** </ul>
768          **
769          ** @todo Normalization should also expand macros, if the corresponding
770          ** search option was checked.
771          **/
772         string normalize(docstring const & s, bool hack_braces) const;
773         // normalized string to search
774         string par_as_string;
775         // regular expression to use for searching
776         lyx::regex regexp;
777         // same as regexp, but prefixed with a ".*"
778         lyx::regex regexp2;
779         // leading format material as string
780         string lead_as_string;
781         // par_as_string after removal of lead_as_string
782         string par_as_string_nolead;
783         // unmatched open braces in the search string/regexp
784         int open_braces;
785         // number of (.*?) subexpressions added at end of search regexp for closing
786         // environments, math mode, styles, etc...
787         int close_wildcards;
788         // Are we searching with regular expressions ?
789         bool use_regexp;
790 };
791
792
793 static docstring buffer_to_latex(Buffer & buffer)
794 {
795         OutputParams runparams(&buffer.params().encoding());
796         odocstringstream ods;
797         otexstream os(ods);
798         runparams.nice = true;
799         runparams.flavor = OutputParams::LATEX;
800         runparams.linelen = 80; //lyxrc.plaintext_linelen;
801         // No side effect of file copying and image conversion
802         runparams.dryrun = true;
803         runparams.for_search = true;
804         pit_type const endpit = buffer.paragraphs().size();
805         for (pit_type pit = 0; pit != endpit; ++pit) {
806                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
807                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
808         }
809         return ods.str();
810 }
811
812
813 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
814 {
815         docstring str;
816         if (!opt.ignoreformat) {
817                 str = buffer_to_latex(buffer);
818         } else {
819                 OutputParams runparams(&buffer.params().encoding());
820                 runparams.nice = true;
821                 runparams.flavor = OutputParams::LATEX;
822                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
823                 runparams.dryrun = true;
824                 runparams.for_search = true;
825                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
826                         Paragraph const & par = buffer.paragraphs().at(pit);
827                         LYXERR(Debug::FIND, "Adding to search string: '"
828                                << par.asString(pos_type(0), par.size(),
829                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
830                                                &runparams)
831                                << "'");
832                         str += par.asString(pos_type(0), par.size(),
833                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
834                                             &runparams);
835                 }
836         }
837         return str;
838 }
839
840
841 /// Return separation pos between the leading material and the rest
842 static size_t identifyLeading(string const & s)
843 {
844         string t = s;
845         // @TODO Support \item[text]
846         // Kornel: Added textsl, textsf, textit, texttt and noun
847         // + allow to seach for colored text too
848         while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)\\{", "")
849                || regex_replace(t, t, REGEX_BOS "\\$", "")
850                || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
851                || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
852                || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
853                ;
854         LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
855         return s.find(t);
856 }
857
858 /*
859  * Given a latexified string, retrieve some handled features
860  * The features of the regex will later be compared with the features
861  * of the searched text. If the regex features are not a
862  * subset of the analized, then, in not format ignoring search
863  * we can early stop the search in the relevant inset.
864  */
865 typedef map<string, bool> Features;
866
867 static Features identifyFeatures(string const & s)
868 {
869         static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
870         static regex const valid("^(((emph|noun|text(bf|sl|sf|it|tt)|(textcolor|foreignlanguage)\\{[a-z]+\\})|item |(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)$");
871         smatch sub;
872         bool displ = true;
873         Features info;
874
875         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
876                 sub = *it;
877                 if (displ) {
878                         if (sub.str(1).compare("regexp") == 0) {
879                                 displ = false;
880                                 continue;
881                         }
882                         string token = sub.str(1);
883                         smatch sub2;
884                         if (regex_match(token, sub2, valid)) {
885                                 info[token] = true;
886                         }
887                         else {
888                                 // ignore
889                         }
890                 }
891                 else {
892                         if (sub.str(1).compare("endregexp") == 0) {
893                                 displ = true;
894                                 continue;
895                         }
896                 }
897         }
898         return(info);
899 }
900
901 /*
902  * Faster search for the related closing parenthesis
903  */
904  static int findclosing(string p, int start, int end)
905 {
906         int skip = 0;
907         int depth = 0;
908         int lastunclosed = start-1;
909         for (int i = start; i < end; i += 1 + skip) {
910                 char c;
911                 c = p[i];
912                 skip = 0;
913                 if (c == '\\') skip = 1;
914                 else if (c == '{') {
915                   depth++;
916                   lastunclosed = i;
917                 }
918                 else if (c == '}') {
919                         if (depth == 0) return(i);
920                         --depth;
921                 }
922         }
923         return(0 - lastunclosed);
924 }
925
926 /*
927  * Discard any info for char sizes for now.
928  */
929 static string removefontinfo(string par)
930 {
931         // Remove fontsizes, inputencoding
932         smatch sub;
933         list <string> fpars;
934         static regex const sizescodings("(\\\\(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|inputencoding\\{[^\\}]*})(\b|(\\{(\\{\\})?\\})?(%\\n)?))");
935         for (sregex_iterator it(par.begin(), par.end(), sizescodings), end; it != end; ++it) {
936                 sub = *it;
937                 string token = sub.str(1);
938                 fpars.push_back(token);
939         }
940         for (list<string>::const_iterator li = fpars.begin(); li != fpars.end(); ++li) {
941                 string token = *li;
942                 int f;
943                 int firstpos = 0;
944                 int ic; // Position of closing part e.g. '}'
945                 while ((f = par.find(token, firstpos)) >= 0) {
946                         size_t ssize = token.length();
947                         int parcount = 0;       // how many '{}' can be removed
948                         if (f == 0)
949                                 ic = -1;
950                         else {
951                                 if (par[f-1] != '{')
952                                         ic = -1;
953                                 else {
954                                         // here '{' preceedes
955                                         ic = findclosing(par, f + ssize, par.length());
956                                         if (f == 1)
957                                                 parcount = 1;
958                                         else if ((f == 2) && (par[f-2] == '{')) {
959                                                 if ((ic < 0) || (par[ic+1] == '}'))
960                                                         parcount = 2;
961                                                 else
962                                                         parcount = 1;
963                                         } else while (f > parcount + 1) {
964                                                 if (par[f-2-parcount] != '{')
965                                                         break;
966                                                 parcount++;
967                                                 if ((ic > 0) && (par[ic+parcount] != '}'))
968                                                         break;
969                                         }
970                                 }
971                         }
972                         firstpos = f;
973
974                         if (ic < 0)
975                                 ic = par.length() - parcount;
976                         par = par.substr(0, f-parcount) + par.substr(f+ssize, ic+parcount-f-ssize) + par.substr(ic+parcount);
977                 }
978         }
979         return(par);
980 }
981
982
983 class LangInfo {
984   public:
985     enum Type {
986       Invalid,
987       Valid,
988       LastValid,
989     };
990     Type valid;
991
992     /*LangInfo(LangInfo &orig) :
993         par(orig.par),
994         maxoffset(orig.maxoffset),
995         search(orig.search) {valid = Invalid;}
996     */
997     LangInfo(string par, string search1 = "", int start = 0, int end = -1)
998       : par(par),
999       _tokenend(0),
1000       _dataEnd(0),
1001       actualdeptindex(0)
1002       {
1003       valid = Invalid;
1004       _tokenstart = start;
1005       if (end > int(par.length())) {
1006         maxoffset = par.length();
1007       }
1008       else if (end > 0)
1009         maxoffset = end;
1010       else
1011         maxoffset = par.length();
1012       if (!search1.empty())
1013         _search = search1;
1014     }
1015     bool nextInfo();    // of the same type, from the last start in the same reagion
1016     bool firstInfo(string search, int datastart);
1017     void setDataEnd(int value);
1018     void setDataStart(int value);
1019     int getDataStart() { return _dataStart;};
1020     string name() { return _search;};
1021     string lasttoken() { if (valid == Valid) return _foundtoken; else return "";};
1022     int getStart() { return _tokenstart;};
1023     int getTokenEnd() { return _tokenend;};
1024     int getEnd() { return _dataEnd;};
1025     bool isValid() { return (valid == Valid); };
1026     void process(ostringstream &os);
1027     void output(ostringstream &os, int);
1028     void addIntervall(int upper);
1029     void addIntervall(int low, int upper); /* if explicit */
1030     void handleParentheses(int lastpos);
1031     string show(int lastpos);
1032   private:
1033     string par;
1034     string _search;
1035     string _foundtoken;
1036     int _tokenstart;
1037     int _tokenend;
1038     int _dataStart;
1039     int _dataEnd;
1040     bool atEnd;
1041     size_t maxoffset;
1042     int depts[20];
1043     int closes[20];
1044     int actualdeptindex;
1045     int ignoreIntervalls[10][2];
1046     int ignoreidx;
1047 };
1048
1049 void LangInfo::setDataEnd(int dataend)
1050 {
1051   if (dataend < _tokenend) {
1052     _dataEnd = _tokenend;
1053     // cout << "Wrong data start, too low\n";
1054   }
1055   else if (size_t(dataend) > par.length()) {
1056     // cout << "Wrong data start, too high\n";
1057     _dataEnd = par.length();
1058   }
1059   else
1060     _dataEnd = dataend;
1061 }
1062
1063 void LangInfo::setDataStart(int datastart)
1064 {
1065   if (datastart < _tokenend) {
1066     _dataStart = _tokenend;
1067     // cout << "Wrong data start, too low\n";
1068   }
1069   else if (size_t(datastart) > par.length()) {
1070     // cout << "Wrong data start, too high\n";
1071     _dataStart = par.length();
1072   }
1073   else
1074     _dataStart = datastart;
1075   //cout << "found entry at " << _tokenstart << "\n";
1076   actualdeptindex = 1;                  /* == Number of open brases */
1077   depts[0] = _dataStart;
1078   closes[0] = -1;
1079   depts[1] = _dataStart;
1080   ignoreidx = 0;
1081   ignoreIntervalls[ignoreidx][0] = _dataStart;
1082   if ((par[_dataStart] == '{') && (par[_dataStart+1] == '}')) {
1083     // First candidates to be ignored
1084     ignoreIntervalls[ignoreidx][1] = _dataStart+2;
1085   }
1086   else
1087     ignoreIntervalls[ignoreidx][1] = _dataStart;
1088 }
1089
1090 void LangInfo::handleParentheses(int lastpos)
1091 {
1092   int skip = 0;
1093   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1094     char c;
1095     c = par[i];
1096     skip = 0;
1097     if (c == '\\') skip = 1;
1098     else if (c == '{') {
1099       actualdeptindex++;
1100       depts[actualdeptindex] = i+1;
1101       closes[actualdeptindex] = -1;
1102     }
1103     else if (c == '}') {
1104       if (actualdeptindex <= 0) {
1105         LYXERR0("ERROR ERROR ERROR"); /* should never happen! */
1106       }
1107       else {
1108         closes[actualdeptindex] = i+1;
1109         actualdeptindex--;
1110       }
1111     }
1112   }
1113 }
1114
1115 void LangInfo::addIntervall(int low, int upper)
1116 {
1117   int idx;
1118   if (low == upper) return;
1119   for (idx = ignoreidx+1; idx > 0; --idx) {
1120     if (low > ignoreIntervalls[idx-1][1]) {
1121       break;
1122     }
1123   }
1124   if (idx > ignoreidx) {
1125     ignoreIntervalls[idx][0] = low;
1126     ignoreIntervalls[idx][1] = upper;
1127   }
1128   else {
1129     // Expand only if one of the new bounds is inside the interwall
1130     if (((low <= ignoreIntervalls[idx][1]) && (low >= ignoreIntervalls[idx][0])) ||
1131         ((upper <= ignoreIntervalls[idx][1]) && (upper >= ignoreIntervalls[idx][0]))) {
1132       if (low < ignoreIntervalls[idx][0])
1133         ignoreIntervalls[idx][0] = low;
1134       if (upper > ignoreIntervalls[idx][1])
1135         ignoreIntervalls[idx][1] = upper;
1136     }
1137   }
1138   ignoreidx = idx;                      /* because upper is in all cases bigger */
1139 }
1140
1141 void LangInfo::addIntervall(int upper)
1142 {
1143   int low;
1144   if (actualdeptindex >= 0)
1145     low = depts[actualdeptindex];   /*  the position of last unclosed '{' */
1146   else {
1147     LYXERR0("ERROR ERROR ERROR2");
1148     low = upper;
1149   }
1150   addIntervall(low, upper);
1151 }
1152
1153 string LangInfo::show(int lastpos)
1154 {
1155   ostringstream os;
1156
1157   os << par.substr(_tokenstart, _tokenend - _tokenstart);
1158   int idx = 0;
1159   for (int i = _dataStart; i < lastpos;) {
1160     if (i <= ignoreIntervalls[idx][0]) {
1161       os << par.substr(i, ignoreIntervalls[idx][0] - i);
1162       i = ignoreIntervalls[idx][1];
1163     }
1164     idx++;
1165     if (idx > ignoreidx) {
1166       os << par.substr(i, lastpos-i);
1167       break;
1168     }
1169   }
1170   for (int i = actualdeptindex; i > 0; --i)
1171     os << "}";
1172   return os.str();
1173 }
1174
1175 void LangInfo::output(ostringstream &os, int lastpos)
1176 {
1177   // get number of chars to output
1178   int idx = 0;                          /* int intervalls */
1179   int count = 0;
1180   for (int i = _dataStart; i < lastpos;) {
1181     if (i <= ignoreIntervalls[idx][0]) {
1182       count += ignoreIntervalls[idx][0] - i;
1183       i = ignoreIntervalls[idx][1];
1184     }
1185     idx++;
1186     if (idx > ignoreidx) {
1187       count += lastpos-i;
1188       break;
1189     }
1190   }
1191   //cout << "Number of output chars would be " << count + actualdeptindex << "\n";
1192   if (count > 0) {
1193     // Now the acual data
1194     os << par.substr(_tokenstart, _tokenend - _tokenstart);
1195     idx = 0;
1196     for (int i = _dataStart; i < lastpos;) {
1197       if (i <= ignoreIntervalls[idx][0]) {
1198         os << par.substr(i, ignoreIntervalls[idx][0] - i);
1199         i = ignoreIntervalls[idx][1];
1200       }
1201       idx++;
1202       if (idx > ignoreidx) {
1203         os << par.substr(i, lastpos-i);
1204         break;
1205       }
1206     }
1207     for (int i = actualdeptindex; i > 0; --i)
1208       os << "}";
1209   }
1210   handleParentheses(lastpos);
1211 }
1212
1213 bool LangInfo::nextInfo()
1214 {
1215   int start = _tokenstart;
1216
1217   // cout << par << "\n";
1218   if (valid == Invalid)
1219     _dataEnd = _tokenstart;
1220   else if (valid == LastValid)
1221     return false;
1222   // cout << "Start search at " << _tokenclose << " for \"" << _search << "\n";
1223   size_t foundstart = par.find(_search, _dataEnd);
1224   if (foundstart == string::npos) {
1225     if (valid == Valid)
1226       valid = LastValid;
1227     return false;                      // not found
1228   }
1229   if (foundstart >= maxoffset)
1230     return false;
1231   start = foundstart;
1232   int closelang = findclosing(par, start + _search.length(), maxoffset);
1233   if (closelang < 0)
1234     return false;
1235   if (size_t(closelang) >= maxoffset)
1236     return false;
1237   if (par[closelang] != '}')
1238     return false;
1239   valid = Valid;
1240   _foundtoken = par.substr(start, closelang - start + 2);
1241   _tokenstart = start;
1242   _tokenend = closelang+2;
1243   setDataStart(_tokenend);
1244   closelang = findclosing(par, _dataStart, maxoffset);
1245   if (closelang < 0) {
1246     _dataEnd = maxoffset;
1247     atEnd = true;
1248   }
1249   else {
1250     _dataEnd = closelang;
1251     atEnd = false;
1252   }
1253   return true;
1254 }
1255
1256 bool LangInfo::firstInfo(string search1, int datastart)
1257 {
1258   if (!search1.empty()) {
1259     if (_search.compare(search1) != 0) {
1260       _tokenstart = datastart;
1261       _search = search1;
1262       valid = Invalid;
1263     }
1264   }
1265   return nextInfo();
1266 }
1267
1268 void LangInfo::process(ostringstream &os)
1269 {
1270   LangInfo color(*this);
1271   (void) color.firstInfo("\\textcolor{", _dataStart);
1272   while (color.isValid() && (color.getStart() < _dataEnd)) {
1273     bool isEmpty = false;
1274     if (color.getDataStart() == color.getEnd()) {
1275       // Empty, e.g. par[color.getDataStart()] == '}'
1276       isEmpty = true;
1277     }
1278     else if ((par[color.getDataStart()] == '{') && (par[color.getDataStart()+1] == '}')) {
1279       // color starts with '{}', discard it
1280       if (color.getDataStart()+2 == color.getEnd())
1281         isEmpty = true;
1282       else {
1283         // discard the first '{}'
1284         addIntervall(color.getDataStart(), color.getDataStart()+2);
1285       }
1286     }
1287     if (isEmpty) {
1288       // it is emty, so ignore and go to next color
1289       addIntervall(color.getStart(), color.getEnd()+1);
1290     }
1291     else {
1292       if (par[color.getStart()-1] != '{') {
1293         output(os, color.getStart());
1294         addIntervall(color.getStart());
1295       }
1296       // Check if color empty
1297       output(os, color.getEnd()+1);
1298       addIntervall(color.getEnd()+1);
1299     }
1300     for (int i = color.getEnd()+1; par[i] == '}'; i++) {
1301       handleParentheses(i+1);
1302       addIntervall(i+1);
1303     }
1304     color.nextInfo();
1305   }
1306   if (par[_dataEnd] != '}')
1307     output(os, _dataEnd-1);
1308   else
1309     output(os, _dataEnd);
1310 }
1311
1312 /*
1313  * Called only if the par starts with lang spec
1314  */
1315
1316 string splitForColors(string par) {
1317   ostringstream os;
1318   LangInfo firstLanguage(par, "\\foreignlanguage{");
1319   if (firstLanguage.firstInfo("\\foreignlanguage{", 0)) {
1320     LangInfo nextLanguage(firstLanguage);
1321     nextLanguage.setDataEnd(firstLanguage.getDataStart());
1322     if (nextLanguage.firstInfo("\\foreignlanguage{", firstLanguage.getTokenEnd())) {
1323       firstLanguage.setDataEnd(nextLanguage.getStart());
1324     }
1325     firstLanguage.process(os);
1326     while (nextLanguage.isValid()) {
1327       nextLanguage.process(os);
1328       // To handle the gap, we need the end of last languuage to start of next
1329       int gapstart = nextLanguage.getEnd()+1;
1330       int gapend;
1331       nextLanguage.nextInfo();
1332       if (nextLanguage.isValid())
1333         gapend = nextLanguage.getStart();
1334       else
1335         gapend = par.length();
1336       // Now handle the gap, if there is one
1337       if (gapend > gapstart) {
1338         // cout << "Gap found, size = " << gapend - gapstart << "\n";
1339         firstLanguage.setDataEnd(gapend);
1340         firstLanguage.setDataStart(gapstart);
1341         firstLanguage.process(os);
1342       }
1343     }
1344   }
1345   string s = os.str();
1346   return s;
1347 }
1348
1349 /*
1350  * Try to unify the language specs in the latexified text.
1351  * Resulting modified string is set to "", if
1352  * the searched tex does not contain all the features in the search pattern
1353  */
1354 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
1355 {
1356         static Features regex_f;
1357         static int missed = 0;
1358         static bool regex_with_format = false;
1359
1360         int parlen = par.length();
1361
1362         while ((parlen > 0) && (par[parlen-1] == '\n')) {
1363                 parlen--;
1364         }
1365         string result = removefontinfo(par.substr(0, parlen));
1366         result = splitForColors(result);
1367         LYXERR(Debug::FIND, "Converted: \"" << result << "\"");
1368         bool handle_colors = false;
1369         if (from_regex) {
1370                 missed = 0;
1371                 if (withformat) {
1372                         regex_f = identifyFeatures(result);
1373                         string features = "";
1374                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1375                                 string a = it->first;
1376                                 regex_with_format = true;
1377                                 if (a.compare(0,10,"textcolor{") == 0)
1378                                   handle_colors = true;
1379                                 features += " " + a;
1380                                 // LYXERR0("Identified regex format:" << a);
1381                         }
1382                         LYXERR(Debug::FIND, "Identified Features" << features);
1383
1384                 }
1385         } else if (regex_with_format) {
1386                 Features info = identifyFeatures(result);
1387                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1388                         string a = it->first;
1389                         bool b = it->second;
1390                         if (b && ! info[a]) {
1391                                 missed++;
1392                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1393                                 return("");
1394                         }
1395                         else if (a.compare(0,10,"textcolor{") == 0)
1396                                 handle_colors = true;
1397                 }
1398         }
1399         else {
1400                 // LYXERR0("No regex formats");
1401         }
1402         // remove possible disturbing macros
1403         while (regex_replace(result, result, "\\\\(noindent )", ""))
1404                 ;
1405         // Either not found language spec,or is single and closed spec or empty
1406         // to be removed
1407         // [a-z+]par
1408         static regex const parreg("((\\n)?\\\\[a-z]+par)\\{");
1409
1410         list <string> pars;
1411         smatch sub;
1412         for (sregex_iterator it(result.begin(), result.end(), parreg), end; it != end; ++it) {
1413                 sub = *it;
1414                 string token = sub.str(1);
1415                 pars.push_back(token);
1416         }
1417         for (list<string>::const_iterator li = pars.begin(); li != pars.end(); ++li) {
1418                 string token = *li;
1419                 int ti = result.find(token);
1420                 int tokensize = token.size() + 1;
1421                 if (ti >= 0) {
1422                         int tc = findclosing(result, ti + tokensize, result.size());
1423                         if (tc > 0)
1424                                 result = result.substr(0, ti) + result.substr(ti + tokensize, tc - ti -tokensize) + result.substr(tc+1);
1425
1426                 }
1427         }
1428         if (handle_colors) {
1429           while (regex_replace(result, result, "(\\{\\\\textcolor\\{[a-z]+\\}\\{)\\s*\\{\\}\\s*", "$1"));
1430           while (regex_replace(result, result, "\\{\\\\textcolor\\{[a-z]+\\}\\{\\s*\\}\\s*\\}", ""));
1431         }
1432         return(result);
1433 }
1434
1435
1436 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1437 static int identifyClosing(string & t)
1438 {
1439         int open_braces = 0;
1440         do {
1441                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1442                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1443                         continue;
1444                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1445                         continue;
1446                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1447                         continue;
1448                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1449                         ++open_braces;
1450                         continue;
1451                 }
1452                 break;
1453         } while (true);
1454         return open_braces;
1455 }
1456
1457
1458 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1459         : p_buf(&buf), p_first_buf(&buf), opt(opt)
1460 {
1461         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1462         docstring const & ds = stringifySearchBuffer(find_buf, opt);
1463         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1464         // When using regexp, braces are hacked already by escape_for_regex()
1465         par_as_string = normalize(ds, !use_regexp);
1466         open_braces = 0;
1467         close_wildcards = 0;
1468
1469         size_t lead_size = 0;
1470         // correct the language settings
1471         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1472         if (opt.ignoreformat) {
1473                 if (!use_regexp) {
1474                         // if par_as_string_nolead were emty,
1475                         // the following call to findAux will always *find* the string
1476                         // in the checked data, and thus always using the slow
1477                         // examining of the current text part.
1478                         par_as_string_nolead = par_as_string;
1479                 }
1480         } else {
1481                 lead_size = identifyLeading(par_as_string);
1482                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1483                 lead_as_string = par_as_string.substr(0, lead_size);
1484                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1485         }
1486
1487         if (!use_regexp) {
1488                 open_braces = identifyClosing(par_as_string);
1489                 identifyClosing(par_as_string_nolead);
1490                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1491                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1492         } else {
1493                 string lead_as_regexp;
1494                 if (lead_size > 0) {
1495                         // @todo No need to search for \regexp{} insets in leading material
1496                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1497                         par_as_string = par_as_string_nolead;
1498                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1499                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1500                 }
1501                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1502                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1503                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1504                 if (
1505                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1506                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1507                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1508                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1509                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1510                         || regex_replace(par_as_string, par_as_string,
1511                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1512                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1513                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1514                         ) {
1515                         ++close_wildcards;
1516                 }
1517                 if (!opt.ignoreformat) {
1518                         // Remove extra '\}' at end
1519                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1520                                 open_braces++;
1521                         }
1522                         // save '\.'
1523                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1524                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1525                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1526                         // replace '[^...]' with '[^...\}\{\\]'
1527                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1528                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1529                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1530                         // restore '\.'
1531                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1532                 }
1533                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1534                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1535                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
1536                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1537
1538                 // If entered regexp must match at begin of searched string buffer
1539                 // Kornel: Added parentheses to use $1 for size of the leading string
1540                 string regexp_str;
1541                 string regexp2_str;
1542                 {
1543                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1544                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
1545                         // so the convert has no effect in that case
1546                         for (int i = 8; i > 0; --i) {
1547                                 string orig = "\\\\" + std::to_string(i);
1548                                 string dest = "\\" + std::to_string(i+1);
1549                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
1550                         }
1551                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1552                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1553                 }
1554                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1555                 regexp = lyx::regex(regexp_str);
1556
1557                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1558                 regexp2 = lyx::regex(regexp2_str);
1559         }
1560 }
1561
1562
1563 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1564 {
1565         if (at_begin &&
1566                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1567                 return 0;
1568
1569         docstring docstr = stringifyFromForSearch(opt, cur, len);
1570         string str = normalize(docstr, true);
1571         if (str.empty()) return(-1);
1572         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
1573         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1574
1575         if (use_regexp) {
1576                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1577                 regex const *p_regexp;
1578                 regex_constants::match_flag_type flags;
1579                 if (at_begin) {
1580                         flags = regex_constants::match_continuous;
1581                         p_regexp = &regexp;
1582                 } else {
1583                         flags = regex_constants::match_default;
1584                         p_regexp = &regexp2;
1585                 }
1586                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1587                 if (re_it == sregex_iterator())
1588                         return 0;
1589                 match_results<string::const_iterator> const & m = *re_it;
1590
1591                 if (0) { // Kornel Benko: DO NOT CHECKK
1592                         // Check braces on the segment that matched the entire regexp expression,
1593                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
1594                         if (!braces_match(m[0].first, m[0].second, open_braces))
1595                                 return 0;
1596                 }
1597
1598                 // Check braces on segments that matched all (.*?) subexpressions,
1599                 // except the last "padding" one inserted by lyx.
1600                 for (size_t i = 1; i < m.size() - 1; ++i)
1601                         if (!braces_match(m[i].first, m[i].second, open_braces))
1602                                 return 0;
1603
1604                 // Exclude from the returned match length any length
1605                 // due to close wildcards added at end of regexp
1606                 // and also the length of the leading (e.g. '\emph{')
1607                 //
1608                 // Whole found string, including the leading: m[0].second - m[0].first
1609                 // Size of the leading string: m[1].second - m[1].first
1610                 int leadingsize = 0;
1611                 if (m.size() > 1)
1612                         leadingsize = m[1].second - m[1].first;
1613                 int result;
1614                 for (size_t i = 0; i < m.size(); i++) {
1615                   LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
1616                 }
1617                 if (close_wildcards == 0)
1618                         result = m[0].second - m[0].first;
1619
1620                 else
1621                         result =  m[m.size() - close_wildcards].first - m[0].first;
1622
1623                 if (result > leadingsize)
1624                         result -= leadingsize;
1625                 else
1626                         result = 0;
1627                 return(result);
1628         }
1629
1630         // else !use_regexp: but all code paths above return
1631         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
1632                                  << par_as_string << "', str='" << str << "'");
1633         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1634                                  << lead_as_string << "', par_as_string_nolead='"
1635                                  << par_as_string_nolead << "'");
1636
1637         if (at_begin) {
1638                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1639                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1640                 if (str.substr(0, par_as_string.size()) == par_as_string)
1641                         return par_as_string.size();
1642         } else {
1643                 size_t pos = str.find(par_as_string_nolead);
1644                 if (pos != string::npos)
1645                         return par_as_string.size();
1646         }
1647         return 0;
1648 }
1649
1650
1651 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1652 {
1653         int res = findAux(cur, len, at_begin);
1654         LYXERR(Debug::FIND,
1655                "res=" << res << ", at_begin=" << at_begin
1656                << ", matchword=" << opt.matchword
1657                << ", inTexted=" << cur.inTexted());
1658         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1659                 return res;
1660         Paragraph const & par = cur.paragraph();
1661         bool ws_left = (cur.pos() > 0)
1662                 ? par.isWordSeparator(cur.pos() - 1)
1663                 : true;
1664         bool ws_right = (cur.pos() + res < par.size())
1665                 ? par.isWordSeparator(cur.pos() + res)
1666                 : true;
1667         LYXERR(Debug::FIND,
1668                "cur.pos()=" << cur.pos() << ", res=" << res
1669                << ", separ: " << ws_left << ", " << ws_right
1670                << endl);
1671         if (ws_left && ws_right)
1672                 return res;
1673         return 0;
1674 }
1675
1676
1677 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1678 {
1679         string t;
1680         if (! opt.casesensitive)
1681                 t = lyx::to_utf8(lowercase(s));
1682         else
1683                 t = lyx::to_utf8(s);
1684         // Remove \n at begin
1685         while (!t.empty() && t[0] == '\n')
1686                 t = t.substr(1);
1687         // Remove \n at end
1688         while (!t.empty() && t[t.size() - 1] == '\n')
1689                 t = t.substr(0, t.size() - 1);
1690         size_t pos;
1691         // Replace all other \n with spaces
1692         while ((pos = t.find("\n")) != string::npos)
1693                 t.replace(pos, 1, " ");
1694         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1695         // Kornel: Added textsl, textsf, textit, texttt and noun
1696         // + allow to seach for colored text too
1697         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1698         while (regex_replace(t, t, "\\\\((emph|noun|text(bf|sl|sf|it|tt|color\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)(\\{(\\{\\})?\\})+", ""))
1699                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1700
1701         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
1702         // FIXME - check what preceeds the brace
1703         if (hack_braces) {
1704                 if (opt.ignoreformat)
1705                         while (regex_replace(t, t, "\\{", "_x_<")
1706                                || regex_replace(t, t, "\\}", "_x_>"))
1707                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1708                 else
1709                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1710                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1711                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1712         }
1713
1714         return t;
1715 }
1716
1717
1718 docstring stringifyFromCursor(DocIterator const & cur, int len)
1719 {
1720         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1721         if (cur.inTexted()) {
1722                 Paragraph const & par = cur.paragraph();
1723                 // TODO what about searching beyond/across paragraph breaks ?
1724                 // TODO Try adding a AS_STR_INSERTS as last arg
1725                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1726                         int(par.size()) : cur.pos() + len;
1727                 OutputParams runparams(&cur.buffer()->params().encoding());
1728                 runparams.nice = true;
1729                 runparams.flavor = OutputParams::LATEX;
1730                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1731                 // No side effect of file copying and image conversion
1732                 runparams.dryrun = true;
1733                 LYXERR(Debug::FIND, "Stringifying with cur: "
1734                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1735                 return par.asString(cur.pos(), end,
1736                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1737                         &runparams);
1738         } else if (cur.inMathed()) {
1739                 docstring s;
1740                 CursorSlice cs = cur.top();
1741                 MathData md = cs.cell();
1742                 MathData::const_iterator it_end =
1743                         (( len == -1 || cs.pos() + len > int(md.size()))
1744                          ? md.end()
1745                          : md.begin() + cs.pos() + len );
1746                 for (MathData::const_iterator it = md.begin() + cs.pos();
1747                      it != it_end; ++it)
1748                         s = s + asString(*it);
1749                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1750                 return s;
1751         }
1752         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1753         return docstring();
1754 }
1755
1756
1757 /** Computes the LaTeX export of buf starting from cur and ending len positions
1758  * after cur, if len is positive, or at the paragraph or innermost inset end
1759  * if len is -1.
1760  */
1761 docstring latexifyFromCursor(DocIterator const & cur, int len)
1762 {
1763         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1764         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1765                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1766         Buffer const & buf = *cur.buffer();
1767
1768         odocstringstream ods;
1769         otexstream os(ods);
1770         OutputParams runparams(&buf.params().encoding());
1771         runparams.nice = false;
1772         runparams.flavor = OutputParams::LATEX;
1773         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1774         // No side effect of file copying and image conversion
1775         runparams.dryrun = true;
1776         runparams.for_search = true;
1777
1778         if (cur.inTexted()) {
1779                 // @TODO what about searching beyond/across paragraph breaks ?
1780                 pos_type endpos = cur.paragraph().size();
1781                 if (len != -1 && endpos > cur.pos() + len)
1782                         endpos = cur.pos() + len;
1783                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1784                           string(), cur.pos(), endpos);
1785                 string s = correctlanguagesetting(lyx::to_utf8(ods.str()), false, false);
1786                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
1787                 return(lyx::from_utf8(s));
1788         } else if (cur.inMathed()) {
1789                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1790                 for (int s = cur.depth() - 1; s >= 0; --s) {
1791                         CursorSlice const & cs = cur[s];
1792                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1793                                 WriteStream ws(os);
1794                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1795                                 break;
1796                         }
1797                 }
1798
1799                 CursorSlice const & cs = cur.top();
1800                 MathData md = cs.cell();
1801                 MathData::const_iterator it_end =
1802                         ((len == -1 || cs.pos() + len > int(md.size()))
1803                          ? md.end()
1804                          : md.begin() + cs.pos() + len);
1805                 for (MathData::const_iterator it = md.begin() + cs.pos();
1806                      it != it_end; ++it)
1807                         ods << asString(*it);
1808
1809                 // Retrieve the math environment type, and add '$' or '$]'
1810                 // or others (\end{equation}) accordingly
1811                 for (int s = cur.depth() - 1; s >= 0; --s) {
1812                         CursorSlice const & cs2 = cur[s];
1813                         InsetMath * inset = cs2.asInsetMath();
1814                         if (inset && inset->asHullInset()) {
1815                                 WriteStream ws(os);
1816                                 inset->asHullInset()->footer_write(ws);
1817                                 break;
1818                         }
1819                 }
1820                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1821         } else {
1822                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1823         }
1824         return ods.str();
1825 }
1826
1827
1828 /** Finalize an advanced find operation, advancing the cursor to the innermost
1829  ** position that matches, plus computing the length of the matching text to
1830  ** be selected
1831  **/
1832 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1833 {
1834         // Search the foremost position that matches (avoids find of entire math
1835         // inset when match at start of it)
1836         size_t d;
1837         DocIterator old_cur(cur.buffer());
1838         do {
1839                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1840                 d = cur.depth();
1841                 old_cur = cur;
1842                 cur.forwardPos();
1843         } while (cur && cur.depth() > d && match(cur) > 0);
1844         cur = old_cur;
1845         if (match(cur) <= 0) return 0;
1846         LYXERR(Debug::FIND, "Ok");
1847
1848         // Compute the match length
1849         int len = 1;
1850         if (cur.pos() + len > cur.lastpos())
1851                 return 0;
1852         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1853         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
1854                 ++len;
1855                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1856         }
1857         // Length of matched text (different from len param)
1858         int old_len = match(cur, len);
1859         if (old_len < 0) old_len = 0;
1860         int new_len;
1861         // Greedy behaviour while matching regexps
1862         while ((new_len = match(cur, len + 1)) > old_len) {
1863                 ++len;
1864                 old_len = new_len;
1865                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1866         }
1867         return len;
1868 }
1869
1870
1871 /// Finds forward
1872 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1873 {
1874         if (!cur)
1875                 return 0;
1876         while (!theApp()->longOperationCancelled() && cur) {
1877                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1878                 int match_len = match(cur, -1, false);
1879                 LYXERR(Debug::FIND, "match_len: " << match_len);
1880                 if (match_len > 0) {
1881                         int match_len_zero_count = 0;
1882                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1883                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1884                                 int match_len2 = match(cur);
1885                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
1886                                 if (match_len2 > 0) {
1887                                         // Sometimes in finalize we understand it wasn't a match
1888                                         // and we need to continue the outest loop
1889                                         int len = findAdvFinalize(cur, match);
1890                                         if (len > 0) {
1891                                                 return len;
1892                                         }
1893                                 }
1894                                 if (match_len2 >= 0) {
1895                                         if (match_len2 == 0)
1896                                                 match_len_zero_count++;
1897                                         else
1898                                                 match_len_zero_count = 0;
1899                                 }
1900                                 else {
1901                                         if (++match_len_zero_count > 3) {
1902                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
1903                                                 match_len_zero_count = 0;
1904                                         }
1905                                         break;
1906                                 }
1907                         }
1908                         if (!cur)
1909                                 return 0;
1910                 }
1911                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
1912                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1913                         cur.forwardPar();
1914                 } else {
1915                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1916                         cur.pos() = cur.lastpos();
1917                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1918                         cur.forwardPos();
1919                 }
1920         }
1921         return 0;
1922 }
1923
1924
1925 /// Find the most backward consecutive match within same paragraph while searching backwards.
1926 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1927 {
1928         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1929         DocIterator tmp_cur = cur;
1930         int len = findAdvFinalize(tmp_cur, match);
1931         Inset & inset = cur.inset();
1932         for (; cur != cur_begin; cur.backwardPos()) {
1933                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1934                 DocIterator new_cur = cur;
1935                 new_cur.backwardPos();
1936                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1937                         break;
1938                 int new_len = findAdvFinalize(new_cur, match);
1939                 if (new_len == len)
1940                         break;
1941                 len = new_len;
1942         }
1943         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1944         return len;
1945 }
1946
1947
1948 /// Finds backwards
1949 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1950 {
1951         if (! cur)
1952                 return 0;
1953         // Backup of original position
1954         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1955         if (cur == cur_begin)
1956                 return 0;
1957         cur.backwardPos();
1958         DocIterator cur_orig(cur);
1959         bool pit_changed = false;
1960         do {
1961                 cur.pos() = 0;
1962                 bool found_match = match(cur, -1, false);
1963
1964                 if (found_match) {
1965                         if (pit_changed)
1966                                 cur.pos() = cur.lastpos();
1967                         else
1968                                 cur.pos() = cur_orig.pos();
1969                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1970                         DocIterator cur_prev_iter;
1971                         do {
1972                                 found_match = match(cur);
1973                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1974                                        << found_match << ", cur: " << cur);
1975                                 if (found_match)
1976                                         return findMostBackwards(cur, match);
1977
1978                                 // Stop if begin of document reached
1979                                 if (cur == cur_begin)
1980                                         break;
1981                                 cur_prev_iter = cur;
1982                                 cur.backwardPos();
1983                         } while (true);
1984                 }
1985                 if (cur == cur_begin)
1986                         break;
1987                 if (cur.pit() > 0)
1988                         --cur.pit();
1989                 else
1990                         cur.backwardPos();
1991                 pit_changed = true;
1992         } while (!theApp()->longOperationCancelled());
1993         return 0;
1994 }
1995
1996
1997 } // namespace
1998
1999
2000 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2001                                  DocIterator const & cur, int len)
2002 {
2003         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2004                 return docstring();
2005         if (!opt.ignoreformat)
2006                 return latexifyFromCursor(cur, len);
2007         else
2008                 return stringifyFromCursor(cur, len);
2009 }
2010
2011
2012 FindAndReplaceOptions::FindAndReplaceOptions(
2013         docstring const & find_buf_name, bool casesensitive,
2014         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2015         docstring const & repl_buf_name, bool keep_case,
2016         SearchScope scope, SearchRestriction restr)
2017         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2018           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2019           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2020 {
2021 }
2022
2023
2024 namespace {
2025
2026
2027 /** Check if 'len' letters following cursor are all non-lowercase */
2028 static bool allNonLowercase(Cursor const & cur, int len)
2029 {
2030         pos_type beg_pos = cur.selectionBegin().pos();
2031         pos_type end_pos = cur.selectionBegin().pos() + len;
2032         if (len > cur.lastpos() + 1 - beg_pos) {
2033                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2034                 len = cur.lastpos() + 1 - beg_pos;
2035                 end_pos = beg_pos + len;
2036         }
2037         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2038                 if (isLowerCase(cur.paragraph().getChar(pos)))
2039                         return false;
2040         return true;
2041 }
2042
2043
2044 /** Check if first letter is upper case and second one is lower case */
2045 static bool firstUppercase(Cursor const & cur)
2046 {
2047         char_type ch1, ch2;
2048         pos_type pos = cur.selectionBegin().pos();
2049         if (pos >= cur.lastpos() - 1) {
2050                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2051                 return false;
2052         }
2053         ch1 = cur.paragraph().getChar(pos);
2054         ch2 = cur.paragraph().getChar(pos + 1);
2055         bool result = isUpperCase(ch1) && isLowerCase(ch2);
2056         LYXERR(Debug::FIND, "firstUppercase(): "
2057                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2058                << ch2 << "(" << char(ch2) << ")"
2059                << ", result=" << result << ", cur=" << cur);
2060         return result;
2061 }
2062
2063
2064 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2065  **
2066  ** \fixme What to do with possible further paragraphs in replace buffer ?
2067  **/
2068 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2069 {
2070         ParagraphList::iterator pit = buffer.paragraphs().begin();
2071         LASSERT(pit->size() >= 1, /**/);
2072         pos_type right = pos_type(1);
2073         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2074         right = pit->size();
2075         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2076 }
2077
2078 } // namespace
2079
2080 ///
2081 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2082 {
2083         Cursor & cur = bv->cursor();
2084         if (opt.repl_buf_name == docstring()
2085             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2086             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2087                 return;
2088
2089         DocIterator sel_beg = cur.selectionBegin();
2090         DocIterator sel_end = cur.selectionEnd();
2091         if (&sel_beg.inset() != &sel_end.inset()
2092             || sel_beg.pit() != sel_end.pit()
2093             || sel_beg.idx() != sel_end.idx())
2094                 return;
2095         int sel_len = sel_end.pos() - sel_beg.pos();
2096         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2097                << ", sel_len: " << sel_len << endl);
2098         if (sel_len == 0)
2099                 return;
2100         LASSERT(sel_len > 0, return);
2101
2102         if (!matchAdv(sel_beg, sel_len))
2103                 return;
2104
2105         // Build a copy of the replace buffer, adapted to the KeepCase option
2106         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2107         ostringstream oss;
2108         repl_buffer_orig.write(oss);
2109         string lyx = oss.str();
2110         Buffer repl_buffer("", false);
2111         repl_buffer.setUnnamed(true);
2112         LASSERT(repl_buffer.readString(lyx), return);
2113         if (opt.keep_case && sel_len >= 2) {
2114                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2115                 if (cur.inTexted()) {
2116                         if (firstUppercase(cur))
2117                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2118                         else if (allNonLowercase(cur, sel_len))
2119                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2120                 }
2121         }
2122         cap::cutSelection(cur, false);
2123         if (cur.inTexted()) {
2124                 repl_buffer.changeLanguage(
2125                         repl_buffer.language(),
2126                         cur.getFont().language());
2127                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2128                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2129                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2130                                         repl_buffer.params().documentClassPtr(),
2131                                         bv->buffer().errorList("Paste"));
2132                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2133                 sel_len = repl_buffer.paragraphs().begin()->size();
2134         } else if (cur.inMathed()) {
2135                 odocstringstream ods;
2136                 otexstream os(ods);
2137                 OutputParams runparams(&repl_buffer.params().encoding());
2138                 runparams.nice = false;
2139                 runparams.flavor = OutputParams::LATEX;
2140                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2141                 runparams.dryrun = true;
2142                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2143                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2144                 docstring repl_latex = ods.str();
2145                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2146                 string s;
2147                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2148                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2149                 repl_latex = from_utf8(s);
2150                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2151                 MathData ar(cur.buffer());
2152                 asArray(repl_latex, ar, Parse::NORMAL);
2153                 cur.insert(ar);
2154                 sel_len = ar.size();
2155                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2156         }
2157         if (cur.pos() >= sel_len)
2158                 cur.pos() -= sel_len;
2159         else
2160                 cur.pos() = 0;
2161         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2162         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2163         bv->processUpdateFlags(Update::Force);
2164 }
2165
2166
2167 /// Perform a FindAdv operation.
2168 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2169 {
2170         DocIterator cur;
2171         int match_len = 0;
2172
2173         // e.g., when invoking word-findadv from mini-buffer wither with
2174         //       wrong options syntax or before ever opening advanced F&R pane
2175         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2176                 return false;
2177
2178         try {
2179                 MatchStringAdv matchAdv(bv->buffer(), opt);
2180                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2181                 if (length > 0)
2182                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2183                 findAdvReplace(bv, opt, matchAdv);
2184                 cur = bv->cursor();
2185                 if (opt.forward)
2186                         match_len = findForwardAdv(cur, matchAdv);
2187                 else
2188                         match_len = findBackwardsAdv(cur, matchAdv);
2189         } catch (...) {
2190                 // This may only be raised by lyx::regex()
2191                 bv->message(_("Invalid regular expression!"));
2192                 return false;
2193         }
2194
2195         if (match_len == 0) {
2196                 bv->message(_("Match not found!"));
2197                 return false;
2198         }
2199
2200         bv->message(_("Match found!"));
2201
2202         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2203         bv->putSelectionAt(cur, match_len, !opt.forward);
2204
2205         return true;
2206 }
2207
2208
2209 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2210 {
2211         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2212            << opt.casesensitive << ' '
2213            << opt.matchword << ' '
2214            << opt.forward << ' '
2215            << opt.expandmacros << ' '
2216            << opt.ignoreformat << ' '
2217            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2218            << opt.keep_case << ' '
2219            << int(opt.scope) << ' '
2220            << int(opt.restr);
2221
2222         LYXERR(Debug::FIND, "built: " << os.str());
2223
2224         return os;
2225 }
2226
2227
2228 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2229 {
2230         LYXERR(Debug::FIND, "parsing");
2231         string s;
2232         string line;
2233         getline(is, line);
2234         while (line != "EOSS") {
2235                 if (! s.empty())
2236                         s = s + "\n";
2237                 s = s + line;
2238                 if (is.eof())   // Tolerate malformed request
2239                         break;
2240                 getline(is, line);
2241         }
2242         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2243         opt.find_buf_name = from_utf8(s);
2244         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2245         is.get();       // Waste space before replace string
2246         s = "";
2247         getline(is, line);
2248         while (line != "EOSS") {
2249                 if (! s.empty())
2250                         s = s + "\n";
2251                 s = s + line;
2252                 if (is.eof())   // Tolerate malformed request
2253                         break;
2254                 getline(is, line);
2255         }
2256         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2257         opt.repl_buf_name = from_utf8(s);
2258         is >> opt.keep_case;
2259         int i;
2260         is >> i;
2261         opt.scope = FindAndReplaceOptions::SearchScope(i);
2262         is >> i;
2263         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2264
2265         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2266                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2267                << opt.scope << ' ' << opt.restr);
2268         return is;
2269 }
2270
2271 } // namespace lyx