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