]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
b3eedec7e470695de7fa42fc2f81c11966baed45
[lyx.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  * \author Tommaso Cucinotta
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyxfind.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/FileName.h"
50 #include "support/gettext.h"
51 #include "support/lassert.h"
52 #include "support/lstrings.h"
53
54 #include "support/regex.h"
55 #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                 escape_map.push_back(P("#", "\\\\#"));
601         }
602         return escape_map;
603 }
604
605 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
606  ** the found occurrence were escaped.
607  **/
608 string apply_escapes(string s, Escapes const & escape_map)
609 {
610         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
611         Escapes::const_iterator it;
612         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
613 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
614                 unsigned int pos = 0;
615                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
616                         s.replace(pos, it->first.length(), it->second);
617                         LYXERR(Debug::FIND, "After escape: " << s);
618                         pos += it->second.length();
619 //                      LYXERR(Debug::FIND, "pos: " << pos);
620                 }
621         }
622         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
623         return s;
624 }
625
626
627 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
628 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
629 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
630 string escape_for_regex(string s, bool match_latex)
631 {
632         size_t pos = 0;
633         while (pos < s.size()) {
634                 size_t new_pos = s.find("\\regexp{", pos);
635                 if (new_pos == string::npos)
636                         new_pos = s.size();
637                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
638                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
639                 LYXERR(Debug::FIND, "t [lyx]: " << t);
640                 t = apply_escapes(t, get_regexp_escapes());
641                 LYXERR(Debug::FIND, "t [rxp]: " << t);
642                 s.replace(pos, new_pos - pos, t);
643                 new_pos = pos + t.size();
644                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
645                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
646                 if (new_pos == s.size())
647                         break;
648                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
649                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
650                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
651                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
652                 LYXERR(Debug::FIND, "t in regexp      : " << t);
653                 t = apply_escapes(t, get_lyx_unescapes());
654                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
655                 if (match_latex) {
656                         t = apply_escapes(t, get_regexp_latex_escapes());
657                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
658                 }
659                 if (end_pos == s.size()) {
660                         s.replace(new_pos, end_pos - new_pos, t);
661                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
662                         break;
663                 }
664                 s.replace(new_pos, end_pos + 13 - new_pos, t);
665                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
666                 pos = new_pos + t.size();
667                 LYXERR(Debug::FIND, "pos: " << pos);
668         }
669         return s;
670 }
671
672
673 /// Wrapper for lyx::regex_replace with simpler interface
674 bool regex_replace(string const & s, string & t, string const & searchstr,
675                    string const & replacestr)
676 {
677         lyx::regex e(searchstr, regex_constants::ECMAScript);
678         ostringstream oss;
679         ostream_iterator<char, char> it(oss);
680         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
681         // tolerate t and s be references to the same variable
682         bool rv = (s != oss.str());
683         t = oss.str();
684         return rv;
685 }
686
687
688 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
689  **
690  ** Verify that closed braces exactly match open braces. This avoids that, for example,
691  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
692  **
693  ** @param unmatched
694  ** Number of open braces that must remain open at the end for the verification to succeed.
695  **/
696 bool braces_match(string::const_iterator const & beg,
697                   string::const_iterator const & end,
698                   int unmatched = 0)
699 {
700         int open_pars = 0;
701         string::const_iterator it = beg;
702         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
703         for (; it != end; ++it) {
704                 // Skip escaped braces in the count
705                 if (*it == '\\') {
706                         ++it;
707                         if (it == end)
708                                 break;
709                 } else if (*it == '{') {
710                         ++open_pars;
711                 } else if (*it == '}') {
712                         if (open_pars == 0) {
713                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
714                                 return false;
715                         } else
716                                 --open_pars;
717                 }
718         }
719         if (open_pars != unmatched) {
720                 LYXERR(Debug::FIND, "Found " << open_pars
721                        << " instead of " << unmatched
722                        << " unmatched open braces at the end of count");
723                 return false;
724         }
725         LYXERR(Debug::FIND, "Braces match as expected");
726         return true;
727 }
728
729
730 /** The class performing a match between a position in the document and the FindAdvOptions.
731  **/
732 class MatchStringAdv {
733 public:
734         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
735
736         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
737          ** constructor as opt.search, under the opt.* options settings.
738          **
739          ** @param at_begin
740          **     If set, then match is searched only against beginning of text starting at cur.
741          **     If unset, then match is searched anywhere in text starting at cur.
742          **
743          ** @return
744          ** The length of the matching text, or zero if no match was found.
745          **/
746         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
747
748 public:
749         /// buffer
750         lyx::Buffer * p_buf;
751         /// first buffer on which search was started
752         lyx::Buffer * const p_first_buf;
753         /// options
754         FindAndReplaceOptions const & opt;
755
756 private:
757         /// Auxiliary find method (does not account for opt.matchword)
758         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
759
760         /** Normalize a stringified or latexified LyX paragraph.
761          **
762          ** Normalize means:
763          ** <ul>
764          **   <li>if search is not casesensitive, then lowercase the string;
765          **   <li>remove any newline at begin or end of the string;
766          **   <li>replace any newline in the middle of the string with a simple space;
767          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
768          ** </ul>
769          **
770          ** @todo Normalization should also expand macros, if the corresponding
771          ** search option was checked.
772          **/
773         string normalize(docstring const & s, bool hack_braces) const;
774         // normalized string to search
775         string par_as_string;
776         // regular expression to use for searching
777         lyx::regex regexp;
778         // same as regexp, but prefixed with a ".*"
779         lyx::regex regexp2;
780         // leading format material as string
781         string lead_as_string;
782         // par_as_string after removal of lead_as_string
783         string par_as_string_nolead;
784         // unmatched open braces in the search string/regexp
785         int open_braces;
786         // number of (.*?) subexpressions added at end of search regexp for closing
787         // environments, math mode, styles, etc...
788         int close_wildcards;
789         // Are we searching with regular expressions ?
790         bool use_regexp;
791 };
792
793
794 static docstring buffer_to_latex(Buffer & buffer)
795 {
796         OutputParams runparams(&buffer.params().encoding());
797         odocstringstream ods;
798         otexstream os(ods);
799         runparams.nice = true;
800         runparams.flavor = OutputParams::LATEX;
801         runparams.linelen = 80; //lyxrc.plaintext_linelen;
802         // No side effect of file copying and image conversion
803         runparams.dryrun = true;
804         runparams.for_search = true;
805         pit_type const endpit = buffer.paragraphs().size();
806         for (pit_type pit = 0; pit != endpit; ++pit) {
807                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
808                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
809         }
810         return ods.str();
811 }
812
813
814 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
815 {
816         docstring str;
817         if (!opt.ignoreformat) {
818                 str = buffer_to_latex(buffer);
819         } else {
820                 OutputParams runparams(&buffer.params().encoding());
821                 runparams.nice = true;
822                 runparams.flavor = OutputParams::LATEX;
823                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
824                 runparams.dryrun = true;
825                 runparams.for_search = true;
826                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
827                         Paragraph const & par = buffer.paragraphs().at(pit);
828                         LYXERR(Debug::FIND, "Adding to search string: '"
829                                << par.asString(pos_type(0), par.size(),
830                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
831                                                &runparams)
832                                << "'");
833                         str += par.asString(pos_type(0), par.size(),
834                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
835                                             &runparams);
836                 }
837         }
838         return str;
839 }
840
841
842 /// Return separation pos between the leading material and the rest
843 static size_t identifyLeading(string const & s)
844 {
845         string t = s;
846         // @TODO Support \item[text]
847         // Kornel: Added textsl, textsf, textit, texttt and noun
848         // + allow to search for colored text too
849         while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|minisec|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
850                || regex_replace(t, t, REGEX_BOS "\\$", "")
851                || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
852                || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
853                || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
854                ;
855         LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
856         return s.find(t);
857 }
858
859 /*
860  * Given a latexified string, retrieve some handled features
861  * The features of the regex will later be compared with the features
862  * of the searched text. If the regex features are not a
863  * subset of the analized, then, in not format ignoring search
864  * we can early stop the search in the relevant inset.
865  */
866 typedef map<string, bool> Features;
867
868 static Features identifyFeatures(string const & s)
869 {
870         static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
871         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|chapter)\\*?)$");
872         smatch sub;
873         bool displ = true;
874         Features info;
875
876         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
877                 sub = *it;
878                 if (displ) {
879                         if (sub.str(1).compare("regexp") == 0) {
880                                 displ = false;
881                                 continue;
882                         }
883                         string token = sub.str(1);
884                         smatch sub2;
885                         if (regex_match(token, sub2, valid)) {
886                                 info[token] = true;
887                         }
888                         else {
889                                 // ignore
890                         }
891                 }
892                 else {
893                         if (sub.str(1).compare("endregexp") == 0) {
894                                 displ = true;
895                                 continue;
896                         }
897                 }
898         }
899         return(info);
900 }
901
902 /*
903  * defines values features of a key "\\[a-z]+{"
904  */
905 class KeyInfo {
906  public:
907   enum KeyType {
908     isChar,
909     isSectioning,
910     isMain,                             /* for \\foreignlanguage */
911     isRegex,
912     isMath,
913     isStandard,
914     isSize,
915     invalid,
916     doRemove,
917     isIgnored                           /* to be ignored by creating infos */
918   };
919  KeyInfo()
920    : keytype(invalid),
921     head(""),
922     parenthesiscount(1),
923     disabled(false),
924     used(false)
925   {};
926  KeyInfo(KeyType type, int parcount, bool disable)
927    : keytype(type),
928     parenthesiscount(parcount),
929     disabled(disable),
930     used(false) {};
931   KeyType keytype;
932   string head;
933   int _tokensize;
934   int _tokenstart;
935   int _dataStart;
936   int _dataEnd;
937   int parenthesiscount;
938   bool disabled;
939   bool used;                            /* by pattern */
940 };
941
942 class Border {
943  public:
944  Border(int l=0, int u=0) : low(l), upper(u) {};
945   int low;
946   int upper;
947 };
948
949 #define MAXOPENED 30
950 class Intervall {
951  public:
952  Intervall() : ignoreidx(-1), actualdeptindex(0) {};
953   string par;
954   int ignoreidx;
955   int depts[MAXOPENED];
956   int closes[MAXOPENED];
957   int actualdeptindex;
958   Border borders[2*MAXOPENED];
959   // int previousNotIgnored(int);
960   int nextNotIgnored(int);
961   void handleOpenP(int i);
962   void handleCloseP(int i, bool closingAllowed);
963   void resetOpenedP(int openPos);
964   void addIntervall(int upper);
965   void addIntervall(int low, int upper); /* if explicit */
966   void setForDefaultLang(int upTo);
967   int findclosing(int start, int end);
968   void handleParentheses(int lastpos, bool closingAllowed);
969   void output(ostringstream &os, int lastpos);
970   // string show(int lastpos);
971 };
972
973 void Intervall::setForDefaultLang(int upTo)
974 {
975   // Enable the use of first token again
976   if (ignoreidx >= 0) {
977     if (borders[0].low < upTo)
978       borders[0].low = upTo;
979     if (borders[0].upper < upTo)
980       borders[0].upper = upTo;
981   }
982 }
983
984 static void checkDepthIndex(int val)
985 {
986   static int maxdepthidx = MAXOPENED-2;
987   if (val > maxdepthidx) {
988     maxdepthidx = val;
989     LYXERR0("maxdepthidx now " << val);
990   }
991 }
992
993 static void checkIgnoreIdx(int val)
994 {
995   static int maxignoreidx = 2*MAXOPENED - 4;
996   if (val > maxignoreidx) {
997     maxignoreidx = val;
998     LYXERR0("maxignoreidx now " << val);
999   }
1000 }
1001
1002 /*
1003  * Expand the region of ignored parts of the input latex string
1004  * The region is only relevant in output()
1005  */
1006 void Intervall::addIntervall(int low, int upper)
1007 {
1008   int idx;
1009   if (low == upper) return;
1010   for (idx = ignoreidx+1; idx > 0; --idx) {
1011     if (low > borders[idx-1].upper) {
1012       break;
1013     }
1014   }
1015   Border br(low, upper);
1016   if (idx > ignoreidx) {
1017     borders[idx] = br;
1018     ignoreidx = idx;
1019     checkIgnoreIdx(ignoreidx);
1020     return;
1021   }
1022   else {
1023     // Expand only if one of the new bound is inside the interwall
1024     // We know here that br.low > borders[idx-1].upper
1025     if (br.upper < borders[idx].low) {
1026       // We have to insert at this pos
1027       for (int i = ignoreidx+1; i > idx; --i) {
1028         borders[i] = borders[i-1];
1029       }
1030       borders[idx] = br;
1031       ignoreidx += 1;
1032       checkIgnoreIdx(ignoreidx);
1033       return;
1034     }
1035     // Here we know, that we are overlapping
1036     if (br.low > borders[idx].low)
1037       br.low = borders[idx].low;
1038     // check what has to be concatenated
1039     int count = 0;
1040     for (int i = idx; i <= ignoreidx; i++) {
1041       if (br.upper >= borders[i].low) {
1042         count++;
1043         if (br.upper < borders[i].upper)
1044           br.upper = borders[i].upper;
1045       }
1046       else {
1047         break;
1048       }
1049     }
1050     // count should be >= 1 here
1051     borders[idx] = br;
1052     if (count > 1) {
1053       for (int i = idx + count; i <= ignoreidx; i++) {
1054         borders[i-count+1] = borders[i];
1055       }
1056       ignoreidx -= count - 1;
1057       return;
1058     }
1059   }
1060 }
1061
1062 void Intervall::handleOpenP(int i)
1063 {
1064   actualdeptindex++;
1065   depts[actualdeptindex] = i+1;
1066   closes[actualdeptindex] = -1;
1067   checkDepthIndex(actualdeptindex);
1068 }
1069
1070 void Intervall::handleCloseP(int i, bool closingAllowed)
1071 {
1072   if (actualdeptindex <= 0) {
1073     if (! closingAllowed)
1074       LYXERR(Debug::FIND, "Bad closing parenthesis in latex");  /* should not happen, but the latex input may be wrong */
1075     // if we are at the very end
1076     addIntervall(i, i+1);
1077   }
1078   else {
1079     closes[actualdeptindex] = i+1;
1080     actualdeptindex--;
1081   }
1082 }
1083
1084 void Intervall::resetOpenedP(int openPos)
1085 {
1086   // Used as initializer for foreignlanguage entry
1087   actualdeptindex = 1;
1088   depts[1] = openPos+1;
1089   closes[1] = -1;
1090 }
1091
1092 #if 0
1093 int Intervall::previousNotIgnored(int start)
1094 {
1095     int idx = 0;                          /* int intervalls */
1096     for (idx = ignoreidx; idx >= 0; --idx) {
1097       if (start > borders[idx].upper)
1098         return(start);
1099       if (start >= borders[idx].low)
1100         start = borders[idx].low-1;
1101     }
1102     return start;
1103 }
1104 #endif
1105
1106 int Intervall::nextNotIgnored(int start)
1107 {
1108     int idx = 0;                          /* int intervalls */
1109     for (idx = 0; idx <= ignoreidx; idx++) {
1110       if (start < borders[idx].low)
1111         return(start);
1112       if (start < borders[idx].upper)
1113         start = borders[idx].upper;
1114     }
1115     return start;
1116 }
1117
1118 typedef map<string, KeyInfo> KeysMap;
1119 typedef vector< KeyInfo> Entries;
1120 static KeysMap keys = map<string, KeyInfo>();
1121
1122 class IgnoreFormats {
1123   static bool ignoreFamily;
1124   static bool ignoreSeries;
1125   static bool ignoreShape;
1126   static bool ignoreUnderline;
1127   static bool ignoreMarkUp;
1128   static bool ignoreStrikeOut;
1129   static bool ignoreSectioning;
1130   static bool ignoreFrontMatter;
1131   static bool ignoreColor;
1132   static bool ignoreLanguage;
1133  public:
1134   bool getFamily() { return ignoreFamily; };
1135   bool getSeries() { return ignoreSeries; };
1136   bool getShape() { return ignoreShape; };
1137   bool getUnderline() { return ignoreUnderline; };
1138   bool getMarkUp() { return ignoreMarkUp; };
1139   bool getStrikeOut() { return ignoreStrikeOut; };
1140   bool getSectioning() { return ignoreSectioning; };
1141   bool getFrontMatter() { return ignoreFrontMatter; };
1142   bool getColor() { return ignoreColor; };
1143   bool getLanguage() { return ignoreLanguage; };
1144
1145   void setIgnoreFormat(string type, bool value);
1146 };
1147
1148 bool IgnoreFormats::ignoreFamily     = false;
1149 bool IgnoreFormats::ignoreSeries     = false;
1150 bool IgnoreFormats::ignoreShape      = false;
1151 bool IgnoreFormats::ignoreUnderline  = false;
1152 bool IgnoreFormats::ignoreMarkUp     = false;
1153 bool IgnoreFormats::ignoreStrikeOut  = false;
1154 bool IgnoreFormats::ignoreSectioning = false;
1155 bool IgnoreFormats::ignoreFrontMatter= true;
1156 bool IgnoreFormats::ignoreColor      = false;
1157 bool IgnoreFormats::ignoreLanguage   = false;
1158
1159 void IgnoreFormats::setIgnoreFormat(string type, bool value)
1160 {
1161   if (type == "color") {
1162     ignoreColor = value;
1163   }
1164   else if (type == "language") {
1165     ignoreLanguage = value;
1166   }
1167   else if (type == "sectioning") {
1168     ignoreSectioning = value;
1169     ignoreFrontMatter = value;
1170   }
1171   else if (type == "font") {
1172     ignoreSeries = value;
1173     ignoreShape = value;
1174     ignoreFamily = value;
1175   }
1176   else if (type == "series") {
1177     ignoreSeries = value;
1178   }
1179   else if (type == "shape") {
1180     ignoreShape = value;
1181   }
1182   else if (type == "family") {
1183     ignoreFamily = value;
1184   }
1185   else if (type == "markup") {
1186     ignoreMarkUp = value;
1187   }
1188   else if (type == "underline") {
1189     ignoreUnderline = value;
1190   }
1191   else if (type == "strike") {
1192     ignoreStrikeOut = value;
1193   }
1194 }
1195 #pragma GCC diagnostic push
1196 #pragma GCC diagnostic ignored "-Wpragmas"
1197 #pragma GCC diagnostic ignored "-Wunused-function"
1198
1199 void setIgnoreFormat(string type, bool value)
1200 {
1201   IgnoreFormats().setIgnoreFormat(type, value);
1202 }
1203 #pragma GCC diagnostic pop
1204
1205 class LatexInfo {
1206  private:
1207   int entidx;
1208   Entries entries;
1209   KeyInfo analyze(string key);
1210   Intervall interval;
1211   void buildKeys(bool);
1212   void buildEntries(bool);
1213   void makeKey(const string &, KeyInfo, bool isPatternString);
1214   void processRegion(int start, int region_end); /*  remove {} parts */
1215   void removeHead(KeyInfo&, int count=0);
1216   IgnoreFormats f;
1217
1218  public:
1219   LatexInfo(string par, bool isPatternString) {
1220     interval.par = par;
1221     buildKeys(isPatternString);
1222     entries = vector<KeyInfo>();
1223     buildEntries(isPatternString);
1224   };
1225   int getFirstKey() {
1226     entidx = 0;
1227     if (entries.empty()) {
1228       return (-1);
1229     }
1230     return 0;
1231   };
1232   int getNextKey() {
1233     entidx++;
1234     if (int(entries.size()) > entidx) {
1235       return entidx;
1236     }
1237     else {
1238       return (-1);
1239     }
1240   };
1241   bool setNextKey(int idx) {
1242     if ((idx == entidx) && (entidx >= 0)) {
1243       entidx--;
1244       return true;
1245     }
1246     else
1247       return(false);
1248   };
1249   int process(ostringstream &os, KeyInfo &actual);
1250   int dispatch(ostringstream &os, int previousStart, KeyInfo &actual);
1251   // string show(int lastpos) { return interval.show(lastpos);};
1252   int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1253   KeyInfo &getKeyInfo(int keyinfo) {
1254     static KeyInfo invalidInfo = KeyInfo();
1255     if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1256       return invalidInfo;
1257     else
1258       return entries[keyinfo];
1259   };
1260   void setForDefaultLang(int upTo) {interval.setForDefaultLang(upTo);};
1261
1262 };
1263
1264
1265 int Intervall::findclosing(int start, int end)
1266 {
1267   int skip = 0;
1268   int depth = 0;
1269   for (int i = start; i < end; i += 1 + skip) {
1270     char c;
1271     c = par[i];
1272     skip = 0;
1273     if (c == '\\') skip = 1;
1274     else if (c == '{') {
1275       depth++;
1276     }
1277     else if (c == '}') {
1278       if (depth == 0) return(i);
1279       --depth;
1280     }
1281   }
1282   return(end);
1283 }
1284
1285 void LatexInfo::buildEntries(bool isPatternString)
1286 {
1287   static regex const rmath("\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multiline|align)\\*?)\\}");
1288   static regex const rkeys("\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?))");
1289   static bool disableLanguageOverride = false;
1290   smatch sub, submath;
1291   bool evaluatingRegexp = false;
1292   KeyInfo found;
1293   bool math_end_waiting = false;
1294   size_t math_pos = 10000;
1295   int math_size = 0;
1296   int math_end_pos = -1;
1297   string math_end;
1298
1299   for (sregex_iterator itmath(interval.par.begin(), interval.par.end(), rmath), end; itmath != end; ++itmath) {
1300     submath = *itmath;
1301     if (math_end_waiting) {
1302       size_t pos = submath.position(size_t(0));
1303       if (math_end == "$") {
1304         if ((submath.str(0) == "$") && (interval.par[pos-1] != '\\')) {
1305           math_size = pos + 1 - math_pos;
1306           math_end_waiting = false;
1307         }
1308       }
1309       else if (math_end == "\\]") {
1310         if (submath.str(0) == "\\]") {
1311           math_size = pos + 2 - math_pos;
1312           math_end_waiting = false;
1313         }
1314       }
1315       else if ((submath.str(1).compare("end") == 0) &&
1316           (submath.str(2).compare(math_end) == 0)) {
1317         math_size = pos + submath.str(0).length() - math_pos;
1318         math_end_waiting = false;
1319       }
1320     }
1321     else {
1322       if (submath.str(1).compare("begin") == 0) {
1323         math_end_waiting = true;
1324         math_end = submath.str(2);
1325         math_pos = submath.position(size_t(0));
1326       }
1327       else if (submath.str(0).compare("\\[") == 0) {
1328         math_end_waiting = true;
1329         math_end = "\\]";
1330         math_pos = submath.position(size_t(0));
1331       }
1332       else if (submath.str(0) == "$") {
1333         size_t pos = submath.position(size_t(0));
1334         if ((pos == 0) || (interval.par[pos-1] != '\\')) {
1335           math_end_waiting = true;
1336           math_end = "$";
1337           math_pos = pos;
1338         }
1339       }
1340     }
1341   }
1342   if (isPatternString) {
1343     if (math_pos < interval.par.length()) {
1344       // Disable language
1345       keys["foreignlanguage"].disabled = true;
1346       disableLanguageOverride = true;
1347     }
1348     else
1349       disableLanguageOverride = false;
1350   }
1351   else {
1352     if (disableLanguageOverride) {
1353       keys["foreignlanguage"].disabled = true;
1354     }
1355   }
1356   for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1357     sub = *it;
1358     string key = sub.str(3);
1359     if (key == "") {
1360       if (sub.str(0)[0] == '\\')
1361         key = sub.str(0)[1];
1362       else
1363         key = sub.str(0);
1364     };
1365     if (evaluatingRegexp) {
1366       if (sub.str(1).compare("endregexp") == 0) {
1367         evaluatingRegexp = false;
1368         // found._tokenstart already set
1369         found._dataEnd = sub.position(size_t(0)) + 13;
1370         found._dataStart = found._dataEnd;
1371         found._tokensize = found._dataEnd - found._tokenstart;
1372         found.parenthesiscount = 0;
1373       }
1374     }
1375     else {
1376       if (keys.find(key) == keys.end()) {
1377         LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1378         continue;
1379       }
1380       found = keys[key];
1381       if (key.compare("regexp") == 0) {
1382         evaluatingRegexp = true;
1383         found._tokenstart = sub.position(size_t(0));
1384         found._tokensize = 0;
1385         continue;
1386       }
1387     }
1388     // Handle the other params of key
1389     if (found.keytype == KeyInfo::isIgnored)
1390       continue;
1391     else if (found.keytype == KeyInfo::isMath) {
1392       if (size_t(sub.position(size_t(0))) == math_pos) {
1393         found = keys[key];
1394         found._tokenstart = sub.position(size_t(0));
1395         found._tokensize = math_size;
1396         found._dataEnd = found._tokenstart + found._tokensize;
1397         found._dataStart = found._dataEnd;
1398         found.parenthesiscount = 0;
1399         math_end_pos = found._dataEnd;
1400       }
1401       else
1402         continue;
1403     }
1404     else if (found.keytype != KeyInfo::isRegex) {
1405       found._tokenstart = sub.position(size_t(0));
1406       if (found._tokenstart < math_end_pos) {
1407         // Ignore if we are inside math equation
1408         continue;
1409       }
1410       if (found.parenthesiscount == 0) {
1411         // Probably to be discarded
1412         char following = interval.par[sub.position(size_t(0)) + sub.str(3).length() + 1];
1413         if (following == ' ')
1414           found.head = "\\" + sub.str(3) + " ";
1415         else if (following == '=') {
1416           // like \uldepth=1000pt
1417           found.head = sub.str(0);
1418         }
1419         else
1420           found.head = "\\" + key;
1421         found._tokensize = found.head.length();
1422         found._dataEnd = found._tokenstart + found._tokensize;
1423         found._dataStart = found._dataEnd;
1424       }
1425       else {
1426         if (found.parenthesiscount == 1) {
1427           found.head = "\\" + key + "{";
1428         }
1429         else if (found.parenthesiscount == 2) {
1430           found.head = sub.str(0) + "{";
1431           found._tokensize = found.head.length();
1432         }
1433         found._tokensize = found.head.length();
1434         found._dataStart = found._tokenstart + found.head.length();
1435         found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1436         if (isPatternString) {
1437           keys[key].used = true;
1438         }
1439       }
1440     }
1441     entries.push_back(found);
1442   }
1443 }
1444
1445 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
1446 {
1447   stringstream s(keysstring);
1448   string key;
1449   const char delim = '|';
1450   while (getline(s, key, delim)) {
1451     KeyInfo keyII(keyI);
1452     if (isPatternString) {
1453       keyII.used = false;
1454     }
1455     else if ( !keys[key].used)
1456       keyII.disabled = true;
1457     keys[key] = keyII;
1458   }
1459 }
1460
1461 void LatexInfo::buildKeys(bool isPatternString)
1462 {
1463
1464   static bool keysBuilt = false;
1465   if (keysBuilt && !isPatternString) return;
1466
1467   // Know statdard keys with 1 parameter.
1468   // Split is done, if not at start of region
1469   makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, f.getFamily()), isPatternString);
1470   makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, f.getSeries()), isPatternString);
1471   makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, f.getShape()), isPatternString);
1472   makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, f.getUnderline()), isPatternString);
1473   makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, f.getMarkUp()), isPatternString);
1474   makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, f.getStrikeOut()), isPatternString);
1475
1476   makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
1477           KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1478   makeKey("section*|subsection*|subsubsection*|paragraph*",
1479           KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1480   makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1481   makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isSectioning, 1, f.getFrontMatter()), isPatternString);
1482   // Regex
1483   makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
1484
1485   // Split is done, if not at start of region
1486   makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, f.getColor()), isPatternString);
1487
1488   // Split is done always.
1489   makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, f.getLanguage()), isPatternString);
1490
1491   // Know charaters
1492   // No split
1493   makeKey("backslash|textbackslash|textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 1, false), isPatternString);
1494
1495   // Known macros to remove (including their parameter)
1496   // No split
1497   makeKey("inputencoding|shortcut", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
1498
1499   // Macros to remove, but let the parameter survive
1500   // No split
1501   makeKey("url|href|menuitem|footnote|code", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1502
1503   // Same effect as previous, parameter will survive (because there is no one anyway)
1504   // No split
1505   makeKey("noindent", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
1506   // like ('tiny{}' or '\tiny ' ... }
1507   makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, true), isPatternString);
1508
1509   // Survives, like known character
1510   makeKey("lyx", KeyInfo(KeyInfo::isIgnored, 0, false), isPatternString);
1511   makeKey("item", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
1512
1513   makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1514   makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1515   makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1516
1517   makeKey("par|uldepth|ULdepth", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
1518
1519   if (isPatternString) {
1520     // Allow the first searched string to rebuild the keys too
1521     keysBuilt = false;
1522   }
1523   else {
1524     // no need to rebuild again
1525     keysBuilt = true;
1526   }
1527 }
1528
1529 /*
1530  * Keep the list of actual opened parentheses actual
1531  * (e.g. depth == 4 means there are 4 '{' not processed yet)
1532  */
1533 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1534 {
1535   int skip = 0;
1536   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1537     char c;
1538     c = par[i];
1539     skip = 0;
1540     if (c == '\\') skip = 1;
1541     else if (c == '{') {
1542       handleOpenP(i);
1543     }
1544     else if (c == '}') {
1545       handleCloseP(i, closingAllowed);
1546     }
1547   }
1548 }
1549
1550 #if (0)
1551 string Intervall::show(int lastpos)
1552 {
1553   int idx = 0;                          /* int intervalls */
1554   int count = 0;
1555   string s;
1556   int i = 0;
1557   for (idx = 0; idx <= ignoreidx; idx++) {
1558     while (i < lastpos) {
1559       int printsize;
1560       if (i <= borders[idx].low) {
1561         if (borders[idx].low > lastpos)
1562           printsize = lastpos - i;
1563         else
1564           printsize = borders[idx].low - i;
1565         s += par.substr(i, printsize);
1566         i += printsize;
1567         if (i >= borders[idx].low)
1568           i = borders[idx].upper;
1569       }
1570       else {
1571         i = borders[idx].upper;
1572         break;
1573       }
1574     }
1575   }
1576   if (lastpos > i) {
1577     s += par.substr(i, lastpos-i);
1578   }
1579   return (s);
1580 }
1581 #endif
1582
1583 void Intervall::output(ostringstream &os, int lastpos)
1584 {
1585   // get number of chars to output
1586   int idx = 0;                          /* int intervalls */
1587   int i = 0;
1588   for (idx = 0; idx <= ignoreidx; idx++) {
1589     if (i < lastpos) {
1590       int printsize;
1591       if (i <= borders[idx].low) {
1592         if (borders[idx].low > lastpos)
1593           printsize = lastpos - i;
1594         else
1595           printsize = borders[idx].low - i;
1596         os << par.substr(i, printsize);
1597         i += printsize;
1598         handleParentheses(i, false);
1599         if (i >= borders[idx].low)
1600           i = borders[idx].upper;
1601       }
1602       else {
1603         i = borders[idx].upper;
1604       }
1605     }
1606     else
1607       break;
1608   }
1609   if (lastpos > i) {
1610     os << par.substr(i, lastpos-i);
1611   }
1612   handleParentheses(lastpos, false);
1613   for (int i = actualdeptindex; i > 0; --i) {
1614     os << "}";
1615   }
1616   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1617 }
1618
1619 void LatexInfo::processRegion(int start, int region_end)
1620 {
1621   while (start < region_end) {          /* Let {[} and {]} survive */
1622     if ((interval.par[start] == '{') &&
1623         (interval.par[start+1] != ']') &&
1624         (interval.par[start+1] != '[')) {
1625       // Closing is allowed past the region
1626       int closing = interval.findclosing(start+1, interval.par.length());
1627       interval.addIntervall(start, start+1);
1628       interval.addIntervall(closing, closing+1);
1629     }
1630     start = interval.nextNotIgnored(start+1);
1631   }
1632 }
1633
1634 void LatexInfo::removeHead(KeyInfo &actual, int count)
1635 {
1636   if (actual.parenthesiscount == 0) {
1637     // "{\tiny{} ...}" ==> "{{} ...}"
1638     interval.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
1639   }
1640   else {
1641     // Remove header hull, that is "\url{abcd}" ==> "abcd"
1642     interval.addIntervall(actual._tokenstart, actual._dataStart);
1643     interval.addIntervall(actual._dataEnd, actual._dataEnd+1);
1644   }
1645 }
1646
1647 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
1648 {
1649   int nextKeyIdx;
1650   switch (actual.keytype)
1651     {
1652     case KeyInfo::isChar: {
1653       nextKeyIdx = getNextKey();
1654       break;
1655     }
1656     case KeyInfo::isSize: {
1657       if (actual.disabled) {
1658         // Allways disabled
1659         processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
1660         interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1661         nextKeyIdx = getNextKey();
1662       } else {
1663         // Split on this key if not at start
1664         int start = interval.nextNotIgnored(previousStart);
1665         if (start < actual._tokenstart) {
1666           interval.output(os, actual._tokenstart);
1667           interval.addIntervall(start, actual._tokenstart);
1668         }
1669         // discard entry if at end of actual
1670         nextKeyIdx = process(os, actual);
1671       }
1672       break;
1673     }
1674     case KeyInfo::isStandard: {
1675       if (actual.disabled) {
1676         removeHead(actual);
1677         processRegion(actual._dataStart, actual._dataStart+1);
1678         nextKeyIdx = getNextKey();
1679       } else {
1680         // Split on this key if not at start
1681         int start = interval.nextNotIgnored(previousStart);
1682         if (start < actual._tokenstart) {
1683           interval.output(os, actual._tokenstart);
1684           interval.addIntervall(start, actual._tokenstart);
1685         }
1686         // discard entry if at end of actual
1687         nextKeyIdx = process(os, actual);
1688       }
1689       break;
1690     }
1691     case KeyInfo::doRemove: {
1692       // Remove the key with all parameters
1693       interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1694       nextKeyIdx = getNextKey();
1695       break;
1696     }
1697     case KeyInfo::isSectioning: {
1698       // Discard space before _tokenstart
1699       int count;
1700       for (count = 0; count < actual._tokenstart; count++) {
1701         if (interval.par[actual._tokenstart-count-1] != ' ')
1702           break;
1703       }
1704       if (actual.disabled) {
1705         removeHead(actual, count);
1706         nextKeyIdx = getNextKey();
1707       } else {
1708         interval.addIntervall(actual._tokenstart-count, actual._tokenstart);
1709         nextKeyIdx = process(os, actual);
1710       }
1711       break;
1712     }
1713     case KeyInfo::isMath: {
1714       // Same as regex, use the content unchanged
1715       nextKeyIdx = getNextKey();
1716       break;
1717     }
1718     case KeyInfo::isRegex: {
1719       // DO NOT SPLIT ON REGEX
1720       // Do not disable
1721       nextKeyIdx = getNextKey();
1722       break;
1723     }
1724     case KeyInfo::isIgnored: {
1725       // Treat like a character for now
1726       nextKeyIdx = getNextKey();
1727       break;
1728     }
1729     case KeyInfo::isMain: {
1730       if (actual.disabled) {
1731         removeHead(actual);
1732         if ((interval.par.substr(actual._dataStart, 3) == " \\[") ||
1733             (interval.par.substr(actual._dataStart, 8) == " \\begin{")) {
1734           // Discard also the space before math-equation
1735           interval.addIntervall(actual._dataStart, actual._dataStart+1);
1736         }
1737         interval.resetOpenedP(actual._dataStart-1);
1738       }
1739       else {
1740         if (actual._tokenstart == 0) {
1741           // for the first (and maybe dummy) language
1742           interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1743         }
1744         interval.resetOpenedP(actual._dataStart-1);
1745       }
1746       break;
1747     }
1748     case KeyInfo::invalid:
1749       // This cannot happen, already handled
1750       // fall through
1751     default: {
1752       // LYXERR0("Unhandled keytype");
1753       nextKeyIdx = getNextKey();
1754       break;
1755     }
1756     }
1757   return(nextKeyIdx);
1758 }
1759
1760 int LatexInfo::process(ostringstream &os, KeyInfo &actual )
1761 {
1762   int end = interval.nextNotIgnored(actual._dataEnd);
1763   int oldStart = actual._dataStart;
1764   int nextKeyIdx = getNextKey();
1765   while (true) {
1766     if ((nextKeyIdx < 0) ||
1767         (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1768         (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1769       if (oldStart <= end) {
1770         processRegion(oldStart, end);
1771         oldStart = end+1;
1772       }
1773       break;
1774     }
1775     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1776
1777     if (nextKey.keytype == KeyInfo::isMain) {
1778       (void) dispatch(os, actual._dataStart, nextKey);
1779       end = nextKey._tokenstart;
1780       break;
1781     }
1782     processRegion(oldStart, nextKey._tokenstart);
1783     nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
1784
1785     oldStart = nextKey._dataEnd+1;
1786   }
1787   // now nextKey is either invalid or is outside of actual._dataEnd
1788   // output the remaining and discard myself
1789   if (oldStart <= end) {
1790     processRegion(oldStart, end);
1791   }
1792   if (interval.par[end] == '}') {
1793     end += 1;
1794     // This is the normal case.
1795     // But if using the firstlanguage, the closing may be missing
1796   }
1797   // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
1798   int output_end;
1799   if (actual._dataEnd < end)
1800     output_end = interval.nextNotIgnored(actual._dataEnd);
1801   else
1802     output_end = interval.nextNotIgnored(end);
1803   if (interval.nextNotIgnored(actual._dataStart) < output_end)
1804     interval.output(os, output_end);
1805   interval.addIntervall(actual._tokenstart, end);
1806   return nextKeyIdx;
1807 }
1808
1809 string splitOnKnownMacros(string par, bool isPatternString) {
1810   ostringstream os;
1811   LatexInfo li(par, isPatternString);
1812   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
1813   DummyKey.head = "";
1814   DummyKey._tokensize = 0;
1815   DummyKey._tokenstart = 0;
1816   DummyKey._dataStart = 0;
1817   DummyKey._dataEnd = par.length();
1818   DummyKey.disabled = true;
1819   int firstkeyIdx = li.getFirstKey();
1820   string s;
1821   if (firstkeyIdx >= 0) {
1822     KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
1823     int nextkeyIdx;
1824     if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
1825       // Create dummy firstKey
1826       firstKey = DummyKey;
1827       (void) li.setNextKey(firstkeyIdx);
1828     }
1829     nextkeyIdx = li.process(os, firstKey);
1830     while (nextkeyIdx >= 0) {
1831       // Check for a possible gap between the last
1832       // entry and this one
1833       int datastart = li.nextNotIgnored(firstKey._dataStart);
1834       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1835       if ((nextKey._tokenstart > datastart)) {
1836         // Handle the gap
1837         firstKey._dataStart = datastart;
1838         firstKey._dataEnd = par.length();
1839         (void) li.setNextKey(nextkeyIdx);
1840         if (firstKey._tokensize > 0)
1841           li.setForDefaultLang(firstKey._tokensize);
1842         // Fake the last opened parenthesis
1843         nextkeyIdx = li.process(os, firstKey);
1844       }
1845       else {
1846         if (nextKey.keytype != KeyInfo::isMain) {
1847           firstKey._dataStart = datastart;
1848           firstKey._dataEnd = nextKey._dataEnd+1;
1849           (void) li.setNextKey(nextkeyIdx);
1850           if (firstKey._tokensize > 0)
1851             li.setForDefaultLang(firstKey._tokensize);
1852           nextkeyIdx = li.process(os, firstKey);
1853         }
1854         else {
1855           nextkeyIdx = li.process(os, nextKey);
1856         }
1857       }
1858     }
1859     // Handle the remaining
1860     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1861     firstKey._dataEnd = par.length();
1862     if (firstKey._dataStart < firstKey._dataEnd)
1863       (void) li.process(os, firstKey);
1864     s = os.str();
1865   }
1866   else
1867     s = par;                            /* no known macros found */
1868   return s;
1869 }
1870
1871 /*
1872  * Try to unify the language specs in the latexified text.
1873  * Resulting modified string is set to "", if
1874  * the searched tex does not contain all the features in the search pattern
1875  */
1876 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
1877 {
1878         static Features regex_f;
1879         static int missed = 0;
1880         static bool regex_with_format = false;
1881
1882         int parlen = par.length();
1883
1884         while ((parlen > 0) && (par[parlen-1] == '\n')) {
1885                 parlen--;
1886         }
1887         string result;
1888         if (withformat) {
1889                 // Split the latex input into pieces which
1890                 // can be digested by our search engine
1891                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
1892                 result = splitOnKnownMacros(par, isPatternString);
1893                 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1894         }
1895         else
1896                 result = par.substr(0, parlen);
1897         if (isPatternString) {
1898                 missed = 0;
1899                 if (withformat) {
1900                         regex_f = identifyFeatures(result);
1901                         string features = "";
1902                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1903                                 string a = it->first;
1904                                 regex_with_format = true;
1905                                 features += " " + a;
1906                                 // LYXERR0("Identified regex format:" << a);
1907                         }
1908                         LYXERR(Debug::FIND, "Identified Features" << features);
1909
1910                 }
1911         } else if (regex_with_format) {
1912                 Features info = identifyFeatures(result);
1913                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1914                         string a = it->first;
1915                         bool b = it->second;
1916                         if (b && ! info[a]) {
1917                                 missed++;
1918                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1919                                 return("");
1920                         }
1921                 }
1922         }
1923         else {
1924                 // LYXERR0("No regex formats");
1925         }
1926         return(result);
1927 }
1928
1929
1930 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1931 static int identifyClosing(string & t)
1932 {
1933         int open_braces = 0;
1934         do {
1935                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1936                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1937                         continue;
1938                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1939                         continue;
1940                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1941                         continue;
1942                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1943                         ++open_braces;
1944                         continue;
1945                 }
1946                 break;
1947         } while (true);
1948         return open_braces;
1949 }
1950
1951
1952 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1953         : p_buf(&buf), p_first_buf(&buf), opt(opt)
1954 {
1955         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1956         docstring const & ds = stringifySearchBuffer(find_buf, opt);
1957         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1958         // When using regexp, braces are hacked already by escape_for_regex()
1959         par_as_string = normalize(ds, !use_regexp);
1960         open_braces = 0;
1961         close_wildcards = 0;
1962
1963         size_t lead_size = 0;
1964         // correct the language settings
1965         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1966         if (opt.ignoreformat) {
1967                 if (!use_regexp) {
1968                         // if par_as_string_nolead were emty,
1969                         // the following call to findAux will always *find* the string
1970                         // in the checked data, and thus always using the slow
1971                         // examining of the current text part.
1972                         par_as_string_nolead = par_as_string;
1973                 }
1974         } else {
1975                 lead_size = identifyLeading(par_as_string);
1976                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1977                 lead_as_string = par_as_string.substr(0, lead_size);
1978                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1979         }
1980
1981         if (!use_regexp) {
1982                 open_braces = identifyClosing(par_as_string);
1983                 identifyClosing(par_as_string_nolead);
1984                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1985                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1986         } else {
1987                 string lead_as_regexp;
1988                 if (lead_size > 0) {
1989                         // @todo No need to search for \regexp{} insets in leading material
1990                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1991                         par_as_string = par_as_string_nolead;
1992                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1993                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1994                 }
1995                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1996                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1997                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1998                 if (
1999                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2000                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2001                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2002                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2003                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2004                         || regex_replace(par_as_string, par_as_string,
2005                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2006                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2007                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2008                         ) {
2009                         ++close_wildcards;
2010                 }
2011                 if (!opt.ignoreformat) {
2012                         // Remove extra '\}' at end
2013                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
2014                                 open_braces++;
2015                         }
2016                         // save '\.'
2017                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2018                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2019                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2020                         // replace '[^...]' with '[^...\}\{\\]'
2021                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2022                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2023                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
2024                         // restore '\.'
2025                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
2026                 }
2027                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2028                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2029                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
2030                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
2031
2032                 // If entered regexp must match at begin of searched string buffer
2033                 // Kornel: Added parentheses to use $1 for size of the leading string
2034                 string regexp_str;
2035                 string regexp2_str;
2036                 {
2037                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
2038                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
2039                         // so the convert has no effect in that case
2040                         for (int i = 8; i > 0; --i) {
2041                                 string orig = "\\\\" + std::to_string(i);
2042                                 string dest = "\\" + std::to_string(i+1);
2043                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
2044                         }
2045                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
2046                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
2047                 }
2048                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
2049                 regexp = lyx::regex(regexp_str);
2050
2051                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
2052                 regexp2 = lyx::regex(regexp2_str);
2053         }
2054 }
2055
2056
2057 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
2058 {
2059         if (at_begin &&
2060                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
2061                 return 0;
2062
2063         docstring docstr = stringifyFromForSearch(opt, cur, len);
2064         string str = normalize(docstr, true);
2065         if (!opt.ignoreformat) {
2066                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
2067         }
2068         if (str.empty()) return(-1);
2069         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
2070         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
2071
2072         if (use_regexp) {
2073                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
2074                 regex const *p_regexp;
2075                 regex_constants::match_flag_type flags;
2076                 if (at_begin) {
2077                         flags = regex_constants::match_continuous;
2078                         p_regexp = &regexp;
2079                 } else {
2080                         flags = regex_constants::match_default;
2081                         p_regexp = &regexp2;
2082                 }
2083                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
2084                 if (re_it == sregex_iterator())
2085                         return 0;
2086                 match_results<string::const_iterator> const & m = *re_it;
2087
2088                 if (0) { // Kornel Benko: DO NOT CHECKK
2089                         // Check braces on the segment that matched the entire regexp expression,
2090                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
2091                         if (!braces_match(m[0].first, m[0].second, open_braces))
2092                                 return 0;
2093                 }
2094
2095                 // Check braces on segments that matched all (.*?) subexpressions,
2096                 // except the last "padding" one inserted by lyx.
2097                 for (size_t i = 1; i < m.size() - 1; ++i)
2098                         if (!braces_match(m[i].first, m[i].second, open_braces))
2099                                 return 0;
2100
2101                 // Exclude from the returned match length any length
2102                 // due to close wildcards added at end of regexp
2103                 // and also the length of the leading (e.g. '\emph{')
2104                 //
2105                 // Whole found string, including the leading: m[0].second - m[0].first
2106                 // Size of the leading string: m[1].second - m[1].first
2107                 int leadingsize = 0;
2108                 if (m.size() > 1)
2109                         leadingsize = m[1].second - m[1].first;
2110                 int result;
2111                 for (size_t i = 0; i < m.size(); i++) {
2112                   LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2113                 }
2114                 if (close_wildcards == 0)
2115                         result = m[0].second - m[0].first;
2116
2117                 else
2118                         result =  m[m.size() - close_wildcards].first - m[0].first;
2119
2120                 if (result > leadingsize)
2121                         result -= leadingsize;
2122                 else
2123                         result = 0;
2124                 return(result);
2125         }
2126
2127         // else !use_regexp: but all code paths above return
2128         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2129                                  << par_as_string << "', str='" << str << "'");
2130         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2131                                  << lead_as_string << "', par_as_string_nolead='"
2132                                  << par_as_string_nolead << "'");
2133
2134         if (at_begin) {
2135                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
2136                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
2137                 if (str.substr(0, par_as_string.size()) == par_as_string)
2138                         return par_as_string.size();
2139         } else {
2140                 size_t pos = str.find(par_as_string_nolead);
2141                 if (pos != string::npos)
2142                         return par_as_string.size();
2143         }
2144         return 0;
2145 }
2146
2147
2148 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
2149 {
2150         int res = findAux(cur, len, at_begin);
2151         LYXERR(Debug::FIND,
2152                "res=" << res << ", at_begin=" << at_begin
2153                << ", matchword=" << opt.matchword
2154                << ", inTexted=" << cur.inTexted());
2155         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
2156                 return res;
2157         Paragraph const & par = cur.paragraph();
2158         bool ws_left = (cur.pos() > 0)
2159                 ? par.isWordSeparator(cur.pos() - 1)
2160                 : true;
2161         bool ws_right = (cur.pos() + res < par.size())
2162                 ? par.isWordSeparator(cur.pos() + res)
2163                 : true;
2164         LYXERR(Debug::FIND,
2165                "cur.pos()=" << cur.pos() << ", res=" << res
2166                << ", separ: " << ws_left << ", " << ws_right
2167                << endl);
2168         if (ws_left && ws_right)
2169                 return res;
2170         return 0;
2171 }
2172
2173
2174 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
2175 {
2176         string t;
2177         if (! opt.casesensitive)
2178                 t = lyx::to_utf8(lowercase(s));
2179         else
2180                 t = lyx::to_utf8(s);
2181         // Remove \n at begin
2182         while (!t.empty() && t[0] == '\n')
2183                 t = t.substr(1);
2184         // Remove \n at end
2185         while (!t.empty() && t[t.size() - 1] == '\n')
2186                 t = t.substr(0, t.size() - 1);
2187         size_t pos;
2188         // Replace all other \n with spaces
2189         while ((pos = t.find("\n")) != string::npos)
2190                 t.replace(pos, 1, " ");
2191         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
2192         // Kornel: Added textsl, textsf, textit, texttt and noun
2193         // + allow to seach for colored text too
2194         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
2195         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
2196                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2197         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
2198                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2199
2200         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
2201         // FIXME - check what preceeds the brace
2202         if (hack_braces) {
2203                 if (opt.ignoreformat)
2204                         while (regex_replace(t, t, "\\{", "_x_<")
2205                                || regex_replace(t, t, "\\}", "_x_>"))
2206                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2207                 else
2208                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
2209                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
2210                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2211         }
2212
2213         return t;
2214 }
2215
2216
2217 docstring stringifyFromCursor(DocIterator const & cur, int len)
2218 {
2219         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2220         if (cur.inTexted()) {
2221                 Paragraph const & par = cur.paragraph();
2222                 // TODO what about searching beyond/across paragraph breaks ?
2223                 // TODO Try adding a AS_STR_INSERTS as last arg
2224                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2225                         int(par.size()) : cur.pos() + len;
2226                 OutputParams runparams(&cur.buffer()->params().encoding());
2227                 runparams.nice = true;
2228                 runparams.flavor = OutputParams::LATEX;
2229                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2230                 // No side effect of file copying and image conversion
2231                 runparams.dryrun = true;
2232                 LYXERR(Debug::FIND, "Stringifying with cur: "
2233                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
2234                 return par.asString(cur.pos(), end,
2235                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2236                         &runparams);
2237         } else if (cur.inMathed()) {
2238                 docstring s;
2239                 CursorSlice cs = cur.top();
2240                 MathData md = cs.cell();
2241                 MathData::const_iterator it_end =
2242                         (( len == -1 || cs.pos() + len > int(md.size()))
2243                          ? md.end()
2244                          : md.begin() + cs.pos() + len );
2245                 for (MathData::const_iterator it = md.begin() + cs.pos();
2246                      it != it_end; ++it)
2247                         s = s + asString(*it);
2248                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2249                 return s;
2250         }
2251         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2252         return docstring();
2253 }
2254
2255
2256 /** Computes the LaTeX export of buf starting from cur and ending len positions
2257  * after cur, if len is positive, or at the paragraph or innermost inset end
2258  * if len is -1.
2259  */
2260 docstring latexifyFromCursor(DocIterator const & cur, int len)
2261 {
2262         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2263         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2264                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2265         Buffer const & buf = *cur.buffer();
2266
2267         odocstringstream ods;
2268         otexstream os(ods);
2269         OutputParams runparams(&buf.params().encoding());
2270         runparams.nice = false;
2271         runparams.flavor = OutputParams::LATEX;
2272         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2273         // No side effect of file copying and image conversion
2274         runparams.dryrun = true;
2275         runparams.for_search = true;
2276
2277         if (cur.inTexted()) {
2278                 // @TODO what about searching beyond/across paragraph breaks ?
2279                 pos_type endpos = cur.paragraph().size();
2280                 if (len != -1 && endpos > cur.pos() + len)
2281                         endpos = cur.pos() + len;
2282                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2283                           string(), cur.pos(), endpos);
2284                 string s = lyx::to_utf8(ods.str());
2285                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2286                 return(lyx::from_utf8(s));
2287         } else if (cur.inMathed()) {
2288                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2289                 for (int s = cur.depth() - 1; s >= 0; --s) {
2290                         CursorSlice const & cs = cur[s];
2291                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2292                                 WriteStream ws(os);
2293                                 cs.asInsetMath()->asHullInset()->header_write(ws);
2294                                 break;
2295                         }
2296                 }
2297
2298                 CursorSlice const & cs = cur.top();
2299                 MathData md = cs.cell();
2300                 MathData::const_iterator it_end =
2301                         ((len == -1 || cs.pos() + len > int(md.size()))
2302                          ? md.end()
2303                          : md.begin() + cs.pos() + len);
2304                 for (MathData::const_iterator it = md.begin() + cs.pos();
2305                      it != it_end; ++it)
2306                         ods << asString(*it);
2307
2308                 // Retrieve the math environment type, and add '$' or '$]'
2309                 // or others (\end{equation}) accordingly
2310                 for (int s = cur.depth() - 1; s >= 0; --s) {
2311                         CursorSlice const & cs2 = cur[s];
2312                         InsetMath * inset = cs2.asInsetMath();
2313                         if (inset && inset->asHullInset()) {
2314                                 WriteStream ws(os);
2315                                 inset->asHullInset()->footer_write(ws);
2316                                 break;
2317                         }
2318                 }
2319                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2320         } else {
2321                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2322         }
2323         return ods.str();
2324 }
2325
2326
2327 /** Finalize an advanced find operation, advancing the cursor to the innermost
2328  ** position that matches, plus computing the length of the matching text to
2329  ** be selected
2330  **/
2331 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2332 {
2333         // Search the foremost position that matches (avoids find of entire math
2334         // inset when match at start of it)
2335         size_t d;
2336         DocIterator old_cur(cur.buffer());
2337         do {
2338                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2339                 d = cur.depth();
2340                 old_cur = cur;
2341                 cur.forwardPos();
2342         } while (cur && cur.depth() > d && match(cur) > 0);
2343         cur = old_cur;
2344         if (match(cur) <= 0) return 0;
2345         LYXERR(Debug::FIND, "Ok");
2346
2347         // Compute the match length
2348         int len = 1;
2349         if (cur.pos() + len > cur.lastpos())
2350                 return 0;
2351         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2352         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2353                 ++len;
2354                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2355         }
2356         // Length of matched text (different from len param)
2357         int old_len = match(cur, len);
2358         if (old_len < 0) old_len = 0;
2359         int new_len;
2360         // Greedy behaviour while matching regexps
2361         while ((new_len = match(cur, len + 1)) > old_len) {
2362                 ++len;
2363                 old_len = new_len;
2364                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
2365         }
2366         return len;
2367 }
2368
2369
2370 /// Finds forward
2371 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2372 {
2373         if (!cur)
2374                 return 0;
2375         while (!theApp()->longOperationCancelled() && cur) {
2376                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2377                 int match_len = match(cur, -1, false);
2378                 LYXERR(Debug::FIND, "match_len: " << match_len);
2379                 if (match_len > 0) {
2380                         int match_len_zero_count = 0;
2381                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2382                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2383                                 int match_len2 = match(cur);
2384                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2385                                 if (match_len2 > 0) {
2386                                         // Sometimes in finalize we understand it wasn't a match
2387                                         // and we need to continue the outest loop
2388                                         int len = findAdvFinalize(cur, match);
2389                                         if (len > 0) {
2390                                                 return len;
2391                                         }
2392                                 }
2393                                 if (match_len2 >= 0) {
2394                                         if (match_len2 == 0)
2395                                                 match_len_zero_count++;
2396                                         else
2397                                                 match_len_zero_count = 0;
2398                                 }
2399                                 else {
2400                                         if (++match_len_zero_count > 3) {
2401                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2402                                                 match_len_zero_count = 0;
2403                                         }
2404                                         break;
2405                                 }
2406                         }
2407                         if (!cur)
2408                                 return 0;
2409                 }
2410                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2411                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2412                         cur.forwardPar();
2413                 } else {
2414                         // This should exit nested insets, if any, or otherwise undefine the currsor.
2415                         cur.pos() = cur.lastpos();
2416                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2417                         cur.forwardPos();
2418                 }
2419         }
2420         return 0;
2421 }
2422
2423
2424 /// Find the most backward consecutive match within same paragraph while searching backwards.
2425 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2426 {
2427         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2428         DocIterator tmp_cur = cur;
2429         int len = findAdvFinalize(tmp_cur, match);
2430         Inset & inset = cur.inset();
2431         for (; cur != cur_begin; cur.backwardPos()) {
2432                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2433                 DocIterator new_cur = cur;
2434                 new_cur.backwardPos();
2435                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2436                         break;
2437                 int new_len = findAdvFinalize(new_cur, match);
2438                 if (new_len == len)
2439                         break;
2440                 len = new_len;
2441         }
2442         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2443         return len;
2444 }
2445
2446
2447 /// Finds backwards
2448 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2449 {
2450         if (! cur)
2451                 return 0;
2452         // Backup of original position
2453         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2454         if (cur == cur_begin)
2455                 return 0;
2456         cur.backwardPos();
2457         DocIterator cur_orig(cur);
2458         bool pit_changed = false;
2459         do {
2460                 cur.pos() = 0;
2461                 bool found_match = match(cur, -1, false);
2462
2463                 if (found_match) {
2464                         if (pit_changed)
2465                                 cur.pos() = cur.lastpos();
2466                         else
2467                                 cur.pos() = cur_orig.pos();
2468                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2469                         DocIterator cur_prev_iter;
2470                         do {
2471                                 found_match = match(cur);
2472                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2473                                        << found_match << ", cur: " << cur);
2474                                 if (found_match)
2475                                         return findMostBackwards(cur, match);
2476
2477                                 // Stop if begin of document reached
2478                                 if (cur == cur_begin)
2479                                         break;
2480                                 cur_prev_iter = cur;
2481                                 cur.backwardPos();
2482                         } while (true);
2483                 }
2484                 if (cur == cur_begin)
2485                         break;
2486                 if (cur.pit() > 0)
2487                         --cur.pit();
2488                 else
2489                         cur.backwardPos();
2490                 pit_changed = true;
2491         } while (!theApp()->longOperationCancelled());
2492         return 0;
2493 }
2494
2495
2496 } // namespace
2497
2498
2499 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2500                                  DocIterator const & cur, int len)
2501 {
2502         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2503                 return docstring();
2504         if (!opt.ignoreformat)
2505                 return latexifyFromCursor(cur, len);
2506         else
2507                 return stringifyFromCursor(cur, len);
2508 }
2509
2510
2511 FindAndReplaceOptions::FindAndReplaceOptions(
2512         docstring const & find_buf_name, bool casesensitive,
2513         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2514         docstring const & repl_buf_name, bool keep_case,
2515         SearchScope scope, SearchRestriction restr)
2516         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2517           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2518           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2519 {
2520 }
2521
2522
2523 namespace {
2524
2525
2526 /** Check if 'len' letters following cursor are all non-lowercase */
2527 static bool allNonLowercase(Cursor const & cur, int len)
2528 {
2529         pos_type beg_pos = cur.selectionBegin().pos();
2530         pos_type end_pos = cur.selectionBegin().pos() + len;
2531         if (len > cur.lastpos() + 1 - beg_pos) {
2532                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2533                 len = cur.lastpos() + 1 - beg_pos;
2534                 end_pos = beg_pos + len;
2535         }
2536         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2537                 if (isLowerCase(cur.paragraph().getChar(pos)))
2538                         return false;
2539         return true;
2540 }
2541
2542
2543 /** Check if first letter is upper case and second one is lower case */
2544 static bool firstUppercase(Cursor const & cur)
2545 {
2546         char_type ch1, ch2;
2547         pos_type pos = cur.selectionBegin().pos();
2548         if (pos >= cur.lastpos() - 1) {
2549                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2550                 return false;
2551         }
2552         ch1 = cur.paragraph().getChar(pos);
2553         ch2 = cur.paragraph().getChar(pos + 1);
2554         bool result = isUpperCase(ch1) && isLowerCase(ch2);
2555         LYXERR(Debug::FIND, "firstUppercase(): "
2556                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2557                << ch2 << "(" << char(ch2) << ")"
2558                << ", result=" << result << ", cur=" << cur);
2559         return result;
2560 }
2561
2562
2563 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2564  **
2565  ** \fixme What to do with possible further paragraphs in replace buffer ?
2566  **/
2567 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2568 {
2569         ParagraphList::iterator pit = buffer.paragraphs().begin();
2570         LASSERT(pit->size() >= 1, /**/);
2571         pos_type right = pos_type(1);
2572         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2573         right = pit->size();
2574         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2575 }
2576
2577 } // namespace
2578
2579 ///
2580 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2581 {
2582         Cursor & cur = bv->cursor();
2583         if (opt.repl_buf_name == docstring()
2584             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2585             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2586                 return;
2587
2588         DocIterator sel_beg = cur.selectionBegin();
2589         DocIterator sel_end = cur.selectionEnd();
2590         if (&sel_beg.inset() != &sel_end.inset()
2591             || sel_beg.pit() != sel_end.pit()
2592             || sel_beg.idx() != sel_end.idx())
2593                 return;
2594         int sel_len = sel_end.pos() - sel_beg.pos();
2595         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2596                << ", sel_len: " << sel_len << endl);
2597         if (sel_len == 0)
2598                 return;
2599         LASSERT(sel_len > 0, return);
2600
2601         if (!matchAdv(sel_beg, sel_len))
2602                 return;
2603
2604         // Build a copy of the replace buffer, adapted to the KeepCase option
2605         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2606         ostringstream oss;
2607         repl_buffer_orig.write(oss);
2608         string lyx = oss.str();
2609         Buffer repl_buffer("", false);
2610         repl_buffer.setUnnamed(true);
2611         LASSERT(repl_buffer.readString(lyx), return);
2612         if (opt.keep_case && sel_len >= 2) {
2613                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2614                 if (cur.inTexted()) {
2615                         if (firstUppercase(cur))
2616                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2617                         else if (allNonLowercase(cur, sel_len))
2618                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2619                 }
2620         }
2621         cap::cutSelection(cur, false);
2622         if (cur.inTexted()) {
2623                 repl_buffer.changeLanguage(
2624                         repl_buffer.language(),
2625                         cur.getFont().language());
2626                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2627                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2628                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2629                                         repl_buffer.params().documentClassPtr(),
2630                                         bv->buffer().errorList("Paste"));
2631                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2632                 sel_len = repl_buffer.paragraphs().begin()->size();
2633         } else if (cur.inMathed()) {
2634                 odocstringstream ods;
2635                 otexstream os(ods);
2636                 OutputParams runparams(&repl_buffer.params().encoding());
2637                 runparams.nice = false;
2638                 runparams.flavor = OutputParams::LATEX;
2639                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2640                 runparams.dryrun = true;
2641                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2642                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2643                 docstring repl_latex = ods.str();
2644                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2645                 string s;
2646                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2647                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2648                 repl_latex = from_utf8(s);
2649                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2650                 MathData ar(cur.buffer());
2651                 asArray(repl_latex, ar, Parse::NORMAL);
2652                 cur.insert(ar);
2653                 sel_len = ar.size();
2654                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2655         }
2656         if (cur.pos() >= sel_len)
2657                 cur.pos() -= sel_len;
2658         else
2659                 cur.pos() = 0;
2660         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2661         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2662         bv->processUpdateFlags(Update::Force);
2663 }
2664
2665
2666 /// Perform a FindAdv operation.
2667 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2668 {
2669         DocIterator cur;
2670         int match_len = 0;
2671
2672         // e.g., when invoking word-findadv from mini-buffer wither with
2673         //       wrong options syntax or before ever opening advanced F&R pane
2674         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2675                 return false;
2676
2677         try {
2678                 MatchStringAdv matchAdv(bv->buffer(), opt);
2679                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2680                 if (length > 0)
2681                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2682                 findAdvReplace(bv, opt, matchAdv);
2683                 cur = bv->cursor();
2684                 if (opt.forward)
2685                         match_len = findForwardAdv(cur, matchAdv);
2686                 else
2687                         match_len = findBackwardsAdv(cur, matchAdv);
2688         } catch (...) {
2689                 // This may only be raised by lyx::regex()
2690                 bv->message(_("Invalid regular expression!"));
2691                 return false;
2692         }
2693
2694         if (match_len == 0) {
2695                 bv->message(_("Match not found!"));
2696                 return false;
2697         }
2698
2699         bv->message(_("Match found!"));
2700
2701         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2702         bv->putSelectionAt(cur, match_len, !opt.forward);
2703
2704         return true;
2705 }
2706
2707
2708 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2709 {
2710         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2711            << opt.casesensitive << ' '
2712            << opt.matchword << ' '
2713            << opt.forward << ' '
2714            << opt.expandmacros << ' '
2715            << opt.ignoreformat << ' '
2716            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2717            << opt.keep_case << ' '
2718            << int(opt.scope) << ' '
2719            << int(opt.restr);
2720
2721         LYXERR(Debug::FIND, "built: " << os.str());
2722
2723         return os;
2724 }
2725
2726
2727 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2728 {
2729         LYXERR(Debug::FIND, "parsing");
2730         string s;
2731         string line;
2732         getline(is, line);
2733         while (line != "EOSS") {
2734                 if (! s.empty())
2735                         s = s + "\n";
2736                 s = s + line;
2737                 if (is.eof())   // Tolerate malformed request
2738                         break;
2739                 getline(is, line);
2740         }
2741         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2742         opt.find_buf_name = from_utf8(s);
2743         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2744         is.get();       // Waste space before replace string
2745         s = "";
2746         getline(is, line);
2747         while (line != "EOSS") {
2748                 if (! s.empty())
2749                         s = s + "\n";
2750                 s = s + line;
2751                 if (is.eof())   // Tolerate malformed request
2752                         break;
2753                 getline(is, line);
2754         }
2755         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2756         opt.repl_buf_name = from_utf8(s);
2757         is >> opt.keep_case;
2758         int i;
2759         is >> i;
2760         opt.scope = FindAndReplaceOptions::SearchScope(i);
2761         is >> i;
2762         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2763
2764         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2765                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2766                << opt.scope << ' ' << opt.restr);
2767         return is;
2768 }
2769
2770 } // namespace lyx