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