]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
FindAdv: Optimization
[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  * \author Kornel Benko
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "lyxfind.h"
19
20 #include "Buffer.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 "Text.h"
33 #include "Encoding.h"
34 #include "Language.h"
35
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathData.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
44
45 #include "support/debug.h"
46 #include "support/docstream.h"
47 #include "support/FileName.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
52
53 #include <unordered_map>
54 #include <regex>
55
56 //#define ResultsDebug
57 #define USE_QT_FOR_SEARCH
58 #if defined(USE_QT_FOR_SEARCH)
59         #include <QtCore>       // sets QT_VERSION
60         #if (QT_VERSION >= 0x050000)
61                 #include <QRegularExpression>
62                 #define QTSEARCH 1
63         #else
64                 #define QTSEARCH 0
65         #endif
66 #else
67         #define QTSEARCH 0
68 #endif
69
70 using namespace std;
71 using namespace lyx::support;
72
73 namespace lyx {
74
75 typedef unordered_map<string, string> AccentsMap;
76 typedef unordered_map<string,string>::const_iterator AccentsIterator;
77 static AccentsMap accents = unordered_map<string, string>();
78
79 // Helper class for deciding what should be ignored
80 class IgnoreFormats {
81  public:
82         ///
83         IgnoreFormats() = default;
84         ///
85         bool getFamily() const { return ignoreFamily_; }
86         ///
87         bool getSeries() const { return ignoreSeries_; }
88         ///
89         bool getShape() const { return ignoreShape_; }
90         ///
91         bool getUnderline() const { return ignoreUnderline_; }
92         ///
93         bool getMarkUp() const { return ignoreMarkUp_; }
94         ///
95         bool getStrikeOut() const { return ignoreStrikeOut_; }
96         ///
97         bool getSectioning() const { return ignoreSectioning_; }
98         ///
99         bool getFrontMatter() const { return ignoreFrontMatter_; }
100         ///
101         bool getColor() const { return ignoreColor_; }
102         ///
103         bool getLanguage() const { return ignoreLanguage_; }
104         ///
105         bool getDeleted() const { return ignoreDeleted_; }
106         ///
107         void setIgnoreDeleted(bool value);
108         ///
109         void setIgnoreFormat(string const & type, bool value);
110
111 private:
112         ///
113         bool ignoreFamily_ = false;
114         ///
115         bool ignoreSeries_ = false;
116         ///
117         bool ignoreShape_ = false;
118         ///
119         bool ignoreUnderline_ = false;
120         ///
121         bool ignoreMarkUp_ = false;
122         ///
123         bool ignoreStrikeOut_ = false;
124         ///
125         bool ignoreSectioning_ = false;
126         ///
127         bool ignoreFrontMatter_ = false;
128         ///
129         bool ignoreColor_ = false;
130         ///
131         bool ignoreLanguage_ = false;
132         ///
133         bool ignoreDeleted_ = true;
134 };
135
136 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
137 {
138         if (type == "color") {
139                 ignoreColor_ = value;
140         }
141         else if (type == "language") {
142                 ignoreLanguage_ = value;
143         }
144         else if (type == "sectioning") {
145                 ignoreSectioning_ = value;
146                 ignoreFrontMatter_ = value;
147         }
148         else if (type == "font") {
149                 ignoreSeries_ = value;
150                 ignoreShape_ = value;
151                 ignoreFamily_ = value;
152         }
153         else if (type == "series") {
154                 ignoreSeries_ = value;
155         }
156         else if (type == "shape") {
157                 ignoreShape_ = value;
158         }
159         else if (type == "family") {
160                 ignoreFamily_ = value;
161         }
162         else if (type == "markup") {
163                 ignoreMarkUp_ = value;
164         }
165         else if (type == "underline") {
166                 ignoreUnderline_ = value;
167         }
168         else if (type == "strike") {
169                 ignoreStrikeOut_ = value;
170         }
171         else if (type == "deleted") {
172                 ignoreDeleted_ = value;
173         }
174 }
175
176 // The global variable that can be changed from outside
177 IgnoreFormats ignoreFormats;
178
179
180 void setIgnoreFormat(string const & type, bool value)
181 {
182   ignoreFormats.setIgnoreFormat(type, value);
183 }
184
185
186 namespace {
187
188 bool parse_bool(docstring & howto)
189 {
190         if (howto.empty())
191                 return false;
192         docstring var;
193         howto = split(howto, var, ' ');
194         return var == "1";
195 }
196
197
198 class MatchString
199 {
200 public:
201         MatchString(docstring const & s, bool cs, bool mw)
202                 : str(s), case_sens(cs), whole_words(mw)
203         {}
204
205         // returns true if the specified string is at the specified position
206         // del specifies whether deleted strings in ct mode will be considered
207         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
208         {
209                 return par.find(str, case_sens, whole_words, pos, del);
210         }
211
212 private:
213         // search string
214         docstring str;
215         // case sensitive
216         bool case_sens;
217         // match whole words only
218         bool whole_words;
219 };
220
221
222 int findForward(DocIterator & cur, MatchString const & match,
223                 bool find_del = true)
224 {
225         for (; cur; cur.forwardChar())
226                 if (cur.inTexted()) {
227                         int len = match(cur.paragraph(), cur.pos(), find_del);
228                         if (len > 0)
229                                 return len;
230                 }
231         return 0;
232 }
233
234
235 int findBackwards(DocIterator & cur, MatchString const & match,
236                   bool find_del = true)
237 {
238         while (cur) {
239                 cur.backwardChar();
240                 if (cur.inTexted()) {
241                         int len = match(cur.paragraph(), cur.pos(), find_del);
242                         if (len > 0)
243                                 return len;
244                 }
245         }
246         return 0;
247 }
248
249
250 bool searchAllowed(docstring const & str)
251 {
252         if (str.empty()) {
253                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
254                 return false;
255         }
256         return true;
257 }
258
259
260 bool findOne(BufferView * bv, docstring const & searchstr,
261              bool case_sens, bool whole, bool forward,
262              bool find_del = true, bool check_wrap = false)
263 {
264         if (!searchAllowed(searchstr))
265                 return false;
266
267         DocIterator cur = forward
268                 ? bv->cursor().selectionEnd()
269                 : bv->cursor().selectionBegin();
270
271         MatchString const match(searchstr, case_sens, whole);
272
273         int match_len = forward
274                 ? findForward(cur, match, find_del)
275                 : findBackwards(cur, match, find_del);
276
277         if (match_len > 0)
278                 bv->putSelectionAt(cur, match_len, !forward);
279         else if (check_wrap) {
280                 DocIterator cur_orig(bv->cursor());
281                 docstring q;
282                 if (forward)
283                         q = _("End of file reached while searching forward.\n"
284                           "Continue searching from the beginning?");
285                 else
286                         q = _("Beginning of file reached while searching backward.\n"
287                           "Continue searching from the end?");
288                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
289                         q, 0, 1, _("&Yes"), _("&No"));
290                 if (wrap_answer == 0) {
291                         if (forward) {
292                                 bv->cursor().clear();
293                                 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
294                         } else {
295                                 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
296                                 bv->cursor().backwardPos();
297                         }
298                         bv->clearSelection();
299                         if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
300                                 return true;
301                 }
302                 bv->cursor().setCursor(cur_orig);
303                 return false;
304         }
305
306         return match_len > 0;
307 }
308
309
310 int replaceAll(BufferView * bv,
311                docstring const & searchstr, docstring const & replacestr,
312                bool case_sens, bool whole)
313 {
314         Buffer & buf = bv->buffer();
315
316         if (!searchAllowed(searchstr) || buf.isReadonly())
317                 return 0;
318
319         DocIterator cur_orig(bv->cursor());
320
321         MatchString const match(searchstr, case_sens, whole);
322         int num = 0;
323
324         int const rsize = replacestr.size();
325         int const ssize = searchstr.size();
326
327         Cursor cur(*bv);
328         cur.setCursor(doc_iterator_begin(&buf));
329         int match_len = findForward(cur, match, false);
330         while (match_len > 0) {
331                 // Backup current cursor position and font.
332                 pos_type const pos = cur.pos();
333                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
334                 cur.recordUndo();
335                 int striked = ssize -
336                         cur.paragraph().eraseChars(pos, pos + match_len,
337                                                    buf.params().track_changes);
338                 cur.paragraph().insert(pos, replacestr, font,
339                                        Change(buf.params().track_changes
340                                               ? Change::INSERTED
341                                               : Change::UNCHANGED));
342                 for (int i = 0; i < rsize + striked; ++i)
343                         cur.forwardChar();
344                 ++num;
345                 match_len = findForward(cur, match, false);
346         }
347
348         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
349
350         cur_orig.fixIfBroken();
351         bv->setCursor(cur_orig);
352
353         return num;
354 }
355
356
357 // the idea here is that we are going to replace the string that
358 // is selected IF it is the search string.
359 // if there is a selection, but it is not the search string, then
360 // we basically ignore it. (FIXME We ought to replace only within
361 // the selection.)
362 // if there is no selection, then:
363 //  (i) if some search string has been provided, then we find it.
364 //      (think of how the dialog works when you hit "replace" the
365 //      first time.)
366 // (ii) if no search string has been provided, then we treat the
367 //      word the cursor is in as the search string. (why? i have no
368 //      idea.) but this only works in text?
369 //
370 // returns the number of replacements made (one, if any) and
371 // whether anything at all was done.
372 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
373                            docstring const & replacestr, bool case_sens,
374                            bool whole, bool forward, bool findnext)
375 {
376         Cursor & cur = bv->cursor();
377         if (!cur.selection()) {
378                 // no selection, non-empty search string: find it
379                 if (!searchstr.empty()) {
380                         bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
381                         return make_pair(found, 0);
382                 }
383                 // empty search string
384                 if (!cur.inTexted())
385                         // bail in math
386                         return make_pair(false, 0);
387                 // select current word and treat it as the search string.
388                 // This causes a minor bug as undo will restore this selection,
389                 // which the user did not create (#8986).
390                 cur.innerText()->selectWord(cur, WHOLE_WORD);
391                 searchstr = cur.selectionAsString(false, true);
392         }
393
394         // if we still don't have a search string, report the error
395         // and abort.
396         if (!searchAllowed(searchstr))
397                 return make_pair(false, 0);
398
399         bool have_selection = cur.selection();
400         docstring const selected = cur.selectionAsString(false, true);
401         bool match =
402                 case_sens
403                 ? searchstr == selected
404                 : compare_no_case(searchstr, selected) == 0;
405
406         // no selection or current selection is not search word:
407         // just find the search word
408         if (!have_selection || !match) {
409                 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
410                 return make_pair(found, 0);
411         }
412
413         // we're now actually ready to replace. if the buffer is
414         // read-only, we can't, though.
415         if (bv->buffer().isReadonly())
416                 return make_pair(false, 0);
417
418         cap::replaceSelectionWithString(cur, replacestr);
419         if (forward) {
420                 cur.pos() += replacestr.length();
421                 LASSERT(cur.pos() <= cur.lastpos(),
422                         cur.pos() = cur.lastpos());
423         }
424         if (findnext)
425                 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
426
427         return make_pair(true, 1);
428 }
429
430 } // namespace
431
432
433 docstring const find2string(docstring const & search,
434                             bool casesensitive, bool matchword, bool forward)
435 {
436         odocstringstream ss;
437         ss << search << '\n'
438            << int(casesensitive) << ' '
439            << int(matchword) << ' '
440            << int(forward);
441         return ss.str();
442 }
443
444
445 docstring const replace2string(docstring const & replace,
446                                docstring const & search,
447                                bool casesensitive, bool matchword,
448                                bool all, bool forward, bool findnext)
449 {
450         odocstringstream ss;
451         ss << replace << '\n'
452            << search << '\n'
453            << int(casesensitive) << ' '
454            << int(matchword) << ' '
455            << int(all) << ' '
456            << int(forward) << ' '
457            << int(findnext);
458         return ss.str();
459 }
460
461
462 bool lyxfind(BufferView * bv, FuncRequest const & ev)
463 {
464         if (!bv || ev.action() != LFUN_WORD_FIND)
465                 return false;
466
467         //lyxerr << "find called, cmd: " << ev << endl;
468
469         // data is of the form
470         // "<search>
471         //  <casesensitive> <matchword> <forward>"
472         docstring search;
473         docstring howto = split(ev.argument(), search, '\n');
474
475         bool casesensitive = parse_bool(howto);
476         bool matchword     = parse_bool(howto);
477         bool forward       = parse_bool(howto);
478
479         return findOne(bv, search, casesensitive, matchword, forward, false, true);
480 }
481
482
483 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
484 {
485         if (!bv || ev.action() != LFUN_WORD_REPLACE)
486                 return false;
487
488         // data is of the form
489         // "<search>
490         //  <replace>
491         //  <casesensitive> <matchword> <all> <forward> <findnext>"
492         docstring search;
493         docstring rplc;
494         docstring howto = split(ev.argument(), rplc, '\n');
495         howto = split(howto, search, '\n');
496
497         bool casesensitive = parse_bool(howto);
498         bool matchword     = parse_bool(howto);
499         bool all           = parse_bool(howto);
500         bool forward       = parse_bool(howto);
501         bool findnext      = howto.empty() ? true : parse_bool(howto);
502
503         bool update = false;
504
505         int replace_count = 0;
506         if (all) {
507                 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
508                 update = replace_count > 0;
509         } else {
510                 pair<bool, int> rv =
511                         replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
512                 update = rv.first;
513                 replace_count = rv.second;
514         }
515
516         Buffer const & buf = bv->buffer();
517         if (!update) {
518                 // emit message signal.
519                 buf.message(_("String not found."));
520         } else {
521                 if (replace_count == 0) {
522                         buf.message(_("String found."));
523                 } else if (replace_count == 1) {
524                         buf.message(_("String has been replaced."));
525                 } else {
526                         docstring const str =
527                                 bformat(_("%1$d strings have been replaced."), replace_count);
528                         buf.message(str);
529                 }
530         }
531         return update;
532 }
533
534
535 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
536 {
537         for (; cur; cur.forwardPos())
538                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
539                         return true;
540
541         if (check_wrap) {
542                 DocIterator cur_orig(bv->cursor());
543                 docstring q = _("End of file reached while searching forward.\n"
544                           "Continue searching from the beginning?");
545                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
546                         q, 0, 1, _("&Yes"), _("&No"));
547                 if (wrap_answer == 0) {
548                         bv->cursor().clear();
549                         bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
550                         bv->clearSelection();
551                         cur.setCursor(bv->cursor().selectionBegin());
552                         if (findNextChange(bv, cur, false))
553                                 return true;
554                 }
555                 bv->cursor().setCursor(cur_orig);
556         }
557
558         return false;
559 }
560
561
562 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
563 {
564         for (cur.backwardPos(); cur; cur.backwardPos()) {
565                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
566                         return true;
567         }
568
569         if (check_wrap) {
570                 DocIterator cur_orig(bv->cursor());
571                 docstring q = _("Beginning of file reached while searching backward.\n"
572                           "Continue searching from the end?");
573                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
574                         q, 0, 1, _("&Yes"), _("&No"));
575                 if (wrap_answer == 0) {
576                         bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
577                         bv->cursor().backwardPos();
578                         bv->clearSelection();
579                         cur.setCursor(bv->cursor().selectionBegin());
580                         if (findPreviousChange(bv, cur, false))
581                                 return true;
582                 }
583                 bv->cursor().setCursor(cur_orig);
584         }
585
586         return false;
587 }
588
589
590 bool selectChange(Cursor & cur, bool forward)
591 {
592         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
593                 return false;
594         Change ch = cur.paragraph().lookupChange(cur.pos());
595
596         CursorSlice tip1 = cur.top();
597         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
598                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
599                 if (!ch2.isSimilarTo(ch))
600                         break;
601         }
602         CursorSlice tip2 = cur.top();
603         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
604                 tip2.backwardPos();
605                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
606                 if (!ch2.isSimilarTo(ch)) {
607                         // take a step forward to correctly set the selection
608                         tip2.forwardPos();
609                         break;
610                 }
611         }
612         if (forward)
613                 swap(tip1, tip2);
614         cur.top() = tip1;
615         cur.bv().mouseSetCursor(cur, false);
616         cur.top() = tip2;
617         cur.bv().mouseSetCursor(cur, true);
618         return true;
619 }
620
621
622 namespace {
623
624
625 bool findChange(BufferView * bv, bool forward)
626 {
627         Cursor cur(*bv);
628         cur.setCursor(forward ? bv->cursor().selectionEnd()
629                       : bv->cursor().selectionBegin());
630         forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
631         return selectChange(cur, forward);
632 }
633
634 } // namespace
635
636 bool findNextChange(BufferView * bv)
637 {
638         return findChange(bv, true);
639 }
640
641
642 bool findPreviousChange(BufferView * bv)
643 {
644         return findChange(bv, false);
645 }
646
647
648
649 namespace {
650
651 typedef vector<pair<string, string> > Escapes;
652
653 string string2regex(string in)
654 {
655         static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
656         string temp = std::regex_replace(in, specialChars,  R"(\$&)" );
657         string temp2("");
658         size_t lastpos = 0;
659         size_t fl_pos = 0;
660         int offset = 1;
661         while (fl_pos < temp.size()) {
662                 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
663                 if (fl_pos == string::npos)
664                         break;
665                 offset = 16;
666                 temp2 += temp.substr(lastpos, fl_pos - lastpos);
667                 temp2 += "\\n";
668                 lastpos = fl_pos;
669         }
670         if (lastpos == 0)
671                 return(temp);
672         if (lastpos < temp.size()) {
673                 temp2 += temp.substr(lastpos, temp.size() - lastpos);
674         }
675         return temp2;
676 }
677
678 string correctRegex(string t, bool withformat)
679 {
680         /* Convert \backslash => \
681          * and \{, \}, \[, \] => {, }, [, ]
682          */
683         string s("");
684         regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
685         size_t lastpos = 0;
686         smatch sub;
687         bool backslashed = false;
688         for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
689                 sub = *it;
690                 string replace;
691                 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
692                         continue;
693                 }
694                 else {
695                         if (sub.str(4) == "backslash") {
696                                 replace = "\\";
697                                 if (withformat) {
698                                         // transforms '\backslash \{' into '\{'
699                                         // and '\{' into '{'
700                                         string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
701                                         if ((next == "\\{") || (next == "\\}")) {
702                                                 replace = "";
703                                                 backslashed = true;
704                                         }
705                                 }
706                         }
707                         else if (sub.str(4) == "mathcircumflex")
708                                 replace = "^";
709                         else if (backslashed) {
710                                 backslashed = false;
711                                 if (withformat && (sub.str(3) == "{"))
712                                         replace = accents["braceleft"];
713                                 else if (withformat && (sub.str(3) == "}"))
714                                         replace = accents["braceright"];
715                                 else {
716                                         // else part should not exist
717                                         LASSERT(1, /**/);
718                                 }
719                         }
720                         else
721                                 replace = sub.str(3);
722                 }
723                 if (lastpos < (size_t) sub.position(2))
724                         s += t.substr(lastpos, sub.position(2) - lastpos);
725                 s += replace;
726                 lastpos = sub.position(2) + sub.length(2);
727         }
728         if (lastpos == 0)
729                 return t;
730         else if (lastpos < t.length())
731                 s += t.substr(lastpos, t.length() - lastpos);
732         return s;
733 }
734
735 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
736 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
737 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
738 string escape_for_regex(string s, bool withformat)
739 {
740         size_t lastpos = 0;
741         string result = "";
742         while (lastpos < s.size()) {
743                 size_t regex_pos = s.find("\\regexp{", lastpos);
744                 if (regex_pos == string::npos) {
745                         regex_pos = s.size();
746                 }
747                 if (regex_pos > lastpos) {
748                         result += string2regex(s.substr(lastpos, regex_pos-lastpos));
749                         lastpos = regex_pos;
750                         if (lastpos == s.size())
751                                 break;
752                 }
753                 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
754                 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
755                 lastpos = end_pos + 13;
756         }
757         return result;
758 }
759
760
761 /// Wrapper for lyx::regex_replace with simpler interface
762 bool regex_replace(string const & s, string & t, string const & searchstr,
763                    string const & replacestr)
764 {
765         regex e(searchstr, regex_constants::ECMAScript);
766         ostringstream oss;
767         ostream_iterator<char, char> it(oss);
768         regex_replace(it, s.begin(), s.end(), e, replacestr);
769         // tolerate t and s be references to the same variable
770         bool rv = (s != oss.str());
771         t = oss.str();
772         return rv;
773 }
774
775 class MatchResult {
776 public:
777         enum range {
778                 newIsTooFar,
779                 newIsBetter,
780                 newIsInvalid
781         };
782         int match_len;
783         int match_prefix;
784         int match2end;
785         int pos;
786         int leadsize;
787         int pos_len;
788         int searched_size;
789         vector <string> result = vector <string>();
790         MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
791 };
792
793 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
794 {
795   if (newres.match2end < oldres.match2end)
796     return MatchResult::newIsTooFar;
797   if (newres.match_len < oldres.match_len)
798     return MatchResult::newIsTooFar;
799
800   if (newres.match_len == oldres.match_len) {
801     if (newres.match2end == oldres.match2end)
802       return MatchResult::newIsBetter;
803   }
804   return MatchResult::newIsInvalid;
805 }
806
807 /** The class performing a match between a position in the document and the FindAdvOptions.
808  **/
809
810 class MatchStringAdv {
811 public:
812         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
813
814         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
815          ** constructor as opt.search, under the opt.* options settings.
816          **
817          ** @param at_begin
818          **     If set, then match is searched only against beginning of text starting at cur.
819          **     If unset, then match is searched anywhere in text starting at cur.
820          **
821          ** @return
822          ** The length of the matching text, or zero if no match was found.
823          **/
824         MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
825 #if QTSEARCH
826         bool regexIsValid;
827         string regexError;
828 #endif
829
830 public:
831         /// buffer
832         lyx::Buffer * p_buf;
833         /// first buffer on which search was started
834         lyx::Buffer * const p_first_buf;
835         /// options
836         FindAndReplaceOptions const & opt;
837
838 private:
839         /// Auxiliary find method (does not account for opt.matchword)
840         MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
841         void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
842
843         /** Normalize a stringified or latexified LyX paragraph.
844          **
845          ** Normalize means:
846          ** <ul>
847          **   <li>if search is not casesensitive, then lowercase the string;
848          **   <li>remove any newline at begin or end of the string;
849          **   <li>replace any newline in the middle of the string with a simple space;
850          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
851          ** </ul>
852          **
853          ** @todo Normalization should also expand macros, if the corresponding
854          ** search option was checked.
855          **/
856         string normalize(docstring const & s) const;
857         // normalized string to search
858         string par_as_string;
859         // regular expression to use for searching
860         // regexp2 is same as regexp, but prefixed with a ".*?"
861 #if QTSEARCH
862         QRegularExpression regexp;
863         QRegularExpression regexp2;
864 #else
865         regex regexp;
866         regex regexp2;
867 #endif
868         // leading format material as string
869         string lead_as_string;
870         // par_as_string after removal of lead_as_string
871         string par_as_string_nolead;
872         // unmatched open braces in the search string/regexp
873         int open_braces;
874         // number of (.*?) subexpressions added at end of search regexp for closing
875         // environments, math mode, styles, etc...
876         int close_wildcards;
877 public:
878         // Are we searching with regular expressions ?
879         bool use_regexp;
880         static int valid_matches;
881         static vector <string> matches;
882         void FillResults(MatchResult &found_mr);
883 };
884
885 int MatchStringAdv::valid_matches = 0;
886 vector <string> MatchStringAdv::matches = vector <string>(10);
887
888 void MatchStringAdv::FillResults(MatchResult &found_mr)
889 {
890   if (found_mr.match_len > 0) {
891     valid_matches = found_mr.result.size();
892     for (size_t i = 0; i < found_mr.result.size(); i++)
893       matches[i] = found_mr.result[i];
894   }
895   else
896     valid_matches = 0;
897 }
898
899 static docstring buffer_to_latex(Buffer & buffer)
900 {
901         //OutputParams runparams(&buffer.params().encoding());
902         OutputParams runparams(encodings.fromLyXName("utf8"));
903         odocstringstream ods;
904         otexstream os(ods);
905         runparams.nice = true;
906         runparams.flavor = Flavor::XeTeX;
907         runparams.linelen = 10000; //lyxrc.plaintext_linelen;
908         // No side effect of file copying and image conversion
909         runparams.dryrun = true;
910         if (ignoreFormats.getDeleted())
911                 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
912         else
913                 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
914         pit_type const endpit = buffer.paragraphs().size();
915         for (pit_type pit = 0; pit != endpit; ++pit) {
916                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
917                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
918         }
919         return ods.str();
920 }
921
922
923 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
924 {
925         docstring str;
926         if (!opt.ignoreformat) {
927                 str = buffer_to_latex(buffer);
928         } else {
929                 // OutputParams runparams(&buffer.params().encoding());
930                 OutputParams runparams(encodings.fromLyXName("utf8"));
931                 runparams.nice = true;
932                 runparams.flavor = Flavor::XeTeX;
933                 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
934                 runparams.dryrun = true;
935                 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
936                 if (ignoreFormats.getDeleted()) {
937                         option |= AS_STR_SKIPDELETE;
938                         runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
939                 }
940                 else {
941                         runparams.for_searchAdv = OutputParams::SearchWithDeleted;
942                 }
943                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
944                         Paragraph const & par = buffer.paragraphs().at(pit);
945                         LYXERR(Debug::FIND, "Adding to search string: '"
946                                << par.asString(pos_type(0), par.size(),
947                                                option,
948                                                &runparams)
949                                << "'");
950                         str += par.asString(pos_type(0), par.size(),
951                                             option,
952                                             &runparams);
953                 }
954                 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
955                 string t = to_utf8(str);
956                 while (regex_replace(t, t, "\\\\(text|lyxmathsym)\\{([^\\}]*)\\}", "$2"));
957                 str = from_utf8(t);
958         }
959         return str;
960 }
961
962
963 /// Return separation pos between the leading material and the rest
964 static size_t identifyLeading(string const & s)
965 {
966         string t = s;
967         // @TODO Support \item[text]
968         // Kornel: Added textsl, textsf, textit, texttt and noun
969         // + allow to search for colored text too
970         while (regex_replace(t, t, "^\\\\(("
971                              "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
972                                "lyxaddress|lyxrightaddress|"
973                                "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
974                                "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
975                              "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
976                              "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
977                || regex_replace(t, t, "^\\$", "")
978                || regex_replace(t, t, "^\\\\\\[", "")
979                || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
980                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
981                ;
982         LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
983         return s.find(t);
984 }
985
986 /*
987  * Given a latexified string, retrieve some handled features
988  * The features of the regex will later be compared with the features
989  * of the searched text. If the regex features are not a
990  * subset of the analized, then, in not format ignoring search
991  * we can early stop the search in the relevant inset.
992  */
993 typedef map<string, bool> Features;
994
995 static Features identifyFeatures(string const & s)
996 {
997         static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
998         static regex const valid("^("
999                 "("
1000                         "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1001                                 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1002                                 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1003                         "(u|uu)line|(s|x)out|uwave|"
1004                         "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1005                 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1006         smatch sub;
1007         bool displ = true;
1008         Features info;
1009
1010         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1011                 sub = *it;
1012                 if (displ) {
1013                         if (sub.str(1).compare("regexp") == 0) {
1014                                 displ = false;
1015                                 continue;
1016                         }
1017                         string token = sub.str(1);
1018                         smatch sub2;
1019                         if (regex_match(token, sub2, valid)) {
1020                                 info[token] = true;
1021                         }
1022                         else {
1023                                 // ignore
1024                         }
1025                 }
1026                 else {
1027                         if (sub.str(1).compare("endregexp") == 0) {
1028                                 displ = true;
1029                                 continue;
1030                         }
1031                 }
1032         }
1033         return info;
1034 }
1035
1036 /*
1037  * defines values features of a key "\\[a-z]+{"
1038  */
1039 class KeyInfo {
1040  public:
1041   enum KeyType {
1042     /* Char type with content discarded
1043      * like \hspace{1cm} */
1044     noContent,
1045     /* Char, like \backslash */
1046     isChar,
1047     /* replace starting backslash with '#' */
1048     isText,
1049     /* \part, \section*, ... */
1050     isSectioning,
1051     /* title, author etc */
1052     isTitle,
1053     /* \foreignlanguage{ngerman}, ... */
1054     isMain,
1055     /* inside \code{}
1056      * to discard language in content */
1057     noMain,
1058     isRegex,
1059     /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1060     isMath,
1061     /* fonts, colors, markups, ... */
1062     isStandard,
1063     /* footnotesize, ... large, ...
1064      * Ignore all of them */
1065     isSize,
1066     invalid,
1067     /* inputencoding, ...
1068      * Discard also content, because they do not help in search */
1069     doRemove,
1070     /* twocolumns, ...
1071      * like remove, but also all arguments */
1072     removeWithArg,
1073     /* item, listitem */
1074     isList,
1075     /* tex, latex, ... like isChar */
1076     isIgnored,
1077     /* like \lettrine[lines=5]{}{} */
1078     cleanToStart,
1079     // like isStandard, but always remove head
1080     headRemove,
1081     /* End of arguments marker for lettrine,
1082      * so that they can be ignored */
1083     endArguments
1084   };
1085  KeyInfo() = default;
1086  KeyInfo(KeyType type, int parcount, bool disable)
1087    : keytype(type),
1088     parenthesiscount(parcount),
1089     disabled(disable) {}
1090   KeyType keytype = invalid;
1091   string head;
1092   int _tokensize = -1;
1093   int _tokenstart = -1;
1094   int _dataStart = -1;
1095   int _dataEnd = -1;
1096   int parenthesiscount = 1;
1097   bool disabled = false;
1098   bool used = false;                    /* by pattern */
1099 };
1100
1101 class Border {
1102  public:
1103  Border(int l=0, int u=0) : low(l), upper(u) {};
1104   int low;
1105   int upper;
1106 };
1107
1108 #define MAXOPENED 30
1109 class Intervall {
1110   bool isPatternString_;
1111 public:
1112   explicit Intervall(bool isPattern, string const & p) :
1113         isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1114         hasTitle(false), langcount(0)
1115   {
1116     depts[0] = 0;
1117     closes[0] = 0;
1118   }
1119
1120   string par;
1121   int ignoreidx;
1122   static vector<Border> borders;
1123   int depts[MAXOPENED];
1124   int closes[MAXOPENED];
1125   int actualdeptindex;
1126   int previousNotIgnored(int) const;
1127   int nextNotIgnored(int) const;
1128   void handleOpenP(int i);
1129   void handleCloseP(int i, bool closingAllowed);
1130   void resetOpenedP(int openPos);
1131   void addIntervall(int upper);
1132   void addIntervall(int low, int upper); /* if explicit */
1133   void removeAccents();
1134   void setForDefaultLang(KeyInfo const & defLang) const;
1135   int findclosing(int start, int end, char up, char down, int repeat);
1136   void handleParentheses(int lastpos, bool closingAllowed);
1137   bool hasTitle;
1138   int langcount;        // Number of disabled language specs up to current position in actual interval
1139   int isOpeningPar(int pos) const;
1140   string titleValue;
1141   void output(ostringstream &os, int lastpos);
1142   // string show(int lastpos);
1143 };
1144
1145 vector<Border> Intervall::borders = vector<Border>(30);
1146
1147 int Intervall::isOpeningPar(int pos) const
1148 {
1149   if ((pos < 0) || (size_t(pos) >= par.size()))
1150     return 0;
1151   if (par[pos] != '{')
1152     return 0;
1153   if (size_t(pos) + 2 >= par.size())
1154     return 1;
1155   if (par[pos+2] != '}')
1156     return 1;
1157   if (par[pos+1] == '[' || par[pos+1] == ']')
1158     return 3;
1159   return 1;
1160 }
1161
1162 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1163 {
1164   // Enable the use of first token again
1165   if (ignoreidx >= 0) {
1166     int value = defLang._tokenstart + defLang._tokensize;
1167     int borderidx = 0;
1168     if (hasTitle) {
1169       borderidx = 1;
1170     }
1171     if (value > 0) {
1172       if (borders[borderidx].low < value)
1173         borders[borderidx].low = value;
1174       if (borders[borderidx].upper < value)
1175         borders[borderidx].upper = value;
1176     }
1177   }
1178 }
1179
1180 static void checkDepthIndex(int val)
1181 {
1182   static int maxdepthidx = MAXOPENED-2;
1183   static int lastmaxdepth = 0;
1184   if (val > lastmaxdepth) {
1185     LYXERR(Debug::INFO, "Depth reached " << val);
1186     lastmaxdepth = val;
1187   }
1188   if (val > maxdepthidx) {
1189     maxdepthidx = val;
1190     LYXERR(Debug::INFO, "maxdepthidx now " << val);
1191   }
1192 }
1193
1194 #if 0
1195 // Not needed, because borders are now dynamically expanded
1196 static void checkIgnoreIdx(int val)
1197 {
1198   static int lastmaxignore = -1;
1199   if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1200     LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1201     lastmaxignore = val;
1202   }
1203 }
1204 #endif
1205
1206 /*
1207  * Expand the region of ignored parts of the input latex string
1208  * The region is only relevant in output()
1209  */
1210 void Intervall::addIntervall(int low, int upper)
1211 {
1212   int idx;
1213   if (low == upper) return;
1214   for (idx = ignoreidx+1; idx > 0; --idx) {
1215     if (low > borders[idx-1].upper) {
1216       break;
1217     }
1218   }
1219   Border br(low, upper);
1220   if (idx > ignoreidx) {
1221     if (borders.size() <= size_t(idx)) {
1222       borders.push_back(br);
1223     }
1224     else {
1225       borders[idx] = br;
1226     }
1227     ignoreidx = idx;
1228     // checkIgnoreIdx(ignoreidx);
1229     return;
1230   }
1231   else {
1232     // Expand only if one of the new bound is inside the interwall
1233     // We know here that br.low > borders[idx-1].upper
1234     if (br.upper < borders[idx].low) {
1235       // We have to insert at this pos
1236       if (size_t(ignoreidx+1) >= borders.size()) {
1237         borders.push_back(borders[ignoreidx]);
1238       }
1239       else {
1240         borders[ignoreidx+1] = borders[ignoreidx];
1241       }
1242       for (int i = ignoreidx; i > idx; --i) {
1243         borders[i] = borders[i-1];
1244       }
1245       borders[idx] = br;
1246       ignoreidx += 1;
1247       // checkIgnoreIdx(ignoreidx);
1248       return;
1249     }
1250     // Here we know, that we are overlapping
1251     if (br.low > borders[idx].low)
1252       br.low = borders[idx].low;
1253     // check what has to be concatenated
1254     int count = 0;
1255     for (int i = idx; i <= ignoreidx; i++) {
1256       if (br.upper >= borders[i].low) {
1257         count++;
1258         if (br.upper < borders[i].upper)
1259           br.upper = borders[i].upper;
1260       }
1261       else {
1262         break;
1263       }
1264     }
1265     // count should be >= 1 here
1266     borders[idx] = br;
1267     if (count > 1) {
1268       for (int i = idx + count; i <= ignoreidx; i++) {
1269         borders[i-count+1] = borders[i];
1270       }
1271       ignoreidx -= count - 1;
1272       return;
1273     }
1274   }
1275 }
1276
1277 static void buildaccent(string n, string param, string values)
1278 {
1279   stringstream s(n);
1280   string name;
1281   const char delim = '|';
1282   while (getline(s, name, delim)) {
1283     size_t start = 0;
1284     for (char c : param) {
1285       string key = name + "{" + c + "}";
1286       // get the corresponding utf8-value
1287       if ((values[start] & 0xc0) != 0xc0) {
1288         // should not happen, utf8 encoding starts at least with 11xxxxxx
1289         // but value for '\dot{i}' is 'i', which is ascii
1290         if ((values[start] & 0x80) == 0) {
1291           // is ascii
1292           accents[key] = values.substr(start, 1);
1293           // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1294         }
1295         start++;
1296         continue;
1297       }
1298       for (int j = 1; ;j++) {
1299         if (start + j >= values.size()) {
1300           accents[key] = values.substr(start, j);
1301           start = values.size() - 1;
1302           break;
1303         }
1304         else if ((values[start+j] & 0xc0) != 0x80) {
1305           // This is the first byte of following utf8 char
1306           accents[key] = values.substr(start, j);
1307           start += j;
1308           // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1309           break;
1310         }
1311       }
1312     }
1313   }
1314 }
1315
1316 // Helper function
1317 static string getutf8(unsigned uchar)
1318 {
1319         #define maxc 5
1320         string ret = string();
1321         char c[maxc] = {0};
1322         if (uchar <= 0x7f) {
1323                 c[maxc-1] = uchar & 0x7f;
1324         }
1325         else {
1326                 unsigned char rest = 0x40;
1327                 unsigned char first = 0x80;
1328                 int start = maxc-1;
1329                 for (int i = start; i >=0; --i) {
1330                         if (uchar < rest) {
1331                                 c[i] = first + uchar;
1332                                 break;
1333                         }
1334                         c[i] = 0x80 | (uchar &  0x3f);
1335                         uchar >>= 6;
1336                         rest >>= 1;
1337                         first >>= 1;
1338                         first |= 0x80;
1339                 }
1340         }
1341         for (int i = 0; i < maxc; i++) {
1342                 if (c[i] == 0) continue;
1343                 ret += c[i];
1344         }
1345         return(ret);
1346 }
1347
1348 static void buildAccentsMap()
1349 {
1350   accents["imath"] = "ı";
1351   accents["i"] = "ı";
1352   accents["jmath"] = "ȷ";
1353   accents["cdot"] = "·";
1354   accents["textasciicircum"] = "^";
1355   accents["mathcircumflex"] = "^";
1356   accents["sim"] = "~";
1357   accents["guillemotright"] = "»";
1358   accents["guillemotleft"] = "«";
1359   accents["hairspace"]     = getutf8(0xf0000);  // select from free unicode plane 15
1360   accents["thinspace"]     = getutf8(0xf0002);  // and used _only_ by findadv
1361   accents["negthinspace"]  = getutf8(0xf0003);  // to omit backslashed latex macros
1362   accents["medspace"]      = getutf8(0xf0004);  // See https://en.wikipedia.org/wiki/Private_Use_Areas
1363   accents["negmedspace"]   = getutf8(0xf0005);
1364   accents["thickspace"]    = getutf8(0xf0006);
1365   accents["negthickspace"] = getutf8(0xf0007);
1366   accents["lyx"]           = getutf8(0xf0010);  // Used logos
1367   accents["LyX"]           = getutf8(0xf0010);
1368   accents["tex"]           = getutf8(0xf0011);
1369   accents["TeX"]           = getutf8(0xf0011);
1370   accents["latex"]         = getutf8(0xf0012);
1371   accents["LaTeX"]         = getutf8(0xf0012);
1372   accents["latexe"]        = getutf8(0xf0013);
1373   accents["LaTeXe"]        = getutf8(0xf0013);
1374   accents["lyxarrow"]      = getutf8(0xf0020);
1375   accents["braceleft"]     = getutf8(0xf0030);
1376   accents["braceright"]    = getutf8(0xf0031);
1377   accents["backslash lyx"]           = getutf8(0xf0010);        // Used logos inserted with starting \backslash
1378   accents["backslash LyX"]           = getutf8(0xf0010);
1379   accents["backslash tex"]           = getutf8(0xf0011);
1380   accents["backslash TeX"]           = getutf8(0xf0011);
1381   accents["backslash latex"]         = getutf8(0xf0012);
1382   accents["backslash LaTeX"]         = getutf8(0xf0012);
1383   accents["backslash latexe"]        = getutf8(0xf0013);
1384   accents["backslash LaTeXe"]        = getutf8(0xf0013);
1385   accents["backslash lyxarrow"]      = getutf8(0xf0020);
1386   accents["ddot{\\imath}"] = "ï";
1387   buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1388                       "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ");       // umlaut
1389   buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1390                        "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ");   // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1391   accents["acute{\\imath}"] = "í";
1392   buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1393                        "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1394   buildaccent("dacute|H|h", "oOuU", "őŐűŰ");        // double acute
1395   buildaccent("mathring|r", "aAuUwy",
1396                             "åÅůŮẘẙ");  // ring
1397   accents["check{\\imath}"] = "ǐ";
1398   accents["check{\\jmath}"] = "ǰ";
1399   buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1400                          "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ");   // caron
1401   accents["hat{\\imath}"] = "î";
1402   accents["hat{\\jmath}"] = "ĵ";
1403   buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1404                        "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ");       // circ
1405   accents["bar{\\imath}"] = "ī";
1406   buildaccent("bar|=", "aAeEiIoOuUyY",
1407                        "āĀēĒīĪōŌūŪȳȲ");     // macron
1408   accents["tilde{\\imath}"] = "ĩ";
1409   buildaccent("tilde", "aAeEiInNoOuUvVyY",
1410                        "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ");       // tilde
1411   accents["breve{\\imath}"] = "ĭ";
1412   buildaccent("breve|u", "aAeEgGiIoOuU",
1413                          "ăĂĕĔğĞĭĬŏŎŭŬ");   // breve
1414   accents["grave{\\imath}"] = "ì";
1415   buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1416                          "àÀèÈìÌòÒùÙǹǸẁẀỳỲ");       // grave
1417   buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1418                           "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ");        // dot below
1419   buildaccent("ogonek|k", "AaEeIiUuOo",
1420                           "ĄąĘęĮįŲųǪǫ");      // ogonek
1421   buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1422                            "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1423   buildaccent("subring|textsubring", "Aa",
1424                                      "Ḁḁ"); // subring
1425   buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1426                                       "ḒḓḘḙḼḽṊṋṰṱṶṷ");  // subcircum
1427   buildaccent("subtilde|textsubtilde", "EeIiUu",
1428                                        "ḚḛḬḭṴṵ");   // subtilde
1429   accents["dgrave{\\imath}"] = "ȉ";
1430   accents["textdoublegrave{\\i}"] = "ȉ";
1431   buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1432                                         "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1433   accents["rcap{\\imath}"] = "ȉ";
1434   accents["textroundcap{\\i}"] = "ȉ";
1435   buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1436                                    "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1437   buildaccent("slashed", "oO",
1438                          "øØ"); // slashed
1439 }
1440
1441 /*
1442  * Created accents in math or regexp environment
1443  * are macros, but we need the utf8 equivalent
1444  */
1445 void Intervall::removeAccents()
1446 {
1447   if (accents.empty())
1448     buildAccentsMap();
1449   static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1450          "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1451       "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))|(brace|guillemot)(left|right)|textasciicircum|mathcircumflex|sim)(?![a-zA-Z]))");
1452   smatch sub;
1453   for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1454     sub = *itacc;
1455     string key = sub.str(1);
1456     AccentsIterator it_ac = accents.find(key);
1457     if (it_ac != accents.end()) {
1458       string val = it_ac->second;
1459       size_t pos = sub.position(size_t(0));
1460       for (size_t i = 0; i < val.size(); i++) {
1461         par[pos+i] = val[i];
1462       }
1463       // Remove possibly following space too
1464       if (par[pos+sub.str(0).size()] == ' ')
1465         addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1466       else
1467         addIntervall(pos+val.size(), pos + sub.str(0).size());
1468       for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1469         // remove traces of any remaining chars
1470         par[i] = ' ';
1471       }
1472     }
1473     else {
1474       LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1475     }
1476   }
1477 }
1478
1479 void Intervall::handleOpenP(int i)
1480 {
1481   actualdeptindex++;
1482   depts[actualdeptindex] = i+1;
1483   closes[actualdeptindex] = -1;
1484   checkDepthIndex(actualdeptindex);
1485 }
1486
1487 void Intervall::handleCloseP(int i, bool closingAllowed)
1488 {
1489   if (actualdeptindex <= 0) {
1490     if (! closingAllowed)
1491       LYXERR(Debug::FIND, "Bad closing parenthesis in latex");  /* should not happen, but the latex input may be wrong */
1492     // if we are at the very end
1493     addIntervall(i, i+1);
1494   }
1495   else {
1496     closes[actualdeptindex] = i+1;
1497     actualdeptindex--;
1498   }
1499 }
1500
1501 void Intervall::resetOpenedP(int openPos)
1502 {
1503   // Used as initializer for foreignlanguage entry
1504   actualdeptindex = 1;
1505   depts[1] = openPos+1;
1506   closes[1] = -1;
1507 }
1508
1509 int Intervall::previousNotIgnored(int start) const
1510 {
1511     int idx = 0;                          /* int intervalls */
1512     for (idx = ignoreidx; idx >= 0; --idx) {
1513       if (start > borders[idx].upper)
1514         return start;
1515       if (start >= borders[idx].low)
1516         start = borders[idx].low-1;
1517     }
1518     return start;
1519 }
1520
1521 int Intervall::nextNotIgnored(int start) const
1522 {
1523     int idx = 0;                          /* int intervalls */
1524     for (idx = 0; idx <= ignoreidx; idx++) {
1525       if (start < borders[idx].low)
1526         return start;
1527       if (start < borders[idx].upper)
1528         start = borders[idx].upper;
1529     }
1530     return start;
1531 }
1532
1533 typedef unordered_map<string, KeyInfo> KeysMap;
1534 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1535 typedef vector< KeyInfo> Entries;
1536 static KeysMap keys = unordered_map<string, KeyInfo>();
1537
1538 class LatexInfo {
1539  private:
1540   int entidx_;
1541   Entries entries_;
1542   Intervall interval_;
1543   void buildKeys(bool);
1544   void buildEntries(bool);
1545   void makeKey(const string &, KeyInfo, bool isPatternString);
1546   void processRegion(int start, int region_end); /*  remove {} parts */
1547   void removeHead(KeyInfo const &, int count=0);
1548
1549  public:
1550  LatexInfo(string const & par, bool isPatternString)
1551          : entidx_(-1), interval_(isPatternString, par)
1552   {
1553     buildKeys(isPatternString);
1554     entries_ = vector<KeyInfo>();
1555     buildEntries(isPatternString);
1556   };
1557   int getFirstKey() {
1558     entidx_ = 0;
1559     if (entries_.empty()) {
1560       return -1;
1561     }
1562     if (entries_[0].keytype == KeyInfo::isTitle) {
1563       interval_.hasTitle = true;
1564       if (! entries_[0].disabled) {
1565         interval_.titleValue = entries_[0].head;
1566       }
1567       else {
1568         interval_.titleValue = "";
1569       }
1570       removeHead(entries_[0]);
1571       if (entries_.size() > 1)
1572         return 1;
1573       else
1574         return -1;
1575     }
1576     return 0;
1577   };
1578   int getNextKey() {
1579     entidx_++;
1580     if (int(entries_.size()) > entidx_) {
1581       return entidx_;
1582     }
1583     else {
1584       return -1;
1585     }
1586   };
1587   bool setNextKey(int idx) {
1588     if ((idx == entidx_) && (entidx_ >= 0)) {
1589       entidx_--;
1590       return true;
1591     }
1592     else
1593       return false;
1594   };
1595   int find(int start, KeyInfo::KeyType keytype) const {
1596     if (start < 0)
1597       return -1;
1598     int tmpIdx = start;
1599     while (tmpIdx < int(entries_.size())) {
1600       if (entries_[tmpIdx].keytype == keytype)
1601         return tmpIdx;
1602       tmpIdx++;
1603     }
1604     return -1;
1605   };
1606   int process(ostringstream & os, KeyInfo const & actual);
1607   int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1608   // string show(int lastpos) { return interval.show(lastpos);};
1609   int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1610   KeyInfo &getKeyInfo(int keyinfo) {
1611     static KeyInfo invalidInfo = KeyInfo();
1612     if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1613       return invalidInfo;
1614     else
1615       return entries_[keyinfo];
1616   };
1617   void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1618   void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1619 };
1620
1621
1622 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1623 {
1624   int skip = 0;
1625   int depth = 0;
1626   for (int i = start; i < end; i += 1 + skip) {
1627     char c;
1628     c = par[i];
1629     skip = 0;
1630     if (c == '\\') skip = 1;
1631     else if (c == up) {
1632       depth++;
1633     }
1634     else if (c == down) {
1635       if (depth == 0) {
1636         repeat--;
1637         if ((repeat <= 0) || (par[i+1] != up))
1638           return i;
1639       }
1640       --depth;
1641     }
1642   }
1643   return end;
1644 }
1645
1646 class MathInfo {
1647   class MathEntry {
1648   public:
1649     string wait;
1650     size_t mathEnd;
1651     size_t mathStart;
1652     size_t mathSize;
1653   };
1654   size_t actualIdx_;
1655   vector<MathEntry> entries_;
1656  public:
1657   MathInfo() {
1658     actualIdx_ = 0;
1659   }
1660   void insert(string const & wait, size_t start, size_t end) {
1661     MathEntry m = MathEntry();
1662     m.wait = wait;
1663     m.mathStart = start;
1664     m.mathEnd = end;
1665     m.mathSize = end - start;
1666     entries_.push_back(m);
1667   }
1668   bool empty() const { return entries_.empty(); };
1669   size_t getEndPos() const {
1670     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1671       return 0;
1672     }
1673     return entries_[actualIdx_].mathEnd;
1674   }
1675   size_t getStartPos() const {
1676     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1677       return 100000;                    /*  definitely enough? */
1678     }
1679     return entries_[actualIdx_].mathStart;
1680   }
1681   size_t getFirstPos() {
1682     actualIdx_ = 0;
1683     return getStartPos();
1684   }
1685   size_t getSize() const {
1686     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1687       return size_t(0);
1688     }
1689     return entries_[actualIdx_].mathSize;
1690   }
1691   void incrEntry() { actualIdx_++; };
1692 };
1693
1694 void LatexInfo::buildEntries(bool isPatternString)
1695 {
1696   static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1697   static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1698   static bool disableLanguageOverride = false;
1699   smatch sub, submath;
1700   bool evaluatingRegexp = false;
1701   MathInfo mi;
1702   bool evaluatingMath = false;
1703   bool evaluatingCode = false;
1704   size_t codeEnd = 0;
1705   bool evaluatingOptional = false;
1706   size_t optionalEnd = 0;
1707   int codeStart = -1;
1708   KeyInfo found;
1709   bool math_end_waiting = false;
1710   size_t math_pos = 10000;
1711   string math_end;
1712   static vector<string> usedText = vector<string>();
1713
1714   interval_.removeAccents();
1715
1716   for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1717     submath = *itmath;
1718     if ((submath.position(2) - submath.position(0)) %2 == 1) {
1719       // prefixed by odd count of '\\'
1720       continue;
1721     }
1722     if (math_end_waiting) {
1723       size_t pos = submath.position(size_t(2));
1724       if ((math_end == "$") &&
1725           (submath.str(2) == "$")) {
1726         mi.insert("$", math_pos, pos + 1);
1727         math_end_waiting = false;
1728       }
1729       else if ((math_end == "\\]") &&
1730                (submath.str(2) == "\\]")) {
1731         mi.insert("\\]", math_pos, pos + 2);
1732         math_end_waiting = false;
1733       }
1734       else if ((submath.str(3).compare("end") == 0) &&
1735           (submath.str(4).compare(math_end) == 0)) {
1736         mi.insert(math_end, math_pos, pos + submath.str(2).length());
1737         math_end_waiting = false;
1738       }
1739       else
1740         continue;
1741     }
1742     else {
1743       if (submath.str(3).compare("begin") == 0) {
1744         math_end_waiting = true;
1745         math_end = submath.str(4);
1746         math_pos = submath.position(size_t(2));
1747       }
1748       else if (submath.str(2).compare("\\[") == 0) {
1749         math_end_waiting = true;
1750         math_end = "\\]";
1751         math_pos = submath.position(size_t(2));
1752       }
1753       else if (submath.str(2) == "$") {
1754         size_t pos = submath.position(size_t(2));
1755         math_end_waiting = true;
1756         math_end = "$";
1757         math_pos = pos;
1758       }
1759     }
1760   }
1761   // Ignore language if there is math somewhere in pattern-string
1762   if (isPatternString) {
1763     for (auto s: usedText) {
1764       // Remove entries created in previous search runs
1765       keys.erase(s);
1766     }
1767     usedText = vector<string>();
1768     if (! mi.empty()) {
1769       // Disable language
1770       keys["foreignlanguage"].disabled = true;
1771       disableLanguageOverride = true;
1772     }
1773     else
1774       disableLanguageOverride = false;
1775   }
1776   else {
1777     if (disableLanguageOverride) {
1778       keys["foreignlanguage"].disabled = true;
1779     }
1780   }
1781   math_pos = mi.getFirstPos();
1782   for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1783     sub = *it;
1784     if ((sub.position(2) - sub.position(0)) %2 == 1) {
1785       // prefixed by odd count of '\\'
1786       continue;
1787     }
1788     string key = sub.str(5);
1789     if (key == "") {
1790       if (sub.str(2)[0] == '\\')
1791         key = sub.str(2)[1];
1792       else {
1793         key = sub.str(2);
1794       }
1795     }
1796     KeysIterator it_key = keys.find(key);
1797     if (it_key != keys.end()) {
1798       if (it_key->second.keytype == KeyInfo::headRemove) {
1799         KeyInfo found1 = it_key->second;
1800         found1.disabled = true;
1801         found1.head = "\\" + key + "{";
1802         found1._tokenstart = sub.position(size_t(2));
1803         found1._tokensize = found1.head.length();
1804         found1._dataStart = found1._tokenstart + found1.head.length();
1805         int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1806         found1._dataEnd = endpos;
1807         removeHead(found1);
1808         continue;
1809       }
1810     }
1811     if (evaluatingRegexp) {
1812       if (sub.str(3).compare("endregexp") == 0) {
1813         evaluatingRegexp = false;
1814         // found._tokenstart already set
1815         found._dataEnd = sub.position(size_t(2)) + 13;
1816         found._dataStart = found._dataEnd;
1817         found._tokensize = found._dataEnd - found._tokenstart;
1818         found.parenthesiscount = 0;
1819         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1820       }
1821       else {
1822         continue;
1823       }
1824     }
1825     else {
1826       if (evaluatingMath) {
1827         if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1828           continue;
1829         evaluatingMath = false;
1830         mi.incrEntry();
1831         math_pos = mi.getStartPos();
1832       }
1833       if (it_key == keys.end()) {
1834         found = KeyInfo(KeyInfo::isStandard, 0, true);
1835         LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1836         found = KeyInfo(KeyInfo::isText, 0, false);
1837         if (isPatternString) {
1838           found.keytype = KeyInfo::isChar;
1839           found.disabled = false;
1840           found.used = true;
1841         }
1842         keys[key] = found;
1843         usedText.push_back(key);
1844       }
1845       else
1846         found = keys[key];
1847       if (key.compare("regexp") == 0) {
1848         evaluatingRegexp = true;
1849         found._tokenstart = sub.position(size_t(2));
1850         found._tokensize = 0;
1851         continue;
1852       }
1853     }
1854     // Handle the other params of key
1855     if (found.keytype == KeyInfo::isIgnored)
1856       continue;
1857     else if (found.keytype == KeyInfo::isMath) {
1858       if (size_t(sub.position(size_t(2))) == math_pos) {
1859         found = keys[key];
1860         found._tokenstart = sub.position(size_t(2));
1861         found._tokensize = mi.getSize();
1862         found._dataEnd = found._tokenstart + found._tokensize;
1863         found._dataStart = found._dataEnd;
1864         found.parenthesiscount = 0;
1865         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1866         evaluatingMath = true;
1867       }
1868       else {
1869         // begin|end of unknown env, discard
1870         // First handle tables
1871         // longtable|tabular
1872         bool discardComment;
1873         found = keys[key];
1874         found.keytype = KeyInfo::doRemove;
1875         if ((sub.str(7).compare("longtable") == 0) ||
1876             (sub.str(7).compare("tabular") == 0)) {
1877           discardComment = true;        /* '%' */
1878         }
1879         else {
1880           discardComment = false;
1881           static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1882           smatch sub2;
1883           string token = sub.str(7);
1884           if (regex_match(token, sub2, removeArgs)) {
1885             found.keytype = KeyInfo::removeWithArg;
1886           }
1887         }
1888         // discard spaces before pos(2)
1889         int pos = sub.position(size_t(2));
1890         int count;
1891         for (count = 0; pos - count > 0; count++) {
1892           char c = interval_.par[pos-count-1];
1893           if (discardComment) {
1894             if ((c != ' ') && (c != '%'))
1895               break;
1896           }
1897           else if (c != ' ')
1898             break;
1899         }
1900         found._tokenstart = pos - count;
1901         if (sub.str(3).compare(0, 5, "begin") == 0) {
1902           size_t pos1 = pos + sub.str(2).length();
1903           if (sub.str(7).compare("cjk") == 0) {
1904             pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1905             if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1906               pos1 += 2;
1907             found.keytype = KeyInfo::isMain;
1908             found._dataStart = pos1;
1909             found._dataEnd = interval_.par.length();
1910             found.disabled = keys["foreignlanguage"].disabled;
1911             found.used = keys["foreignlanguage"].used;
1912             found._tokensize = pos1 - found._tokenstart;
1913             found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1914           }
1915           else {
1916             // Swallow possible optional params
1917             while (interval_.par[pos1] == '[') {
1918               pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1919             }
1920             // Swallow also the eventual parameter
1921             if (interval_.par[pos1] == '{') {
1922               found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1923             }
1924             else {
1925               found._dataEnd = pos1;
1926             }
1927             found._dataStart = found._dataEnd;
1928             found._tokensize = count + found._dataEnd - pos;
1929             found.parenthesiscount = 0;
1930             found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1931             found.disabled = true;
1932           }
1933         }
1934         else {
1935           // Handle "\end{...}"
1936           found._dataStart = pos + sub.str(2).length();
1937           found._dataEnd = found._dataStart;
1938           found._tokensize = count + found._dataEnd - pos;
1939           found.parenthesiscount = 0;
1940           found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1941           found.disabled = true;
1942         }
1943       }
1944     }
1945     else if (found.keytype != KeyInfo::isRegex) {
1946       found._tokenstart = sub.position(size_t(2));
1947       if (found.parenthesiscount == 0) {
1948         // Probably to be discarded
1949         size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
1950         char following = interval_.par[following_pos];
1951         if (following == ' ')
1952           found.head = "\\" + sub.str(5) + " ";
1953         else if (following == '=') {
1954           // like \uldepth=1000pt
1955           found.head = sub.str(2);
1956         }
1957         else
1958           found.head = "\\" + key;
1959         found._tokensize = found.head.length();
1960         found._dataEnd = found._tokenstart + found._tokensize;
1961         found._dataStart = found._dataEnd;
1962       }
1963       else {
1964         int params = found._tokenstart + key.length() + 1;
1965         if (evaluatingOptional) {
1966           if (size_t(found._tokenstart) > optionalEnd) {
1967             evaluatingOptional = false;
1968           }
1969           else {
1970             found.disabled = true;
1971           }
1972         }
1973         int optend = params;
1974         while (interval_.par[optend] == '[') {
1975           // discard optional parameters
1976           optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
1977         }
1978         if (optend > params) {
1979           key += interval_.par.substr(params, optend-params);
1980           evaluatingOptional = true;
1981           optionalEnd = optend;
1982           if (found.keytype == KeyInfo::isSectioning) {
1983             // Remove optional values (but still keep in header)
1984             interval_.addIntervall(params, optend);
1985           }
1986         }
1987         string token = sub.str(7);
1988         int closings;
1989         if (interval_.par[optend] != '{') {
1990           closings = 0;
1991           found.parenthesiscount = 0;
1992           found.head = "\\" + key;
1993         }
1994         else
1995           closings = found.parenthesiscount;
1996         if (found.parenthesiscount == 1) {
1997           found.head = "\\" + key + "{";
1998         }
1999         else if (found.parenthesiscount > 1) {
2000           if (token != "") {
2001             found.head = sub.str(2) + "{";
2002             closings = found.parenthesiscount - 1;
2003           }
2004           else {
2005             found.head = "\\" + key + "{";
2006           }
2007         }
2008         found._tokensize = found.head.length();
2009         found._dataStart = found._tokenstart + found.head.length();
2010         if (found.keytype == KeyInfo::doRemove) {
2011           if (closings > 0) {
2012             size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2013             if (endpar >= interval_.par.length())
2014               found._dataStart = interval_.par.length();
2015             else
2016               found._dataStart = endpar;
2017             found._tokensize = found._dataStart - found._tokenstart;
2018           }
2019           else {
2020             found._dataStart = found._tokenstart + found._tokensize;
2021           }
2022           closings = 0;
2023         }
2024         if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2025           found._dataStart += 15;
2026         }
2027         size_t endpos;
2028         if (closings < 1)
2029           endpos = found._dataStart - 1;
2030         else
2031           endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2032         if (found.keytype == KeyInfo::isList) {
2033           // Check if it really is list env
2034           static regex const listre("^([a-z]+)$");
2035           smatch sub2;
2036           if (!regex_match(token, sub2, listre)) {
2037             // Change the key of this entry. It is not in a list/item environment
2038             found.keytype = KeyInfo::endArguments;
2039           }
2040         }
2041         if (found.keytype == KeyInfo::noMain) {
2042           evaluatingCode = true;
2043           codeEnd = endpos;
2044           codeStart = found._dataStart;
2045         }
2046         else if (evaluatingCode) {
2047           if (size_t(found._dataStart) > codeEnd)
2048             evaluatingCode = false;
2049           else if (found.keytype == KeyInfo::isMain) {
2050             // Disable this key, treate it as standard
2051             found.keytype = KeyInfo::isStandard;
2052             found.disabled = true;
2053             if ((codeEnd +1 >= interval_.par.length()) &&
2054                 (found._tokenstart == codeStart)) {
2055               // trickery, because the code inset starts
2056               // with \selectlanguage ...
2057               codeEnd = endpos;
2058               if (entries_.size() > 1) {
2059                 entries_[entries_.size()-1]._dataEnd = codeEnd;
2060               }
2061             }
2062           }
2063         }
2064         if ((endpos == interval_.par.length()) &&
2065             (found.keytype == KeyInfo::doRemove)) {
2066           // Missing closing => error in latex-input?
2067           // therefore do not delete remaining data
2068           found._dataStart -= 1;
2069           found._dataEnd = found._dataStart;
2070         }
2071         else
2072           found._dataEnd = endpos;
2073       }
2074       if (isPatternString) {
2075         keys[key].used = true;
2076       }
2077     }
2078     entries_.push_back(found);
2079   }
2080 }
2081
2082 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2083 {
2084   stringstream s(keysstring);
2085   string key;
2086   const char delim = '|';
2087   while (getline(s, key, delim)) {
2088     KeyInfo keyII(keyI);
2089     if (isPatternString) {
2090       keyII.used = false;
2091     }
2092     else if ( !keys[key].used)
2093       keyII.disabled = true;
2094     keys[key] = keyII;
2095   }
2096 }
2097
2098 void LatexInfo::buildKeys(bool isPatternString)
2099 {
2100
2101   static bool keysBuilt = false;
2102   if (keysBuilt && !isPatternString) return;
2103
2104   // Keys to ignore in any case
2105   makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2106   // Known standard keys with 1 parameter.
2107   // Split is done, if not at start of region
2108   makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2109   makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2110   makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2111   makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2112   makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2113   makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2114
2115   makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2116           KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2117   makeKey("section*|subsection*|subsubsection*|paragraph*",
2118           KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2119   makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2120   makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2121   // Regex
2122   makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2123
2124   // Split is done, if not at start of region
2125   makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2126   makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2127
2128   // Split is done always.
2129   makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2130
2131   // Known charaters
2132   // No split
2133   makeKey("backslash|textbackslash|slash",  KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2134   makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2135   makeKey("textasciiacute|texemdash",       KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2136   makeKey("dots|ldots",                     KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2137   // Spaces
2138   makeKey("quad|qquad|hfill|dotfill",               KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2139   makeKey("textvisiblespace|nobreakspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2140   makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2141   makeKey("thickspace|medspace|thinspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2142   // Skip
2143   // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2144   // Custom space/skip, remove the content (== length value)
2145   makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2146   // Found in fr/UserGuide.lyx
2147   makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2148   // quotes
2149   makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2150   makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2151   // Known macros to remove (including their parameter)
2152   // No split
2153   makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2154   makeKey("addtocounter|setlength",                 KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2155   // handle like standard keys with 1 parameter.
2156   makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2157
2158   // Ignore deleted text
2159   makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2160   // but preserve added text
2161   makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2162
2163   // Macros to remove, but let the parameter survive
2164   // No split
2165   makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2166
2167   // Remove language spec from content of these insets
2168   makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2169
2170   // Same effect as previous, parameter will survive (because there is no one anyway)
2171   // No split
2172   makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2173   // Remove table decorations
2174   makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2175   // Discard shape-header.
2176   // For footnote or shortcut too, because of lang settings
2177   // and wrong handling if used 'KeyInfo::noMain'
2178   makeKey("circlepar|diamondpar|heartpar|nutpar",  KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2179   makeKey("trianglerightpar|hexagonpar|starpar",   KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2180   makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2181   makeKey("triangleleftpar|shapepar|dropuppar",    KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2182   makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics",     KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2183   makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2184   // like ('tiny{}' or '\tiny ' ... )
2185   makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2186
2187   // Survives, like known character
2188   // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2189   makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2190   makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2191
2192   makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2193   makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2194   makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2195
2196   makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2197   // Remove RTL/LTR marker
2198   makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2199   makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2200   makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2201   makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2202   makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2203   makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2204   makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2205   if (isPatternString) {
2206     // Allow the first searched string to rebuild the keys too
2207     keysBuilt = false;
2208   }
2209   else {
2210     // no need to rebuild again
2211     keysBuilt = true;
2212   }
2213 }
2214
2215 /*
2216  * Keep the list of actual opened parentheses actual
2217  * (e.g. depth == 4 means there are 4 '{' not processed yet)
2218  */
2219 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2220 {
2221   int skip = 0;
2222   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2223     char c;
2224     c = par[i];
2225     skip = 0;
2226     if (c == '\\') skip = 1;
2227     else if (c == '{') {
2228       handleOpenP(i);
2229     }
2230     else if (c == '}') {
2231       handleCloseP(i, closingAllowed);
2232     }
2233   }
2234 }
2235
2236 #if (0)
2237 string Intervall::show(int lastpos)
2238 {
2239   int idx = 0;                          /* int intervalls */
2240   string s;
2241   int i = 0;
2242   for (idx = 0; idx <= ignoreidx; idx++) {
2243     while (i < lastpos) {
2244       int printsize;
2245       if (i <= borders[idx].low) {
2246         if (borders[idx].low > lastpos)
2247           printsize = lastpos - i;
2248         else
2249           printsize = borders[idx].low - i;
2250         s += par.substr(i, printsize);
2251         i += printsize;
2252         if (i >= borders[idx].low)
2253           i = borders[idx].upper;
2254       }
2255       else {
2256         i = borders[idx].upper;
2257         break;
2258       }
2259     }
2260   }
2261   if (lastpos > i) {
2262     s += par.substr(i, lastpos-i);
2263   }
2264   return s;
2265 }
2266 #endif
2267
2268 void Intervall::output(ostringstream &os, int lastpos)
2269 {
2270   // get number of chars to output
2271   int idx = 0;                          /* int intervalls */
2272   int i = 0;
2273   int printed = 0;
2274   string startTitle = titleValue;
2275   for (idx = 0; idx <= ignoreidx; idx++) {
2276     if (i < lastpos) {
2277       if (i <= borders[idx].low) {
2278         int printsize;
2279         if (borders[idx].low > lastpos)
2280           printsize = lastpos - i;
2281         else
2282           printsize = borders[idx].low - i;
2283         if (printsize > 0) {
2284           os << startTitle << par.substr(i, printsize);
2285           i += printsize;
2286           printed += printsize;
2287           startTitle = "";
2288         }
2289         handleParentheses(i, false);
2290         if (i >= borders[idx].low)
2291           i = borders[idx].upper;
2292       }
2293       else {
2294         i = borders[idx].upper;
2295       }
2296     }
2297     else
2298       break;
2299   }
2300   if (lastpos > i) {
2301     os << startTitle << par.substr(i, lastpos-i);
2302     printed += lastpos-i;
2303   }
2304   handleParentheses(lastpos, false);
2305   int startindex;
2306   if (keys["foreignlanguage"].disabled)
2307     startindex = actualdeptindex-langcount;
2308   else
2309     startindex = actualdeptindex;
2310   for (int i = startindex; i > 0; --i) {
2311     os << "}";
2312   }
2313   if (hasTitle && (printed > 0))
2314     os << "}";
2315   if (! isPatternString_)
2316     os << "\n";
2317   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2318 }
2319
2320 void LatexInfo::processRegion(int start, int region_end)
2321 {
2322   while (start < region_end) {          /* Let {[} and {]} survive */
2323     int cnt = interval_.isOpeningPar(start);
2324     if (cnt == 1) {
2325       // Closing is allowed past the region
2326       int closing = interval_.findclosing(start+1, interval_.par.length());
2327       interval_.addIntervall(start, start+1);
2328       interval_.addIntervall(closing, closing+1);
2329     }
2330     else if (cnt == 3)
2331       start += 2;
2332     start = interval_.nextNotIgnored(start+1);
2333   }
2334 }
2335
2336 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2337 {
2338   if (actual.parenthesiscount == 0) {
2339     // "{\tiny{} ...}" ==> "{{} ...}"
2340     interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2341   }
2342   else {
2343     // Remove header hull, that is "\url{abcd}" ==> "abcd"
2344     interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2345     interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2346   }
2347 }
2348
2349 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2350 {
2351   int nextKeyIdx = 0;
2352   switch (actual.keytype)
2353   {
2354     case KeyInfo::isTitle: {
2355       removeHead(actual);
2356       nextKeyIdx = getNextKey();
2357       break;
2358     }
2359     case KeyInfo::cleanToStart: {
2360       actual._dataEnd = actual._dataStart;
2361       nextKeyIdx = getNextKey();
2362       // Search for end of arguments
2363       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2364       if (tmpIdx > 0) {
2365         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2366           entries_[i].disabled = true;
2367         }
2368         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2369       }
2370       while (interval_.par[actual._dataEnd] == ' ')
2371         actual._dataEnd++;
2372       interval_.addIntervall(0, actual._dataEnd+1);
2373       interval_.actualdeptindex = 0;
2374       interval_.depts[0] = actual._dataEnd+1;
2375       interval_.closes[0] = -1;
2376       break;
2377     }
2378     case KeyInfo::isText:
2379       interval_.par[actual._tokenstart] = '#';
2380       //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2381       nextKeyIdx = getNextKey();
2382       break;
2383     case KeyInfo::noContent: {          /* char like "\hspace{2cm}" */
2384       if (actual.disabled)
2385         interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2386       else
2387         interval_.addIntervall(actual._dataStart, actual._dataEnd);
2388     }
2389       // fall through
2390     case KeyInfo::isChar: {
2391       nextKeyIdx = getNextKey();
2392       break;
2393     }
2394     case KeyInfo::isSize: {
2395       if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2396         if (actual.parenthesiscount == 0)
2397           interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2398         else {
2399           interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2400         }
2401         nextKeyIdx = getNextKey();
2402       } else {
2403         // Here _dataStart points to '{', so correct it
2404         actual._dataStart += 1;
2405         actual._tokensize += 1;
2406         actual.parenthesiscount = 1;
2407         if (interval_.par[actual._dataStart] == '}') {
2408           // Determine the end if used like '{\tiny{}...}'
2409           actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2410           interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2411         }
2412         else {
2413           // Determine the end if used like '\tiny{...}'
2414           actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2415         }
2416         // Split on this key if not at start
2417         int start = interval_.nextNotIgnored(previousStart);
2418         if (start < actual._tokenstart) {
2419           interval_.output(os, actual._tokenstart);
2420           interval_.addIntervall(start, actual._tokenstart);
2421         }
2422         // discard entry if at end of actual
2423         nextKeyIdx = process(os, actual);
2424       }
2425       break;
2426     }
2427     case KeyInfo::endArguments: {
2428       // Remove trailing '{}' too
2429       actual._dataStart += 1;
2430       actual._dataEnd += 1;
2431       interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2432       nextKeyIdx = getNextKey();
2433       break;
2434     }
2435     case KeyInfo::noMain:
2436       // fall through
2437     case KeyInfo::isStandard: {
2438       if (actual.disabled) {
2439         removeHead(actual);
2440         processRegion(actual._dataStart, actual._dataStart+1);
2441         nextKeyIdx = getNextKey();
2442       } else {
2443         // Split on this key if not at datastart of calling entry
2444         int start = interval_.nextNotIgnored(previousStart);
2445         if (start < actual._tokenstart) {
2446           interval_.output(os, actual._tokenstart);
2447           interval_.addIntervall(start, actual._tokenstart);
2448         }
2449         // discard entry if at end of actual
2450         nextKeyIdx = process(os, actual);
2451       }
2452       break;
2453     }
2454     case KeyInfo::removeWithArg: {
2455       nextKeyIdx = getNextKey();
2456       // Search for end of arguments
2457       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2458       if (tmpIdx > 0) {
2459         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2460           entries_[i].disabled = true;
2461         }
2462         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2463       }
2464       interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2465       break;
2466     }
2467     case KeyInfo::doRemove: {
2468       // Remove the key with all parameters and following spaces
2469       size_t pos;
2470       size_t start;
2471       if (interval_.par[actual._dataEnd-1] == ' ')
2472         start = actual._dataEnd;
2473       else
2474         start = actual._dataEnd+1;
2475       for (pos = start; pos < interval_.par.length(); pos++) {
2476         if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2477           break;
2478       }
2479       // Remove also enclosing parentheses [] and {}
2480       int numpars = 0;
2481       int spaces = 0;
2482       while (actual._tokenstart > numpars) {
2483         if (pos+numpars >= interval_.par.size())
2484           break;
2485         else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2486           numpars++;
2487         else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2488           numpars++;
2489         else
2490           break;
2491       }
2492       if (numpars > 0) {
2493         if (interval_.par[pos+numpars] == ' ')
2494           spaces++;
2495       }
2496
2497       interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2498       nextKeyIdx = getNextKey();
2499       break;
2500     }
2501     case KeyInfo::isList: {
2502       // Discard space before _tokenstart
2503       int count;
2504       for (count = 0; count < actual._tokenstart; count++) {
2505         if (interval_.par[actual._tokenstart-count-1] != ' ')
2506           break;
2507       }
2508       nextKeyIdx = getNextKey();
2509       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2510       if (tmpIdx > 0) {
2511         // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2512         // with arguments
2513         // How else can we catch this one?
2514         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2515           entries_[i].disabled = true;
2516         }
2517         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2518       }
2519       else if (nextKeyIdx > 0) {
2520         // Ignore any lang entries inside data region
2521         for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2522           if (entries_[i].keytype == KeyInfo::isMain)
2523             entries_[i].disabled = true;
2524         }
2525       }
2526       if (actual.disabled) {
2527         interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2528       }
2529       else {
2530         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2531       }
2532       if (interval_.par[actual._dataEnd+1] == '[') {
2533         int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2534         if ((interval_.par[actual._dataEnd+2] == '{') &&
2535             (interval_.par[posdown-1] == '}')) {
2536           interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2537           interval_.addIntervall(posdown-1, posdown+1);
2538         }
2539         else {
2540           interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2541           interval_.addIntervall(posdown, posdown+1);
2542         }
2543         int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2544         if (blk > posdown) {
2545           // Discard at most 1 space after empty item
2546           int count;
2547           for (count = 0; count < 1; count++) {
2548             if (interval_.par[blk+count] != ' ')
2549               break;
2550           }
2551           if (count > 0)
2552             interval_.addIntervall(blk, blk+count);
2553         }
2554       }
2555       break;
2556     }
2557     case KeyInfo::isSectioning: {
2558       // Discard spaces before _tokenstart
2559       int count;
2560       int val = actual._tokenstart;
2561       for (count = 0; count < actual._tokenstart;) {
2562         val = interval_.previousNotIgnored(val-1);
2563         if (val < 0 || interval_.par[val] != ' ')
2564           break;
2565         else {
2566           count = actual._tokenstart - val;
2567         }
2568       }
2569       if (actual.disabled) {
2570         removeHead(actual, count);
2571         nextKeyIdx = getNextKey();
2572       } else {
2573         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2574         nextKeyIdx = process(os, actual);
2575       }
2576       break;
2577     }
2578     case KeyInfo::isMath: {
2579       // Same as regex, use the content unchanged
2580       nextKeyIdx = getNextKey();
2581       break;
2582     }
2583     case KeyInfo::isRegex: {
2584       // DO NOT SPLIT ON REGEX
2585       // Do not disable
2586       nextKeyIdx = getNextKey();
2587       break;
2588     }
2589     case KeyInfo::isIgnored: {
2590       // Treat like a character for now
2591       nextKeyIdx = getNextKey();
2592       break;
2593     }
2594     case KeyInfo::isMain: {
2595       if (interval_.par.substr(actual._dataStart, 2) == "% ")
2596         interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2597       if (actual._tokenstart > 0) {
2598         int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2599         if ((prev >= 0) && interval_.par[prev] == '%')
2600           interval_.addIntervall(prev, prev+1);
2601       }
2602       if (actual.disabled) {
2603         removeHead(actual);
2604         interval_.langcount++;
2605         if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2606             (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2607           // Discard also the space before math-equation
2608           interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2609         }
2610         nextKeyIdx = getNextKey();
2611         // interval.resetOpenedP(actual._dataStart-1);
2612       }
2613       else {
2614         if (actual._tokenstart < 26) {
2615           // for the first (and maybe dummy) language
2616           interval_.setForDefaultLang(actual);
2617         }
2618         interval_.resetOpenedP(actual._dataStart-1);
2619       }
2620       break;
2621     }
2622     case KeyInfo::invalid:
2623     case KeyInfo::headRemove:
2624       // These two cases cannot happen, already handled
2625       // fall through
2626     default: {
2627       // LYXERR(Debug::INFO, "Unhandled keytype");
2628       nextKeyIdx = getNextKey();
2629       break;
2630     }
2631   }
2632   return nextKeyIdx;
2633 }
2634
2635 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2636 {
2637   int end = interval_.nextNotIgnored(actual._dataEnd);
2638   int oldStart = actual._dataStart;
2639   int nextKeyIdx = getNextKey();
2640   while (true) {
2641     if ((nextKeyIdx < 0) ||
2642         (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2643         (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2644       if (oldStart <= end) {
2645         processRegion(oldStart, end);
2646         oldStart = end+1;
2647       }
2648       break;
2649     }
2650     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2651
2652     if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2653       (void) dispatch(os, actual._dataStart, nextKey);
2654       end = nextKey._tokenstart;
2655       break;
2656     }
2657     processRegion(oldStart, nextKey._tokenstart);
2658     nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2659
2660     oldStart = nextKey._dataEnd+1;
2661   }
2662   // now nextKey is either invalid or is outside of actual._dataEnd
2663   // output the remaining and discard myself
2664   if (oldStart <= end) {
2665     processRegion(oldStart, end);
2666   }
2667   if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2668     end += 1;
2669     // This is the normal case.
2670     // But if using the firstlanguage, the closing may be missing
2671   }
2672   // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2673   int output_end;
2674   if (actual._dataEnd < end)
2675     output_end = interval_.nextNotIgnored(actual._dataEnd);
2676   else if (interval_.par.size() > (size_t) end)
2677     output_end = interval_.nextNotIgnored(end);
2678   else
2679     output_end = interval_.par.size();
2680   if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2681     interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2682   }
2683   // Remove possible empty data
2684   int dstart = interval_.nextNotIgnored(actual._dataStart);
2685   while (interval_.isOpeningPar(dstart) == 1) {
2686     interval_.addIntervall(dstart, dstart+1);
2687     int dend = interval_.findclosing(dstart+1, output_end);
2688     interval_.addIntervall(dend, dend+1);
2689     dstart = interval_.nextNotIgnored(dstart+1);
2690   }
2691   if (dstart < output_end)
2692     interval_.output(os, output_end);
2693   interval_.addIntervall(actual._tokenstart, end);
2694   return nextKeyIdx;
2695 }
2696
2697 string splitOnKnownMacros(string par, bool isPatternString)
2698 {
2699   ostringstream os;
2700   LatexInfo li(par, isPatternString);
2701   // LYXERR(Debug::INFO, "Berfore split: " << par);
2702   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2703   DummyKey.head = "";
2704   DummyKey._tokensize = 0;
2705   DummyKey._dataStart = 0;
2706   DummyKey._dataEnd = par.length();
2707   DummyKey.disabled = true;
2708   int firstkeyIdx = li.getFirstKey();
2709   string s;
2710   if (firstkeyIdx >= 0) {
2711     KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2712     DummyKey._tokenstart = firstKey._tokenstart;
2713     int nextkeyIdx;
2714     if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2715       // Use dummy firstKey
2716       firstKey = DummyKey;
2717       (void) li.setNextKey(firstkeyIdx);
2718     }
2719     else {
2720       if (par.substr(firstKey._dataStart, 2) == "% ")
2721         li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2722     }
2723     nextkeyIdx = li.process(os, firstKey);
2724     while (nextkeyIdx >= 0) {
2725       // Check for a possible gap between the last
2726       // entry and this one
2727       int datastart = li.nextNotIgnored(firstKey._dataStart);
2728       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2729       if ((nextKey._tokenstart > datastart)) {
2730         // Handle the gap
2731         firstKey._dataStart = datastart;
2732         firstKey._dataEnd = par.length();
2733         (void) li.setNextKey(nextkeyIdx);
2734         // Fake the last opened parenthesis
2735         li.setForDefaultLang(firstKey);
2736         nextkeyIdx = li.process(os, firstKey);
2737       }
2738       else {
2739         if (nextKey.keytype != KeyInfo::isMain) {
2740           firstKey._dataStart = datastart;
2741           firstKey._dataEnd = nextKey._dataEnd+1;
2742           (void) li.setNextKey(nextkeyIdx);
2743           li.setForDefaultLang(firstKey);
2744           nextkeyIdx = li.process(os, firstKey);
2745         }
2746         else {
2747           nextkeyIdx = li.process(os, nextKey);
2748         }
2749       }
2750     }
2751     // Handle the remaining
2752     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2753     firstKey._dataEnd = par.length();
2754     // Check if ! empty
2755     if ((firstKey._dataStart < firstKey._dataEnd) &&
2756         (par[firstKey._dataStart] != '}')) {
2757       li.setForDefaultLang(firstKey);
2758       (void) li.process(os, firstKey);
2759     }
2760     s = os.str();
2761     if (s.empty()) {
2762       // return string definitelly impossible to match
2763       s = "\\foreignlanguage{ignore}{ }";
2764     }
2765   }
2766   else
2767     s = par;                            /* no known macros found */
2768   // LYXERR(Debug::INFO, "After split: " << s);
2769   return s;
2770 }
2771
2772 /*
2773  * Try to unify the language specs in the latexified text.
2774  * Resulting modified string is set to "", if
2775  * the searched tex does not contain all the features in the search pattern
2776  */
2777 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2778 {
2779         static Features regex_f;
2780         static int missed = 0;
2781         static bool regex_with_format = false;
2782
2783         int parlen = par.length();
2784
2785         while ((parlen > 0) && (par[parlen-1] == '\n')) {
2786                 parlen--;
2787         }
2788         if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2789                 // Happens to be there in case of description or labeling environment
2790                 parlen--;
2791         }
2792         string result;
2793         if (withformat) {
2794                 // Split the latex input into pieces which
2795                 // can be digested by our search engine
2796                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2797                 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2798                         // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2799                         string doclang = pbuf->params().language->polyglossia();
2800                         static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2801                         smatch sub;
2802                         bool toIgnoreLang = true;
2803                         for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2804                                 sub = *it;
2805                                 if (sub.str(2) != doclang) {
2806                                         toIgnoreLang = false;
2807                                         break;
2808                                 }
2809                         }
2810                         setIgnoreFormat("language", toIgnoreLang);
2811
2812                 }
2813                 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2814                 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2815         }
2816         else
2817                 result = par.substr(0, parlen);
2818         if (isPatternString) {
2819                 missed = 0;
2820                 if (withformat) {
2821                         regex_f = identifyFeatures(result);
2822                         string features = "";
2823                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2824                                 string a = it->first;
2825                                 regex_with_format = true;
2826                                 features += " " + a;
2827                                 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2828                         }
2829                         LYXERR(Debug::FIND, "Identified Features" << features);
2830
2831                 }
2832         } else if (regex_with_format) {
2833                 Features info = identifyFeatures(result);
2834                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2835                         string a = it->first;
2836                         bool b = it->second;
2837                         if (b && ! info[a]) {
2838                                 missed++;
2839                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2840                                 return "";
2841                         }
2842                 }
2843
2844         }
2845         else {
2846                 // LYXERR(Debug::INFO, "No regex formats");
2847         }
2848         return result;
2849 }
2850
2851
2852 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2853 static int identifyClosing(string & t)
2854 {
2855         int open_braces = 0;
2856         do {
2857                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2858                 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2859                         continue;
2860                 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2861                         continue;
2862                 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2863                         continue;
2864                 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2865                         ++open_braces;
2866                         continue;
2867                 }
2868                 break;
2869         } while (true);
2870         return open_braces;
2871 }
2872
2873 static int num_replaced = 0;
2874 static bool previous_single_replace = true;
2875
2876 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2877 {
2878 #if QTSEARCH
2879         // Handle \w properly
2880         QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2881         if (! opt.casesensitive) {
2882                 popts |= QRegularExpression::CaseInsensitiveOption;
2883         }
2884         regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2885         regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2886         regexError = "";
2887         if (regexp.isValid() && regexp2.isValid()) {
2888                 regexIsValid = true;
2889                 // Check '{', '}' pairs inside the regex
2890                 int balanced = 0;
2891                 int skip = 1;
2892                 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2893                         char c = par_as_string[i];
2894                         if (c == '\\') {
2895                                 skip = 2;
2896                                 continue;
2897                         }
2898                         if (c == '{')
2899                                 balanced++;
2900                         else if (c == '}') {
2901                                 balanced--;
2902                                 if (balanced < 0)
2903                                         break;
2904                                 }
2905                                 skip = 1;
2906                         }
2907                 if (balanced != 0) {
2908                         regexIsValid = false;
2909                         regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2910                 }
2911         }
2912         else {
2913                 regexIsValid = false;
2914                 if (!regexp.isValid())
2915                         regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2916                 else
2917                         regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2918         }
2919 #else
2920         if (opt.casesensitive) {
2921                 regexp = regex(regexp_str);
2922                 regexp2 = regex(regexp2_str);
2923         }
2924         else {
2925                 regexp = regex(regexp_str, std::regex_constants::icase);
2926                 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2927         }
2928 #endif
2929 }
2930
2931 static void modifyRegexForMatchWord(string &t)
2932 {
2933         string s("");
2934         regex wordre("(\\\\)*((\\.|\\\\b))");
2935         size_t lastpos = 0;
2936         smatch sub;
2937         for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
2938                 sub = *it;
2939                 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
2940                         continue;
2941                 }
2942                 else if (sub.str(2) == "\\\\b")
2943                         return;
2944                 if (lastpos < (size_t) sub.position(2))
2945                         s += t.substr(lastpos, sub.position(2) - lastpos);
2946                 s += "\\S";
2947                 lastpos = sub.position(2) + sub.length(2);
2948         }
2949         if (lastpos == 0) {
2950                 s = "\\b" + t + "\\b";
2951                 t = s;
2952                 return;
2953         }
2954         else if (lastpos < t.length())
2955                 s += t.substr(lastpos, t.length() - lastpos);
2956       t = "\\b" + s + "\\b";
2957 }
2958
2959 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
2960         : p_buf(&buf), p_first_buf(&buf), opt(opt)
2961 {
2962         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2963         docstring const & ds = stringifySearchBuffer(find_buf, opt);
2964         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2965         if (opt.replace_all && previous_single_replace) {
2966                 previous_single_replace = false;
2967                 num_replaced = 0;
2968         }
2969         else if (!opt.replace_all) {
2970                 num_replaced = 0;       // count number of replaced strings
2971                 previous_single_replace = true;
2972         }
2973         // When using regexp, braces are hacked already by escape_for_regex()
2974         par_as_string = normalize(ds);
2975         open_braces = 0;
2976         close_wildcards = 0;
2977
2978         size_t lead_size = 0;
2979         // correct the language settings
2980         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
2981         opt.matchAtStart = false;
2982         if (!use_regexp) {
2983                 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
2984                 if (opt.ignoreformat) {
2985                         lead_size = 0;
2986                 }
2987                 else {
2988                         lead_size = identifyLeading(par_as_string);
2989                 }
2990                 lead_as_string = par_as_string.substr(0, lead_size);
2991                 string lead_as_regex_string = string2regex(lead_as_string);
2992                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2993                 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
2994                 /* Handle whole words too in this case
2995                 */
2996                 if (opt.matchword) {
2997                         par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
2998                         opt.matchword = false;
2999                 }
3000                 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3001                 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3002                 CreateRegexp(opt, regexp_str, regexp2_str);
3003                 use_regexp = true;
3004                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3005                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3006                 return;
3007         }
3008
3009         if (!opt.ignoreformat) {
3010                 lead_size = identifyLeading(par_as_string);
3011                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3012                 lead_as_string = par_as_string.substr(0, lead_size);
3013                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3014         }
3015
3016         // Here we are using regexp
3017         LASSERT(use_regexp, /**/);
3018         {
3019                 string lead_as_regexp;
3020                 if (lead_size > 0) {
3021                         lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3022                         regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3023                         par_as_string = par_as_string_nolead;
3024                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3025                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3026                 }
3027                 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3028                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3029                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3030                 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3031                 ++close_wildcards;
3032                 size_t lng = par_as_string.size();
3033                 if (!opt.ignoreformat) {
3034                         // Remove extra '\}' at end if not part of \{\.\}
3035                         while(lng > 2) {
3036                                 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3037                                         if (lng >= 6) {
3038                                                 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3039                                                         break;
3040                                         }
3041                                         lng -= 2;
3042                                         open_braces++;
3043                                 }
3044                                 else
3045                                         break;
3046                         }
3047                         if (lng < par_as_string.size())
3048                                 par_as_string = par_as_string.substr(0,lng);
3049                 }
3050                 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3051                 if ((lng > 0) && (par_as_string[0] == '^')) {
3052                         par_as_string = par_as_string.substr(1);
3053                         --lng;
3054                         opt.matchAtStart = true;
3055                 }
3056                 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3057                 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3058                 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3059
3060                 // If entered regexp must match at begin of searched string buffer
3061                 // Kornel: Added parentheses to use $1 for size of the leading string
3062                 string regexp_str;
3063                 string regexp2_str;
3064                 {
3065                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3066                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
3067                         // so the convert has no effect in that case
3068                         for (int i = 7; i > 0; --i) {
3069                                 string orig = "\\\\" + std::to_string(i);
3070                                 string dest = "\\" + std::to_string(i+2);
3071                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
3072                         }
3073                         if (opt.matchword) {
3074                                 modifyRegexForMatchWord(par_as_string);
3075                                 opt.matchword = false;
3076                         }
3077                         regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3078                         regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3079                 }
3080                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3081                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3082                 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3083         }
3084 }
3085
3086 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3087 {
3088         MatchResult mres;
3089
3090         mres.searched_size = len;
3091         if (at_begin &&
3092                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3093                 return mres;
3094
3095         docstring docstr = stringifyFromForSearch(opt, cur, len);
3096         string str;
3097         str = normalize(docstr);
3098         if (!opt.ignoreformat) {
3099                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3100                 // remove closing '}' and '\n' to allow for use of '$' in regex
3101                 size_t lng = str.size();
3102                 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3103                         lng--;
3104                 if (lng != str.size()) {
3105                         str = str.substr(0, lng);
3106                 }
3107         }
3108         if (str.empty()) {
3109                 mres.match_len = -1;
3110                 return mres;
3111         }
3112         LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3113
3114         LASSERT(use_regexp, /**/);
3115         {
3116                 // use_regexp always true
3117                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3118 #if QTSEARCH
3119                 QString qstr = QString::fromStdString(str);
3120                 QRegularExpression const *p_regexp;
3121                 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3122                 if (at_begin) {
3123                         p_regexp = &regexp;
3124                 } else {
3125                         p_regexp = &regexp2;
3126                 }
3127                 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3128                 if (!match.hasMatch())
3129                         return mres;
3130 #else
3131                 regex const *p_regexp;
3132                 regex_constants::match_flag_type flags;
3133                 if (at_begin) {
3134                         flags = regex_constants::match_continuous;
3135                         p_regexp = &regexp;
3136                 } else {
3137                         flags = regex_constants::match_default;
3138                         p_regexp = &regexp2;
3139                 }
3140                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3141                 if (re_it == sregex_iterator())
3142                         return mres;
3143                 match_results<string::const_iterator> const & m = *re_it;
3144 #endif
3145                 // Whole found string, including the leading
3146                 // std: m[0].second - m[0].first
3147                 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3148                 //
3149                 // Size of the leading string
3150                 // std: m[1].second - m[1].first
3151                 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3152                 int leadingsize = 0;
3153 #if QTSEARCH
3154                 if (match.lastCapturedIndex() > 0) {
3155                         leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3156                 }
3157
3158 #else
3159                 if (m.size() > 2) {
3160                         leadingsize = m[1].second - m[1].first;
3161                 }
3162 #endif
3163 #if QTSEARCH
3164                 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3165                 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3166                 // because of different number of closing at end of string
3167                 // we have to 'unify' the length of the post-match.
3168                 // Done by ignoring closing parenthesis and linefeeds at string end
3169                 int matchend = match.capturedEnd(0);
3170                 size_t strsize = qstr.size();
3171                 if (!opt.ignoreformat) {
3172                         while (mres.match_len > 0) {
3173                                 QChar c = qstr.at(matchend - 1);
3174                                 if ((c == '\n') || (c == '}') || (c == '{')) {
3175                                         mres.match_len--;
3176                                         matchend--;
3177                                 }
3178                                 else
3179                                         break;
3180                         }
3181                         while (strsize > (size_t) match.capturedEnd(0)) {
3182                                 QChar c = qstr.at(strsize-1);
3183                                 if ((c == '\n') || (c == '}')) {
3184                                         --strsize;
3185                                 }
3186                                 else
3187                                         break;
3188                         }
3189                 }
3190                 // LYXERR0(qstr.toStdString());
3191                 mres.match2end = strsize - matchend;
3192                 mres.pos = match.capturedStart(2);
3193 #else
3194                 mres.match_prefix = m[2].second - m[2].first;
3195                 mres.match_len = m[0].second - m[2].second;
3196                 // ignore closing parenthesis and linefeeds at string end
3197                 size_t strend = m[0].second - m[0].first;
3198                 int matchend = strend;
3199                 size_t strsize = str.size();
3200                 if (!opt.ignoreformat) {
3201                         while (mres.match_len > 0) {
3202                                 char c = str.at(matchend - 1);
3203                                 if ((c == '\n') || (c == '}') || (c == '{')) {
3204                                         mres.match_len--;
3205                                         matchend--;
3206                                 }
3207                                 else
3208                                         break;
3209                         }
3210                         while (strsize > strend) {
3211                                 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3212                                         --strsize;
3213                                 }
3214                                 else
3215                                         break;
3216                         }
3217                 }
3218                 // LYXERR0(str);
3219                 mres.match2end = strsize - matchend;
3220                 mres.pos = m[2].first - m[0].first;;
3221 #endif
3222                 if (mres.match2end < 0)
3223                   mres.match_len = 0;
3224                 mres.leadsize = leadingsize;
3225 #if QTSEARCH
3226                 if (mres.match_len > 0) {
3227                   string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3228                   mres.result.push_back(a0);
3229                   for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3230                     mres.result.push_back(match.captured(i).toStdString());
3231                   }
3232                 }
3233 #else
3234                 if (mres.match_len > 0) {
3235                   string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3236                   mres.result.push_back(a0);
3237                   for (size_t i = 3; i < m.size(); i++) {
3238                     mres.result.push_back(m[i]);
3239                   }
3240                 }
3241 #endif
3242                 return mres;
3243         }
3244 }
3245
3246
3247 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3248 {
3249         MatchResult mres = findAux(cur, len, at_begin);
3250         int res = mres.match_len;
3251         LYXERR(Debug::FIND,
3252                "res=" << res << ", at_begin=" << at_begin
3253                << ", matchAtStart=" << opt.matchAtStart
3254                << ", inTexted=" << cur.inTexted());
3255         if (opt.matchAtStart) {
3256                 if (cur.pos() != 0)
3257                         mres.match_len = 0;
3258                 else if (mres.match_prefix > 0)
3259                         mres.match_len = 0;
3260                 return mres;
3261         }
3262         else
3263                 return mres;
3264 }
3265
3266 #if 0
3267 static bool simple_replace(string &t, string from, string to)
3268 {
3269   regex repl("(\\\\)*(" + from + ")");
3270   string s("");
3271   size_t lastpos = 0;
3272   smatch sub;
3273   for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3274     sub = *it;
3275     if ((sub.position(2) - sub.position(0)) % 2 == 1)
3276       continue;
3277     if (lastpos < (size_t) sub.position(2))
3278       s += t.substr(lastpos, sub.position(2) - lastpos);
3279     s += to;
3280     lastpos = sub.position(2) + sub.length(2);
3281   }
3282   if (lastpos == 0)
3283     return false;
3284   else if (lastpos < t.length())
3285     s += t.substr(lastpos, t.length() - lastpos);
3286   t = s;
3287   return true;
3288 }
3289 #endif
3290
3291 string MatchStringAdv::normalize(docstring const & s) const
3292 {
3293         string t;
3294         t = lyx::to_utf8(s);
3295         // Remove \n at begin
3296         while (!t.empty() && t[0] == '\n')
3297                 t = t.substr(1);
3298         // Remove \n at end
3299         while (!t.empty() && t[t.size() - 1] == '\n')
3300                 t = t.substr(0, t.size() - 1);
3301         size_t pos;
3302         // Handle all other '\n'
3303         while ((pos = t.find("\n")) != string::npos) {
3304                 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3305                         // Handle '\\\n'
3306                         if (isAlnumASCII(t[pos+1])) {
3307                                 t.replace(pos-2, 3, " ");
3308                         }
3309                         else {
3310                                 t.replace(pos-2, 3, "");
3311                         }
3312                 }
3313                 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3314                         // '\n' adjacent to non-alpha-numerics, discard
3315                         t.replace(pos, 1, "");
3316                 }
3317                 else {
3318                         // Replace all other \n with spaces
3319                         t.replace(pos, 1, " ");
3320                 }
3321         }
3322         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3323         // Kornel: Added textsl, textsf, textit, texttt and noun
3324         // + allow to seach for colored text too
3325         LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3326         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3327                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3328         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3329                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3330         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3331
3332         return t;
3333 }
3334
3335
3336 docstring stringifyFromCursor(DocIterator const & cur, int len)
3337 {
3338         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3339         if (cur.inTexted()) {
3340                 Paragraph const & par = cur.paragraph();
3341                 // TODO what about searching beyond/across paragraph breaks ?
3342                 // TODO Try adding a AS_STR_INSERTS as last arg
3343                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3344                         int(par.size()) : cur.pos() + len;
3345                 // OutputParams runparams(&cur.buffer()->params().encoding());
3346                 OutputParams runparams(encodings.fromLyXName("utf8"));
3347                 runparams.nice = true;
3348                 runparams.flavor = Flavor::XeTeX;
3349                 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3350                 // No side effect of file copying and image conversion
3351                 runparams.dryrun = true;
3352                 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3353                 if (ignoreFormats.getDeleted()) {
3354                         option |= AS_STR_SKIPDELETE;
3355                         runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3356                 }
3357                 else {
3358                         runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3359                 }
3360                 LYXERR(Debug::FIND, "Stringifying with cur: "
3361                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
3362                 return par.asString(cur.pos(), end,
3363                         option,
3364                         &runparams);
3365         } else if (cur.inMathed()) {
3366                 CursorSlice cs = cur.top();
3367                 MathData md = cs.cell();
3368                 MathData::const_iterator it_end =
3369                         (( len == -1 || cs.pos() + len > int(md.size()))
3370                          ? md.end()
3371                          : md.begin() + cs.pos() + len );
3372                 MathData md2;
3373                 for (MathData::const_iterator it = md.begin() + cs.pos();
3374                      it != it_end; ++it)
3375                         md2.push_back(*it);
3376                 docstring s = asString(md2);
3377                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3378                 return s;
3379         }
3380         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3381         return docstring();
3382 }
3383
3384
3385 /** Computes the LaTeX export of buf starting from cur and ending len positions
3386  * after cur, if len is positive, or at the paragraph or innermost inset end
3387  * if len is -1.
3388  */
3389 docstring latexifyFromCursor(DocIterator const & cur, int len)
3390 {
3391         /*
3392         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3393         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3394                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3395         */
3396         Buffer const & buf = *cur.buffer();
3397
3398         odocstringstream ods;
3399         otexstream os(ods);
3400         //OutputParams runparams(&buf.params().encoding());
3401         OutputParams runparams(encodings.fromLyXName("utf8"));
3402         runparams.nice = false;
3403         runparams.flavor = Flavor::XeTeX;
3404         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3405         // No side effect of file copying and image conversion
3406         runparams.dryrun = true;
3407         if (ignoreFormats.getDeleted()) {
3408                 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3409         }
3410         else {
3411                 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3412         }
3413
3414         if (cur.inTexted()) {
3415                 // @TODO what about searching beyond/across paragraph breaks ?
3416                 pos_type endpos = cur.paragraph().size();
3417                 if (len != -1 && endpos > cur.pos() + len)
3418                         endpos = cur.pos() + len;
3419                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3420                           string(), cur.pos(), endpos);
3421                 string s = lyx::to_utf8(ods.str());
3422                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3423                 return(lyx::from_utf8(s));
3424         } else if (cur.inMathed()) {
3425                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3426                 for (int s = cur.depth() - 1; s >= 0; --s) {
3427                         CursorSlice const & cs = cur[s];
3428                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3429                                 TeXMathStream ws(os);
3430                                 cs.asInsetMath()->asHullInset()->header_write(ws);
3431                                 break;
3432                         }
3433                 }
3434
3435                 CursorSlice const & cs = cur.top();
3436                 MathData md = cs.cell();
3437                 MathData::const_iterator it_end =
3438                         ((len == -1 || cs.pos() + len > int(md.size()))
3439                          ? md.end()
3440                          : md.begin() + cs.pos() + len);
3441                 MathData md2;
3442                 for (MathData::const_iterator it = md.begin() + cs.pos();
3443                      it != it_end; ++it)
3444                         md2.push_back(*it);
3445
3446                 ods << asString(md2);
3447                 // Retrieve the math environment type, and add '$' or '$]'
3448                 // or others (\end{equation}) accordingly
3449                 for (int s = cur.depth() - 1; s >= 0; --s) {
3450                         CursorSlice const & cs2 = cur[s];
3451                         InsetMath * inset = cs2.asInsetMath();
3452                         if (inset && inset->asHullInset()) {
3453                                 TeXMathStream ws(os);
3454                                 inset->asHullInset()->footer_write(ws);
3455                                 break;
3456                         }
3457                 }
3458                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3459         } else {
3460                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3461         }
3462         return ods.str();
3463 }
3464
3465 #if defined(ResultsDebug)
3466 // Debugging output
3467 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3468 {
3469         LYXERR0( "from:\t\t\t" << from);
3470         string status;
3471         if (mres.pos_len > 0) {
3472                 // Set in finalize
3473                 status = "FINALSEARCH";
3474         }
3475         else {
3476                 if (mres.match_len > 0) {
3477                         if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3478                                 status = "Good Match";
3479                         else
3480                                 status = "Matched in";
3481                 }
3482                 else
3483                         status = "MissedSearch";
3484         }
3485
3486         LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3487         if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3488                 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3489         if ((mres.pos > 0) || (mres.match_prefix > 0))
3490                 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3491         for (size_t i = 0; i < mres.result.size(); i++)
3492                 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3493 }
3494         #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3495 #else
3496         #define displayMres(s, txt, cur)
3497 #endif
3498
3499 /** Finalize an advanced find operation, advancing the cursor to the innermost
3500  ** position that matches, plus computing the length of the matching text to
3501  ** be selected
3502  ** Return the cur.pos() difference between start and end of found match
3503  **/
3504 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3505 {
3506         // Search the foremost position that matches (avoids find of entire math
3507         // inset when match at start of it)
3508         DocIterator old_cur(cur.buffer());
3509         MatchResult mres;
3510         static MatchResult fail = MatchResult();
3511         MatchResult max_match;
3512         // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3513         // Happens with e.g. hyperlinks
3514         // either one sees "http://www.bla.bla" or nothing
3515         // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3516         // and although we search for only 3 chars, we find the whole hyperlink inset
3517         bool at_begin = (expected.match_prefix == 0);
3518         if (!match.opt.forward && match.opt.ignoreformat) {
3519                 if (expected.pos > 0)
3520                         return fail;
3521         }
3522         LASSERT(at_begin, /**/);
3523         if (expected.match_len > 0 && at_begin) {
3524                 // Search for deepest match
3525                 old_cur = cur;
3526                 max_match = expected;
3527                 do {
3528                         size_t d = cur.depth();
3529                         cur.forwardPos();
3530                         if (!cur)
3531                                 break;
3532                         if (cur.depth() < d)
3533                                 break;
3534                         if (cur.depth() == d)
3535                                 break;
3536                         size_t lastd = d;
3537                         while (cur && cur.depth() > lastd) {
3538                                 lastd = cur.depth();
3539                                 mres = match(cur, -1, at_begin);
3540                                 displayMres(mres, "Checking innermost", cur);
3541                                 if (mres.match_len > 0)
3542                                         break;
3543                                 // maybe deeper?
3544                                 cur.forwardPos();
3545                         }
3546                         if (mres.match_len < expected.match_len)
3547                                 break;
3548                         max_match = mres;
3549                         old_cur = cur;;
3550                 } while(1);
3551                 cur = old_cur;
3552         }
3553         else {
3554                 // (expected.match_len <= 0)
3555                 mres = match(cur);      /* match valid only if not searching whole words */
3556                 displayMres(mres, "Start with negative match", cur);
3557                 max_match = mres;
3558         }
3559         if (max_match.match_len <= 0) return fail;
3560         LYXERR(Debug::FIND, "Ok");
3561
3562         // Compute the match length
3563         int len = 1;
3564         if (cur.pos() + len > cur.lastpos())
3565           return fail;
3566
3567         LASSERT(match.use_regexp, /**/);
3568         {
3569           int minl = 1;
3570           int maxl = cur.lastpos() - cur.pos();
3571           // Greedy behaviour while matching regexps
3572           while (maxl > minl) {
3573             MatchResult mres2;
3574             mres2 = match(cur, len, at_begin);
3575             displayMres(mres2, "Finalize loop", cur);
3576             int actual_match_len = mres2.match_len;
3577             if (actual_match_len >= max_match.match_len) {
3578               // actual_match_len > max_match _can_ happen,
3579               // if the search area splits
3580               // some following word so that the regex
3581               // (e.g. 'r.*r\b' matches 'r' from the middle of the
3582               // splitted word)
3583               // This means, the len value is too big
3584               actual_match_len = max_match.match_len;
3585               max_match = mres2;
3586               max_match.match_len = actual_match_len;
3587               maxl = len;
3588               if (maxl - minl < 4)
3589                 len = (int)((maxl + minl)/2);
3590               else
3591                 len = (int)(minl + (maxl - minl + 3)/4);
3592             }
3593             else {
3594               // (actual_match_len < max_match.match_len)
3595               minl = len + 1;
3596               len = (int)((maxl + minl)/2);
3597             }
3598           }
3599           len = minl;
3600           old_cur = cur;
3601           // Search for real start of matched characters
3602           while (len > 1) {
3603             MatchResult actual_match;
3604             do {
3605               cur.forwardPos();
3606             } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3607             if (cur.depth() < old_cur.depth()) {
3608               // Outer inset?
3609               LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3610               break;
3611             }
3612             if (cur.pos() != old_cur.pos()) {
3613               // OK, forwarded 1 pos in actual inset
3614               actual_match = match(cur, len-1, at_begin);
3615               if (actual_match.match_len == max_match.match_len) {
3616                 // Ha, got it! The shorter selection has the same match length
3617                 len--;
3618                 old_cur = cur;
3619                 max_match = actual_match;
3620               }
3621               else {
3622                 // OK, the shorter selection matches less chars, revert to previous value
3623                 cur = old_cur;
3624                 break;
3625               }
3626             }
3627             else {
3628               LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3629               actual_match = match(cur, len, at_begin);
3630               if (actual_match.match_len == max_match.match_len) {
3631                 old_cur = cur;
3632                 max_match = actual_match;
3633               }
3634             }
3635           }
3636           if (len == 0)
3637             return fail;
3638           else {
3639             max_match.pos_len = len;
3640             displayMres(max_match, "SEARCH RESULT", cur)
3641             return max_match;
3642           }
3643         }
3644 }
3645
3646 /// Finds forward
3647 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3648 {
3649         if (!cur)
3650                 return 0;
3651         bool repeat = false;
3652         DocIterator orig_cur;   // to be used if repeat not successful
3653         MatchResult orig_mres;
3654         while (!theApp()->longOperationCancelled() && cur) {
3655                 //(void) findAdvForwardInnermost(cur);
3656                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3657                 MatchResult mres = match(cur, -1, false);
3658                 string msg = "Starting";
3659                 if (repeat)
3660                         msg = "Repeated";
3661                 displayMres(mres, msg + " findForwardAdv", cur)
3662                 int match_len = mres.match_len;
3663                 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3664                         LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3665                         match_len = 0;
3666                 }
3667                 if (match_len <= 0) {
3668                         // This should exit nested insets, if any, or otherwise undefine the currsor.
3669                         cur.pos() = cur.lastpos();
3670                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3671                         cur.forwardPos();
3672                 }
3673                 else {  // match_len > 0
3674                         // Try to find the begin of searched string
3675                         int increment;
3676                         int firstInvalid = cur.lastpos() - cur.pos();
3677                         {
3678                                 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3679                                 int incrcur = (firstInvalid + 1 )*3/4;
3680                                 if (incrcur < incrmatch)
3681                                         increment = incrcur;
3682                                 else
3683                                         increment = incrmatch;
3684                                 if (increment < 1)
3685                                         increment = 1;
3686                         }
3687                         LYXERR(Debug::FIND, "Set increment to " << increment);
3688                         while (increment > 0) {
3689                                 DocIterator old_cur = cur;
3690                                 if (cur.pos() + increment >= cur.lastpos()) {
3691                                         increment /= 2;
3692                                         continue;
3693                                 }
3694                                 cur.pos() = cur.pos() + increment;
3695                                 MatchResult mres2 = match(cur, -1, false);
3696                                 displayMres(mres2, "findForwardAdv loop", cur)
3697                                 switch (interpretMatch(mres, mres2)) {
3698                                         case MatchResult::newIsTooFar:
3699                                                 // behind the expected match
3700                                                 firstInvalid = increment;
3701                                                 cur = old_cur;
3702                                                 increment /= 2;
3703                                                 break;
3704                                         case MatchResult::newIsBetter:
3705                                                 // not reached yet, but cur.pos()+increment is bettert
3706                                                 mres = mres2;
3707                                                 firstInvalid -= increment;
3708                                                 if (increment > firstInvalid*3/4)
3709                                                         increment = firstInvalid*3/4;
3710                                                 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3711                                                         if (increment >= mres2.match_prefix)
3712                                                                 increment = (mres2.match_prefix+1)*3/4;
3713                                                 }
3714                                                 break;
3715                                         default:
3716                                                 // Todo@
3717                                                 // Handle not like MatchResult::newIsTooFar
3718                                                 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3719                                                 firstInvalid--;
3720                                                 increment = increment*3/4;
3721                                                 cur = old_cur;
3722                                         break;
3723                                 }
3724                         }
3725                         if (mres.match_len > 0) {
3726                                 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3727                                         // The match seems to indicate some deeper level 
3728                                         repeat = true;
3729                                         orig_cur = cur;
3730                                         orig_mres = mres;
3731                                         cur.forwardPos();
3732                                         continue;
3733                                 }
3734                         }
3735                         else if (repeat) {
3736                                 // should never be reached.
3737                                 cur = orig_cur;
3738                                 mres = orig_mres;
3739                         }
3740                         // LYXERR0("Leaving first loop");
3741                         LYXERR(Debug::FIND, "Finalizing 1");
3742                         MatchResult found_match = findAdvFinalize(cur, match, mres);
3743                         if (found_match.match_len > 0) {
3744                                 LASSERT(found_match.pos_len > 0, /**/);
3745                                 match.FillResults(found_match);
3746                                 return found_match.pos_len;
3747                         }
3748                         else {
3749                                 // try next possible match
3750                                 cur.forwardPos();
3751                                 repeat = false;
3752                                 continue;
3753                         }
3754                 }
3755         }
3756         return 0;
3757 }
3758
3759
3760 /// Find the most backward consecutive match within same paragraph while searching backwards.
3761 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3762 {
3763         DocIterator cur_begin = cur;
3764         cur_begin.pos() = 0;
3765         DocIterator tmp_cur = cur;
3766         MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3767         Inset & inset = cur.inset();
3768         for (; cur != cur_begin; cur.backwardPos()) {
3769                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3770                 DocIterator new_cur = cur;
3771                 new_cur.backwardPos();
3772                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3773                         break;
3774                 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3775                 if (new_mr.match_len == mr.match_len)
3776                         break;
3777                 mr = new_mr;
3778         }
3779         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3780         return mr;
3781 }
3782
3783
3784 /// Finds backwards
3785 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3786 {
3787         if (! cur)
3788                 return 0;
3789         // Backup of original position
3790         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3791         if (cur == cur_begin)
3792                 return 0;
3793         cur.backwardPos();
3794         DocIterator cur_orig(cur);
3795         bool pit_changed = false;
3796         do {
3797                 cur.pos() = 0;
3798                 MatchResult found_match = match(cur, -1, false);
3799
3800                 if (found_match.match_len > 0) {
3801                         if (pit_changed)
3802                                 cur.pos() = cur.lastpos();
3803                         else
3804                                 cur.pos() = cur_orig.pos();
3805                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3806                         DocIterator cur_prev_iter;
3807                         do {
3808                                 found_match = match(cur);
3809                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3810                                        << (found_match.match_len > 0) << ", cur: " << cur);
3811                                 if (found_match.match_len > 0) {
3812                                         MatchResult found_mr = findMostBackwards(cur, match, found_match);
3813                                         if (found_mr.pos_len > 0) {
3814                                                 match.FillResults(found_mr);
3815                                                 return found_mr.pos_len;
3816                                         }
3817                                 }
3818
3819                                 // Stop if begin of document reached
3820                                 if (cur == cur_begin)
3821                                         break;
3822                                 cur_prev_iter = cur;
3823                                 cur.backwardPos();
3824                         } while (true);
3825                 }
3826                 if (cur == cur_begin)
3827                         break;
3828                 if (cur.pit() > 0)
3829                         --cur.pit();
3830                 else
3831                         cur.backwardPos();
3832                 pit_changed = true;
3833         } while (!theApp()->longOperationCancelled());
3834         return 0;
3835 }
3836
3837
3838 } // namespace
3839
3840
3841 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3842                                  DocIterator const & cur, int len)
3843 {
3844         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3845                 return docstring();
3846         if (!opt.ignoreformat)
3847                 return latexifyFromCursor(cur, len);
3848         else
3849                 return stringifyFromCursor(cur, len);
3850 }
3851
3852
3853 FindAndReplaceOptions::FindAndReplaceOptions(
3854         docstring const & _find_buf_name, bool _casesensitive,
3855         bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3856         docstring const & _repl_buf_name, bool _keep_case,
3857         SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3858         : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3859           forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3860           repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3861 {
3862 }
3863
3864
3865 namespace {
3866
3867
3868 /** Check if 'len' letters following cursor are all non-lowercase */
3869 static bool allNonLowercase(Cursor const & cur, int len)
3870 {
3871         pos_type beg_pos = cur.selectionBegin().pos();
3872         pos_type end_pos = cur.selectionBegin().pos() + len;
3873         if (len > cur.lastpos() + 1 - beg_pos) {
3874                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3875                 len = cur.lastpos() + 1 - beg_pos;
3876                 end_pos = beg_pos + len;
3877         }
3878         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3879                 if (isLowerCase(cur.paragraph().getChar(pos)))
3880                         return false;
3881         return true;
3882 }
3883
3884
3885 /** Check if first letter is upper case and second one is lower case */
3886 static bool firstUppercase(Cursor const & cur)
3887 {
3888         char_type ch1, ch2;
3889         pos_type pos = cur.selectionBegin().pos();
3890         if (pos >= cur.lastpos() - 1) {
3891                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3892                 return false;
3893         }
3894         ch1 = cur.paragraph().getChar(pos);
3895         ch2 = cur.paragraph().getChar(pos + 1);
3896         bool result = isUpperCase(ch1) && isLowerCase(ch2);
3897         LYXERR(Debug::FIND, "firstUppercase(): "
3898                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3899                << ch2 << "(" << char(ch2) << ")"
3900                << ", result=" << result << ", cur=" << cur);
3901         return result;
3902 }
3903
3904
3905 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3906  **
3907  ** \fixme What to do with possible further paragraphs in replace buffer ?
3908  **/
3909 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3910 {
3911         ParagraphList::iterator pit = buffer.paragraphs().begin();
3912         LASSERT(!pit->empty(), /**/);
3913         pos_type right = pos_type(1);
3914         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3915         right = pit->size();
3916         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3917 }
3918 } // namespace
3919
3920 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3921 {
3922   // Should replace the string "$" + std::to_string(matchnum) with replacement
3923   // if the char '$' is not prefixed with odd number of char '\\'
3924   static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3925   string s;
3926   size_t lastpos = 0;
3927   smatch sub;
3928   for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3929     sub = *it;
3930     if ((sub.position(2) - sub.position(0)) % 2 == 1)
3931       continue;
3932     int num = stoi(sub.str(3), nullptr, 10);
3933     if (num >= maxmatchnum)
3934       continue;
3935     if (lastpos < (size_t) sub.position(2))
3936       s += t.substr(lastpos, sub.position(2) - lastpos);
3937     s += replacements[num];
3938     lastpos = sub.position(2) + sub.length(2);
3939   }
3940   if (lastpos == 0)
3941     return false;
3942   else if (lastpos < t.length())
3943     s += t.substr(lastpos, t.length() - lastpos);
3944   t = s;
3945   return true;
3946 }
3947
3948 ///
3949 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3950 {
3951         Cursor & cur = bv->cursor();
3952         if (opt.repl_buf_name.empty()
3953             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3954             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3955                 return 0;
3956
3957         DocIterator sel_beg = cur.selectionBegin();
3958         DocIterator sel_end = cur.selectionEnd();
3959         if (&sel_beg.inset() != &sel_end.inset()
3960             || sel_beg.pit() != sel_end.pit()
3961             || sel_beg.idx() != sel_end.idx())
3962                 return 0;
3963         int sel_len = sel_end.pos() - sel_beg.pos();
3964         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3965                << ", sel_len: " << sel_len << endl);
3966         if (sel_len == 0)
3967                 return 0;
3968         LASSERT(sel_len > 0, return 0);
3969
3970         if (!matchAdv(sel_beg, sel_len).match_len)
3971                 return 0;
3972
3973         // Build a copy of the replace buffer, adapted to the KeepCase option
3974         Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
3975         ostringstream oss;
3976         repl_buffer_orig.write(oss);
3977         string lyx = oss.str();
3978         if (matchAdv.valid_matches > 0) {
3979           replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
3980         }
3981         Buffer repl_buffer("", false);
3982         repl_buffer.setUnnamed(true);
3983         LASSERT(repl_buffer.readString(lyx), return 0);
3984         if (opt.keep_case && sel_len >= 2) {
3985                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
3986                 if (cur.inTexted()) {
3987                         if (firstUppercase(cur))
3988                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
3989                         else if (allNonLowercase(cur, sel_len))
3990                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
3991                 }
3992         }
3993         cap::cutSelection(cur, false);
3994         if (cur.inTexted()) {
3995                 repl_buffer.changeLanguage(
3996                         repl_buffer.language(),
3997                         cur.getFont().language());
3998                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
3999                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4000                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4001                                         repl_buffer.params().documentClassPtr(),
4002                                         bv->buffer().errorList("Paste"));
4003                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4004                 sel_len = repl_buffer.paragraphs().begin()->size();
4005         } else if (cur.inMathed()) {
4006                 odocstringstream ods;
4007                 otexstream os(ods);
4008                 // OutputParams runparams(&repl_buffer.params().encoding());
4009                 OutputParams runparams(encodings.fromLyXName("utf8"));
4010                 runparams.nice = false;
4011                 runparams.flavor = Flavor::XeTeX;
4012                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4013                 runparams.dryrun = true;
4014                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4015                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4016                 docstring repl_latex = ods.str();
4017                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4018                 string s;
4019                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4020                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4021                 repl_latex = from_utf8(s);
4022                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4023                 MathData ar(cur.buffer());
4024                 asArray(repl_latex, ar, Parse::NORMAL);
4025                 cur.insert(ar);
4026                 sel_len = ar.size();
4027                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4028         }
4029         if (cur.pos() >= sel_len)
4030                 cur.pos() -= sel_len;
4031         else
4032                 cur.pos() = 0;
4033         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4034         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4035         bv->processUpdateFlags(Update::Force);
4036         return 1;
4037 }
4038
4039
4040 /// Perform a FindAdv operation.
4041 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4042 {
4043         DocIterator cur;
4044         int pos_len = 0;
4045
4046         // e.g., when invoking word-findadv from mini-buffer wither with
4047         //       wrong options syntax or before ever opening advanced F&R pane
4048         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4049                 return false;
4050
4051         try {
4052                 MatchStringAdv matchAdv(bv->buffer(), opt);
4053 #if QTSEARCH
4054                 if (!matchAdv.regexIsValid) {
4055                         bv->message(lyx::from_utf8(matchAdv.regexError));
4056                         return(false);
4057                 }
4058 #endif
4059                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4060                 if (length > 0)
4061                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4062                 num_replaced += findAdvReplace(bv, opt, matchAdv);
4063                 cur = bv->cursor();
4064                 if (opt.forward)
4065                         pos_len = findForwardAdv(cur, matchAdv);
4066                 else
4067                         pos_len = findBackwardsAdv(cur, matchAdv);
4068         } catch (exception & ex) {
4069                 bv->message(from_utf8(ex.what()));
4070                 return false;
4071         }
4072
4073         if (pos_len == 0) {
4074                 if (num_replaced > 0) {
4075                         switch (num_replaced)
4076                         {
4077                                 case 1:
4078                                         bv->message(_("One match has been replaced."));
4079                                         break;
4080                                 case 2:
4081                                         bv->message(_("Two matches have been replaced."));
4082                                         break;
4083                                 default:
4084                                         bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4085                                         break;
4086                         }
4087                         num_replaced = 0;
4088                 }
4089                 else {
4090                         bv->message(_("Match not found."));
4091                 }
4092                 return false;
4093         }
4094
4095         if (num_replaced > 0)
4096                 bv->message(_("Match has been replaced."));
4097         else
4098                 bv->message(_("Match found."));
4099
4100         if (cur.pos() + pos_len > cur.lastpos()) {
4101                 // Prevent crash in bv->putSelectionAt()
4102                 // Should never happen, maybe LASSERT() here?
4103                 pos_len = cur.lastpos() - cur.pos();
4104         }
4105         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4106         bv->putSelectionAt(cur, pos_len, !opt.forward);
4107
4108         return true;
4109 }
4110
4111
4112 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4113 {
4114         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4115            << opt.casesensitive << ' '
4116            << opt.matchword << ' '
4117            << opt.forward << ' '
4118            << opt.expandmacros << ' '
4119            << opt.ignoreformat << ' '
4120            << opt.replace_all << ' '
4121            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4122            << opt.keep_case << ' '
4123            << int(opt.scope) << ' '
4124            << int(opt.restr);
4125
4126         LYXERR(Debug::FIND, "built: " << os.str());
4127
4128         return os;
4129 }
4130
4131
4132 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4133 {
4134         // LYXERR(Debug::FIND, "parsing");
4135         string s;
4136         string line;
4137         getline(is, line);
4138         while (line != "EOSS") {
4139                 if (! s.empty())
4140                         s = s + "\n";
4141                 s = s + line;
4142                 if (is.eof())   // Tolerate malformed request
4143                         break;
4144                 getline(is, line);
4145         }
4146         // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4147         opt.find_buf_name = from_utf8(s);
4148         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4149         is.get();       // Waste space before replace string
4150         s = "";
4151         getline(is, line);
4152         while (line != "EOSS") {
4153                 if (! s.empty())
4154                         s = s + "\n";
4155                 s = s + line;
4156                 if (is.eof())   // Tolerate malformed request
4157                         break;
4158                 getline(is, line);
4159         }
4160         // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4161         opt.repl_buf_name = from_utf8(s);
4162         is >> opt.keep_case;
4163         int i;
4164         is >> i;
4165         opt.scope = FindAndReplaceOptions::SearchScope(i);
4166         is >> i;
4167         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4168
4169         /*
4170         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4171                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4172                << opt.scope << ' ' << opt.restr);
4173         */
4174         return is;
4175 }
4176
4177 } // namespace lyx