]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
FindAdv: Ignore math hull if searching for normal text
[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|ensuremath)\\{([^\\}]*)\\}", "$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 mathpostfixsize;
1652     size_t mathStart;
1653     size_t mathprefixsize;
1654     size_t mathSize;
1655   };
1656   size_t actualIdx_;
1657   vector<MathEntry> entries_;
1658  public:
1659   MathInfo() {
1660     actualIdx_ = 0;
1661   }
1662   void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1663     MathEntry m = MathEntry();
1664     m.wait = wait;
1665     m.mathStart = start;
1666     m.mathprefixsize = prefixsize;
1667     m.mathEnd = end;
1668     m.mathpostfixsize = postfixsize;
1669     m.mathSize = end - start;
1670     entries_.push_back(m);
1671   }
1672   bool empty() const { return entries_.empty(); };
1673   size_t getEndPos() const {
1674     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1675       return 0;
1676     }
1677     return entries_[actualIdx_].mathEnd;
1678   }
1679   size_t getStartPos() const {
1680     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1681       return 100000;                    /*  definitely enough? */
1682     }
1683     return entries_[actualIdx_].mathStart;
1684   }
1685   size_t getPrefixSize() const {
1686     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1687       return 0;
1688     }
1689     return entries_[actualIdx_].mathprefixsize;
1690   }
1691   size_t getPostfixSize() const {
1692     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1693       return 0;
1694     }
1695     return entries_[actualIdx_].mathpostfixsize;
1696   }
1697   size_t getFirstPos() {
1698     actualIdx_ = 0;
1699     return getStartPos();
1700   }
1701   size_t getSize() const {
1702     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1703       return size_t(0);
1704     }
1705     return entries_[actualIdx_].mathSize;
1706   }
1707   void incrEntry() { actualIdx_++; };
1708 };
1709
1710 void LatexInfo::buildEntries(bool isPatternString)
1711 {
1712   static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1713   static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1714   static bool disableLanguageOverride = false;
1715   smatch sub, submath;
1716   bool evaluatingRegexp = false;
1717   MathInfo mi;
1718   bool evaluatingMath = false;
1719   bool evaluatingCode = false;
1720   size_t codeEnd = 0;
1721   bool evaluatingOptional = false;
1722   size_t optionalEnd = 0;
1723   int codeStart = -1;
1724   KeyInfo found;
1725   bool math_end_waiting = false;
1726   size_t math_pos = 10000;
1727   size_t math_prefix_size = 1;
1728   string math_end;
1729   static vector<string> usedText = vector<string>();
1730   static bool removeMathHull = false;
1731
1732   interval_.removeAccents();
1733
1734   for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1735     submath = *itmath;
1736     if ((submath.position(2) - submath.position(0)) %2 == 1) {
1737       // prefixed by odd count of '\\'
1738       continue;
1739     }
1740     if (math_end_waiting) {
1741       size_t pos = submath.position(size_t(2));
1742       if ((math_end == "$") &&
1743           (submath.str(2) == "$")) {
1744         mi.insert("$", math_pos, 1, pos + 1, 1);
1745         math_end_waiting = false;
1746       }
1747       else if ((math_end == "\\]") &&
1748                (submath.str(2) == "\\]")) {
1749         mi.insert("\\]", math_pos, 2, pos + 2, 2);
1750         math_end_waiting = false;
1751       }
1752       else if ((submath.str(3).compare("end") == 0) &&
1753           (submath.str(4).compare(math_end) == 0)) {
1754         mi.insert(math_end, math_pos, math_prefix_size, pos + submath.str(2).length(), submath.str(2).length());
1755         math_end_waiting = false;
1756       }
1757       else
1758         continue;
1759     }
1760     else {
1761       if (submath.str(3).compare("begin") == 0) {
1762         math_end_waiting = true;
1763         math_end = submath.str(4);
1764         math_pos = submath.position(size_t(2));
1765         math_prefix_size = submath.str(2).length();
1766       }
1767       else if (submath.str(2).compare("\\[") == 0) {
1768         math_end_waiting = true;
1769         math_end = "\\]";
1770         math_pos = submath.position(size_t(2));
1771       }
1772       else if (submath.str(2) == "$") {
1773         size_t pos = submath.position(size_t(2));
1774         math_end_waiting = true;
1775         math_end = "$";
1776         math_pos = pos;
1777       }
1778     }
1779   }
1780   // Ignore language if there is math somewhere in pattern-string
1781   if (isPatternString) {
1782     for (auto s: usedText) {
1783       // Remove entries created in previous search runs
1784       keys.erase(s);
1785     }
1786     usedText = vector<string>();
1787     if (! mi.empty()) {
1788       // Disable language
1789       keys["foreignlanguage"].disabled = true;
1790       disableLanguageOverride = true;
1791       removeMathHull = false;
1792     }
1793     else {
1794       removeMathHull = true;    // used later if not isPatternString
1795       disableLanguageOverride = false;
1796     }
1797   }
1798   else {
1799     if (disableLanguageOverride) {
1800       keys["foreignlanguage"].disabled = true;
1801     }
1802   }
1803   math_pos = mi.getFirstPos();
1804   for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1805     sub = *it;
1806     if ((sub.position(2) - sub.position(0)) %2 == 1) {
1807       // prefixed by odd count of '\\'
1808       continue;
1809     }
1810     string key = sub.str(5);
1811     if (key == "") {
1812       if (sub.str(2)[0] == '\\')
1813         key = sub.str(2)[1];
1814       else {
1815         key = sub.str(2);
1816       }
1817     }
1818     KeysIterator it_key = keys.find(key);
1819     if (it_key != keys.end()) {
1820       if (it_key->second.keytype == KeyInfo::headRemove) {
1821         KeyInfo found1 = it_key->second;
1822         found1.disabled = true;
1823         found1.head = "\\" + key + "{";
1824         found1._tokenstart = sub.position(size_t(2));
1825         found1._tokensize = found1.head.length();
1826         found1._dataStart = found1._tokenstart + found1.head.length();
1827         int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1828         found1._dataEnd = endpos;
1829         removeHead(found1);
1830         continue;
1831       }
1832     }
1833     if (evaluatingRegexp) {
1834       if (sub.str(3).compare("endregexp") == 0) {
1835         evaluatingRegexp = false;
1836         // found._tokenstart already set
1837         found._dataEnd = sub.position(size_t(2)) + 13;
1838         found._dataStart = found._dataEnd;
1839         found._tokensize = found._dataEnd - found._tokenstart;
1840         found.parenthesiscount = 0;
1841         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1842       }
1843       else {
1844         continue;
1845       }
1846     }
1847     else {
1848       if (evaluatingMath) {
1849         if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1850           continue;
1851         evaluatingMath = false;
1852         mi.incrEntry();
1853         math_pos = mi.getStartPos();
1854       }
1855       if (it_key == keys.end()) {
1856         found = KeyInfo(KeyInfo::isStandard, 0, true);
1857         LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1858         found = KeyInfo(KeyInfo::isText, 0, false);
1859         if (isPatternString) {
1860           found.keytype = KeyInfo::isChar;
1861           found.disabled = false;
1862           found.used = true;
1863         }
1864         keys[key] = found;
1865         usedText.push_back(key);
1866       }
1867       else
1868         found = keys[key];
1869       if (key.compare("regexp") == 0) {
1870         evaluatingRegexp = true;
1871         found._tokenstart = sub.position(size_t(2));
1872         found._tokensize = 0;
1873         continue;
1874       }
1875     }
1876     // Handle the other params of key
1877     if (found.keytype == KeyInfo::isIgnored)
1878       continue;
1879     else if (found.keytype == KeyInfo::isMath) {
1880       if (size_t(sub.position(size_t(2))) == math_pos) {
1881         found = keys[key];
1882         found._tokenstart = sub.position(size_t(2));
1883         found._tokensize = mi.getSize();
1884         found._dataEnd = found._tokenstart + found._tokensize;
1885         found._dataStart = found._dataEnd;
1886         found.parenthesiscount = 0;
1887         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1888         if (removeMathHull) {
1889           interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
1890           interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
1891         }
1892         evaluatingMath = true;
1893       }
1894       else {
1895         // begin|end of unknown env, discard
1896         // First handle tables
1897         // longtable|tabular
1898         bool discardComment;
1899         found = keys[key];
1900         found.keytype = KeyInfo::doRemove;
1901         if ((sub.str(7).compare("longtable") == 0) ||
1902             (sub.str(7).compare("tabular") == 0)) {
1903           discardComment = true;        /* '%' */
1904         }
1905         else {
1906           discardComment = false;
1907           static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1908           smatch sub2;
1909           string token = sub.str(7);
1910           if (regex_match(token, sub2, removeArgs)) {
1911             found.keytype = KeyInfo::removeWithArg;
1912           }
1913         }
1914         // discard spaces before pos(2)
1915         int pos = sub.position(size_t(2));
1916         int count;
1917         for (count = 0; pos - count > 0; count++) {
1918           char c = interval_.par[pos-count-1];
1919           if (discardComment) {
1920             if ((c != ' ') && (c != '%'))
1921               break;
1922           }
1923           else if (c != ' ')
1924             break;
1925         }
1926         found._tokenstart = pos - count;
1927         if (sub.str(3).compare(0, 5, "begin") == 0) {
1928           size_t pos1 = pos + sub.str(2).length();
1929           if (sub.str(7).compare("cjk") == 0) {
1930             pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1931             if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1932               pos1 += 2;
1933             found.keytype = KeyInfo::isMain;
1934             found._dataStart = pos1;
1935             found._dataEnd = interval_.par.length();
1936             found.disabled = keys["foreignlanguage"].disabled;
1937             found.used = keys["foreignlanguage"].used;
1938             found._tokensize = pos1 - found._tokenstart;
1939             found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1940           }
1941           else {
1942             // Swallow possible optional params
1943             while (interval_.par[pos1] == '[') {
1944               pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1945             }
1946             // Swallow also the eventual parameter
1947             if (interval_.par[pos1] == '{') {
1948               found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1949             }
1950             else {
1951               found._dataEnd = pos1;
1952             }
1953             found._dataStart = found._dataEnd;
1954             found._tokensize = count + found._dataEnd - pos;
1955             found.parenthesiscount = 0;
1956             found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1957             found.disabled = true;
1958           }
1959         }
1960         else {
1961           // Handle "\end{...}"
1962           found._dataStart = pos + sub.str(2).length();
1963           found._dataEnd = found._dataStart;
1964           found._tokensize = count + found._dataEnd - pos;
1965           found.parenthesiscount = 0;
1966           found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1967           found.disabled = true;
1968         }
1969       }
1970     }
1971     else if (found.keytype != KeyInfo::isRegex) {
1972       found._tokenstart = sub.position(size_t(2));
1973       if (found.parenthesiscount == 0) {
1974         // Probably to be discarded
1975         size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
1976         char following = interval_.par[following_pos];
1977         if (following == ' ')
1978           found.head = "\\" + sub.str(5) + " ";
1979         else if (following == '=') {
1980           // like \uldepth=1000pt
1981           found.head = sub.str(2);
1982         }
1983         else
1984           found.head = "\\" + key;
1985         found._tokensize = found.head.length();
1986         found._dataEnd = found._tokenstart + found._tokensize;
1987         found._dataStart = found._dataEnd;
1988       }
1989       else {
1990         int params = found._tokenstart + key.length() + 1;
1991         if (evaluatingOptional) {
1992           if (size_t(found._tokenstart) > optionalEnd) {
1993             evaluatingOptional = false;
1994           }
1995           else {
1996             found.disabled = true;
1997           }
1998         }
1999         int optend = params;
2000         while (interval_.par[optend] == '[') {
2001           // discard optional parameters
2002           optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2003         }
2004         if (optend > params) {
2005           key += interval_.par.substr(params, optend-params);
2006           evaluatingOptional = true;
2007           optionalEnd = optend;
2008           if (found.keytype == KeyInfo::isSectioning) {
2009             // Remove optional values (but still keep in header)
2010             interval_.addIntervall(params, optend);
2011           }
2012         }
2013         string token = sub.str(7);
2014         int closings;
2015         if (interval_.par[optend] != '{') {
2016           closings = 0;
2017           found.parenthesiscount = 0;
2018           found.head = "\\" + key;
2019         }
2020         else
2021           closings = found.parenthesiscount;
2022         if (found.parenthesiscount == 1) {
2023           found.head = "\\" + key + "{";
2024         }
2025         else if (found.parenthesiscount > 1) {
2026           if (token != "") {
2027             found.head = sub.str(2) + "{";
2028             closings = found.parenthesiscount - 1;
2029           }
2030           else {
2031             found.head = "\\" + key + "{";
2032           }
2033         }
2034         found._tokensize = found.head.length();
2035         found._dataStart = found._tokenstart + found.head.length();
2036         if (found.keytype == KeyInfo::doRemove) {
2037           if (closings > 0) {
2038             size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2039             if (endpar >= interval_.par.length())
2040               found._dataStart = interval_.par.length();
2041             else
2042               found._dataStart = endpar;
2043             found._tokensize = found._dataStart - found._tokenstart;
2044           }
2045           else {
2046             found._dataStart = found._tokenstart + found._tokensize;
2047           }
2048           closings = 0;
2049         }
2050         if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2051           found._dataStart += 15;
2052         }
2053         size_t endpos;
2054         if (closings < 1)
2055           endpos = found._dataStart - 1;
2056         else
2057           endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2058         if (found.keytype == KeyInfo::isList) {
2059           // Check if it really is list env
2060           static regex const listre("^([a-z]+)$");
2061           smatch sub2;
2062           if (!regex_match(token, sub2, listre)) {
2063             // Change the key of this entry. It is not in a list/item environment
2064             found.keytype = KeyInfo::endArguments;
2065           }
2066         }
2067         if (found.keytype == KeyInfo::noMain) {
2068           evaluatingCode = true;
2069           codeEnd = endpos;
2070           codeStart = found._dataStart;
2071         }
2072         else if (evaluatingCode) {
2073           if (size_t(found._dataStart) > codeEnd)
2074             evaluatingCode = false;
2075           else if (found.keytype == KeyInfo::isMain) {
2076             // Disable this key, treate it as standard
2077             found.keytype = KeyInfo::isStandard;
2078             found.disabled = true;
2079             if ((codeEnd +1 >= interval_.par.length()) &&
2080                 (found._tokenstart == codeStart)) {
2081               // trickery, because the code inset starts
2082               // with \selectlanguage ...
2083               codeEnd = endpos;
2084               if (entries_.size() > 1) {
2085                 entries_[entries_.size()-1]._dataEnd = codeEnd;
2086               }
2087             }
2088           }
2089         }
2090         if ((endpos == interval_.par.length()) &&
2091             (found.keytype == KeyInfo::doRemove)) {
2092           // Missing closing => error in latex-input?
2093           // therefore do not delete remaining data
2094           found._dataStart -= 1;
2095           found._dataEnd = found._dataStart;
2096         }
2097         else
2098           found._dataEnd = endpos;
2099       }
2100       if (isPatternString) {
2101         keys[key].used = true;
2102       }
2103     }
2104     entries_.push_back(found);
2105   }
2106 }
2107
2108 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2109 {
2110   stringstream s(keysstring);
2111   string key;
2112   const char delim = '|';
2113   while (getline(s, key, delim)) {
2114     KeyInfo keyII(keyI);
2115     if (isPatternString) {
2116       keyII.used = false;
2117     }
2118     else if ( !keys[key].used)
2119       keyII.disabled = true;
2120     keys[key] = keyII;
2121   }
2122 }
2123
2124 void LatexInfo::buildKeys(bool isPatternString)
2125 {
2126
2127   static bool keysBuilt = false;
2128   if (keysBuilt && !isPatternString) return;
2129
2130   // Keys to ignore in any case
2131   makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2132   // Known standard keys with 1 parameter.
2133   // Split is done, if not at start of region
2134   makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2135   makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2136   makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2137   makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2138   makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2139   makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2140
2141   makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2142           KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2143   makeKey("section*|subsection*|subsubsection*|paragraph*",
2144           KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2145   makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2146   makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2147   // Regex
2148   makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2149
2150   // Split is done, if not at start of region
2151   makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2152   makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2153
2154   // Split is done always.
2155   makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2156
2157   // Known charaters
2158   // No split
2159   makeKey("backslash|textbackslash|slash",  KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2160   makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2161   makeKey("textasciiacute|texemdash",       KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2162   makeKey("dots|ldots",                     KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2163   // Spaces
2164   makeKey("quad|qquad|hfill|dotfill",               KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2165   makeKey("textvisiblespace|nobreakspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2166   makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2167   makeKey("thickspace|medspace|thinspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2168   // Skip
2169   // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2170   // Custom space/skip, remove the content (== length value)
2171   makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2172   // Found in fr/UserGuide.lyx
2173   makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2174   // quotes
2175   makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2176   makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2177   // Known macros to remove (including their parameter)
2178   // No split
2179   makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2180   makeKey("addtocounter|setlength",                 KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2181   // handle like standard keys with 1 parameter.
2182   makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2183
2184   // Ignore deleted text
2185   makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2186   // but preserve added text
2187   makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2188
2189   // Macros to remove, but let the parameter survive
2190   // No split
2191   makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2192
2193   // Remove language spec from content of these insets
2194   makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2195
2196   // Same effect as previous, parameter will survive (because there is no one anyway)
2197   // No split
2198   makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2199   // Remove table decorations
2200   makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2201   // Discard shape-header.
2202   // For footnote or shortcut too, because of lang settings
2203   // and wrong handling if used 'KeyInfo::noMain'
2204   makeKey("circlepar|diamondpar|heartpar|nutpar",  KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2205   makeKey("trianglerightpar|hexagonpar|starpar",   KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2206   makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2207   makeKey("triangleleftpar|shapepar|dropuppar",    KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2208   makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics",     KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2209   makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2210   // like ('tiny{}' or '\tiny ' ... )
2211   makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2212
2213   // Survives, like known character
2214   // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2215   makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2216   makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2217
2218   makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2219   makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2220   makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2221
2222   makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2223   // Remove RTL/LTR marker
2224   makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2225   makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2226   makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2227   makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2228   makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2229   makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2230   makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2231   if (isPatternString) {
2232     // Allow the first searched string to rebuild the keys too
2233     keysBuilt = false;
2234   }
2235   else {
2236     // no need to rebuild again
2237     keysBuilt = true;
2238   }
2239 }
2240
2241 /*
2242  * Keep the list of actual opened parentheses actual
2243  * (e.g. depth == 4 means there are 4 '{' not processed yet)
2244  */
2245 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2246 {
2247   int skip = 0;
2248   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2249     char c;
2250     c = par[i];
2251     skip = 0;
2252     if (c == '\\') skip = 1;
2253     else if (c == '{') {
2254       handleOpenP(i);
2255     }
2256     else if (c == '}') {
2257       handleCloseP(i, closingAllowed);
2258     }
2259   }
2260 }
2261
2262 #if (0)
2263 string Intervall::show(int lastpos)
2264 {
2265   int idx = 0;                          /* int intervalls */
2266   string s;
2267   int i = 0;
2268   for (idx = 0; idx <= ignoreidx; idx++) {
2269     while (i < lastpos) {
2270       int printsize;
2271       if (i <= borders[idx].low) {
2272         if (borders[idx].low > lastpos)
2273           printsize = lastpos - i;
2274         else
2275           printsize = borders[idx].low - i;
2276         s += par.substr(i, printsize);
2277         i += printsize;
2278         if (i >= borders[idx].low)
2279           i = borders[idx].upper;
2280       }
2281       else {
2282         i = borders[idx].upper;
2283         break;
2284       }
2285     }
2286   }
2287   if (lastpos > i) {
2288     s += par.substr(i, lastpos-i);
2289   }
2290   return s;
2291 }
2292 #endif
2293
2294 void Intervall::output(ostringstream &os, int lastpos)
2295 {
2296   // get number of chars to output
2297   int idx = 0;                          /* int intervalls */
2298   int i = 0;
2299   int printed = 0;
2300   string startTitle = titleValue;
2301   for (idx = 0; idx <= ignoreidx; idx++) {
2302     if (i < lastpos) {
2303       if (i <= borders[idx].low) {
2304         int printsize;
2305         if (borders[idx].low > lastpos)
2306           printsize = lastpos - i;
2307         else
2308           printsize = borders[idx].low - i;
2309         if (printsize > 0) {
2310           os << startTitle << par.substr(i, printsize);
2311           i += printsize;
2312           printed += printsize;
2313           startTitle = "";
2314         }
2315         handleParentheses(i, false);
2316         if (i >= borders[idx].low)
2317           i = borders[idx].upper;
2318       }
2319       else {
2320         i = borders[idx].upper;
2321       }
2322     }
2323     else
2324       break;
2325   }
2326   if (lastpos > i) {
2327     os << startTitle << par.substr(i, lastpos-i);
2328     printed += lastpos-i;
2329   }
2330   handleParentheses(lastpos, false);
2331   int startindex;
2332   if (keys["foreignlanguage"].disabled)
2333     startindex = actualdeptindex-langcount;
2334   else
2335     startindex = actualdeptindex;
2336   for (int i = startindex; i > 0; --i) {
2337     os << "}";
2338   }
2339   if (hasTitle && (printed > 0))
2340     os << "}";
2341   if (! isPatternString_)
2342     os << "\n";
2343   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2344 }
2345
2346 void LatexInfo::processRegion(int start, int region_end)
2347 {
2348   while (start < region_end) {          /* Let {[} and {]} survive */
2349     int cnt = interval_.isOpeningPar(start);
2350     if (cnt == 1) {
2351       // Closing is allowed past the region
2352       int closing = interval_.findclosing(start+1, interval_.par.length());
2353       interval_.addIntervall(start, start+1);
2354       interval_.addIntervall(closing, closing+1);
2355     }
2356     else if (cnt == 3)
2357       start += 2;
2358     start = interval_.nextNotIgnored(start+1);
2359   }
2360 }
2361
2362 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2363 {
2364   if (actual.parenthesiscount == 0) {
2365     // "{\tiny{} ...}" ==> "{{} ...}"
2366     interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2367   }
2368   else {
2369     // Remove header hull, that is "\url{abcd}" ==> "abcd"
2370     interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2371     interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2372   }
2373 }
2374
2375 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2376 {
2377   int nextKeyIdx = 0;
2378   switch (actual.keytype)
2379   {
2380     case KeyInfo::isTitle: {
2381       removeHead(actual);
2382       nextKeyIdx = getNextKey();
2383       break;
2384     }
2385     case KeyInfo::cleanToStart: {
2386       actual._dataEnd = actual._dataStart;
2387       nextKeyIdx = getNextKey();
2388       // Search for end of arguments
2389       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2390       if (tmpIdx > 0) {
2391         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2392           entries_[i].disabled = true;
2393         }
2394         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2395       }
2396       while (interval_.par[actual._dataEnd] == ' ')
2397         actual._dataEnd++;
2398       interval_.addIntervall(0, actual._dataEnd+1);
2399       interval_.actualdeptindex = 0;
2400       interval_.depts[0] = actual._dataEnd+1;
2401       interval_.closes[0] = -1;
2402       break;
2403     }
2404     case KeyInfo::isText:
2405       interval_.par[actual._tokenstart] = '#';
2406       //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2407       nextKeyIdx = getNextKey();
2408       break;
2409     case KeyInfo::noContent: {          /* char like "\hspace{2cm}" */
2410       if (actual.disabled)
2411         interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2412       else
2413         interval_.addIntervall(actual._dataStart, actual._dataEnd);
2414     }
2415       // fall through
2416     case KeyInfo::isChar: {
2417       nextKeyIdx = getNextKey();
2418       break;
2419     }
2420     case KeyInfo::isSize: {
2421       if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2422         if (actual.parenthesiscount == 0)
2423           interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2424         else {
2425           interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2426         }
2427         nextKeyIdx = getNextKey();
2428       } else {
2429         // Here _dataStart points to '{', so correct it
2430         actual._dataStart += 1;
2431         actual._tokensize += 1;
2432         actual.parenthesiscount = 1;
2433         if (interval_.par[actual._dataStart] == '}') {
2434           // Determine the end if used like '{\tiny{}...}'
2435           actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2436           interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2437         }
2438         else {
2439           // Determine the end if used like '\tiny{...}'
2440           actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2441         }
2442         // Split on this key if not at start
2443         int start = interval_.nextNotIgnored(previousStart);
2444         if (start < actual._tokenstart) {
2445           interval_.output(os, actual._tokenstart);
2446           interval_.addIntervall(start, actual._tokenstart);
2447         }
2448         // discard entry if at end of actual
2449         nextKeyIdx = process(os, actual);
2450       }
2451       break;
2452     }
2453     case KeyInfo::endArguments: {
2454       // Remove trailing '{}' too
2455       actual._dataStart += 1;
2456       actual._dataEnd += 1;
2457       interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2458       nextKeyIdx = getNextKey();
2459       break;
2460     }
2461     case KeyInfo::noMain:
2462       // fall through
2463     case KeyInfo::isStandard: {
2464       if (actual.disabled) {
2465         removeHead(actual);
2466         processRegion(actual._dataStart, actual._dataStart+1);
2467         nextKeyIdx = getNextKey();
2468       } else {
2469         // Split on this key if not at datastart of calling entry
2470         int start = interval_.nextNotIgnored(previousStart);
2471         if (start < actual._tokenstart) {
2472           interval_.output(os, actual._tokenstart);
2473           interval_.addIntervall(start, actual._tokenstart);
2474         }
2475         // discard entry if at end of actual
2476         nextKeyIdx = process(os, actual);
2477       }
2478       break;
2479     }
2480     case KeyInfo::removeWithArg: {
2481       nextKeyIdx = getNextKey();
2482       // Search for end of arguments
2483       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2484       if (tmpIdx > 0) {
2485         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2486           entries_[i].disabled = true;
2487         }
2488         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2489       }
2490       interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2491       break;
2492     }
2493     case KeyInfo::doRemove: {
2494       // Remove the key with all parameters and following spaces
2495       size_t pos;
2496       size_t start;
2497       if (interval_.par[actual._dataEnd-1] == ' ')
2498         start = actual._dataEnd;
2499       else
2500         start = actual._dataEnd+1;
2501       for (pos = start; pos < interval_.par.length(); pos++) {
2502         if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2503           break;
2504       }
2505       // Remove also enclosing parentheses [] and {}
2506       int numpars = 0;
2507       int spaces = 0;
2508       while (actual._tokenstart > numpars) {
2509         if (pos+numpars >= interval_.par.size())
2510           break;
2511         else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2512           numpars++;
2513         else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2514           numpars++;
2515         else
2516           break;
2517       }
2518       if (numpars > 0) {
2519         if (interval_.par[pos+numpars] == ' ')
2520           spaces++;
2521       }
2522
2523       interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2524       nextKeyIdx = getNextKey();
2525       break;
2526     }
2527     case KeyInfo::isList: {
2528       // Discard space before _tokenstart
2529       int count;
2530       for (count = 0; count < actual._tokenstart; count++) {
2531         if (interval_.par[actual._tokenstart-count-1] != ' ')
2532           break;
2533       }
2534       nextKeyIdx = getNextKey();
2535       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2536       if (tmpIdx > 0) {
2537         // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2538         // with arguments
2539         // How else can we catch this one?
2540         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2541           entries_[i].disabled = true;
2542         }
2543         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2544       }
2545       else if (nextKeyIdx > 0) {
2546         // Ignore any lang entries inside data region
2547         for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2548           if (entries_[i].keytype == KeyInfo::isMain)
2549             entries_[i].disabled = true;
2550         }
2551       }
2552       if (actual.disabled) {
2553         interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2554       }
2555       else {
2556         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2557       }
2558       if (interval_.par[actual._dataEnd+1] == '[') {
2559         int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2560         if ((interval_.par[actual._dataEnd+2] == '{') &&
2561             (interval_.par[posdown-1] == '}')) {
2562           interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2563           interval_.addIntervall(posdown-1, posdown+1);
2564         }
2565         else {
2566           interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2567           interval_.addIntervall(posdown, posdown+1);
2568         }
2569         int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2570         if (blk > posdown) {
2571           // Discard at most 1 space after empty item
2572           int count;
2573           for (count = 0; count < 1; count++) {
2574             if (interval_.par[blk+count] != ' ')
2575               break;
2576           }
2577           if (count > 0)
2578             interval_.addIntervall(blk, blk+count);
2579         }
2580       }
2581       break;
2582     }
2583     case KeyInfo::isSectioning: {
2584       // Discard spaces before _tokenstart
2585       int count;
2586       int val = actual._tokenstart;
2587       for (count = 0; count < actual._tokenstart;) {
2588         val = interval_.previousNotIgnored(val-1);
2589         if (val < 0 || interval_.par[val] != ' ')
2590           break;
2591         else {
2592           count = actual._tokenstart - val;
2593         }
2594       }
2595       if (actual.disabled) {
2596         removeHead(actual, count);
2597         nextKeyIdx = getNextKey();
2598       } else {
2599         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2600         nextKeyIdx = process(os, actual);
2601       }
2602       break;
2603     }
2604     case KeyInfo::isMath: {
2605       // Same as regex, use the content unchanged
2606       nextKeyIdx = getNextKey();
2607       break;
2608     }
2609     case KeyInfo::isRegex: {
2610       // DO NOT SPLIT ON REGEX
2611       // Do not disable
2612       nextKeyIdx = getNextKey();
2613       break;
2614     }
2615     case KeyInfo::isIgnored: {
2616       // Treat like a character for now
2617       nextKeyIdx = getNextKey();
2618       break;
2619     }
2620     case KeyInfo::isMain: {
2621       if (interval_.par.substr(actual._dataStart, 2) == "% ")
2622         interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2623       if (actual._tokenstart > 0) {
2624         int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2625         if ((prev >= 0) && interval_.par[prev] == '%')
2626           interval_.addIntervall(prev, prev+1);
2627       }
2628       if (actual.disabled) {
2629         removeHead(actual);
2630         interval_.langcount++;
2631         if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2632             (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2633           // Discard also the space before math-equation
2634           interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2635         }
2636         nextKeyIdx = getNextKey();
2637         // interval.resetOpenedP(actual._dataStart-1);
2638       }
2639       else {
2640         if (actual._tokenstart < 26) {
2641           // for the first (and maybe dummy) language
2642           interval_.setForDefaultLang(actual);
2643         }
2644         interval_.resetOpenedP(actual._dataStart-1);
2645       }
2646       break;
2647     }
2648     case KeyInfo::invalid:
2649     case KeyInfo::headRemove:
2650       // These two cases cannot happen, already handled
2651       // fall through
2652     default: {
2653       // LYXERR(Debug::INFO, "Unhandled keytype");
2654       nextKeyIdx = getNextKey();
2655       break;
2656     }
2657   }
2658   return nextKeyIdx;
2659 }
2660
2661 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2662 {
2663   int end = interval_.nextNotIgnored(actual._dataEnd);
2664   int oldStart = actual._dataStart;
2665   int nextKeyIdx = getNextKey();
2666   while (true) {
2667     if ((nextKeyIdx < 0) ||
2668         (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2669         (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2670       if (oldStart <= end) {
2671         processRegion(oldStart, end);
2672         oldStart = end+1;
2673       }
2674       break;
2675     }
2676     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2677
2678     if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2679       (void) dispatch(os, actual._dataStart, nextKey);
2680       end = nextKey._tokenstart;
2681       break;
2682     }
2683     processRegion(oldStart, nextKey._tokenstart);
2684     nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2685
2686     oldStart = nextKey._dataEnd+1;
2687   }
2688   // now nextKey is either invalid or is outside of actual._dataEnd
2689   // output the remaining and discard myself
2690   if (oldStart <= end) {
2691     processRegion(oldStart, end);
2692   }
2693   if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2694     end += 1;
2695     // This is the normal case.
2696     // But if using the firstlanguage, the closing may be missing
2697   }
2698   // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2699   int output_end;
2700   if (actual._dataEnd < end)
2701     output_end = interval_.nextNotIgnored(actual._dataEnd);
2702   else if (interval_.par.size() > (size_t) end)
2703     output_end = interval_.nextNotIgnored(end);
2704   else
2705     output_end = interval_.par.size();
2706   if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2707     interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2708   }
2709   // Remove possible empty data
2710   int dstart = interval_.nextNotIgnored(actual._dataStart);
2711   while (interval_.isOpeningPar(dstart) == 1) {
2712     interval_.addIntervall(dstart, dstart+1);
2713     int dend = interval_.findclosing(dstart+1, output_end);
2714     interval_.addIntervall(dend, dend+1);
2715     dstart = interval_.nextNotIgnored(dstart+1);
2716   }
2717   if (dstart < output_end)
2718     interval_.output(os, output_end);
2719   if (nextKeyIdx < 0)
2720     interval_.addIntervall(0, end);
2721   else
2722     interval_.addIntervall(actual._tokenstart, end);
2723   return nextKeyIdx;
2724 }
2725
2726 string splitOnKnownMacros(string par, bool isPatternString)
2727 {
2728   ostringstream os;
2729   LatexInfo li(par, isPatternString);
2730   // LYXERR(Debug::INFO, "Berfore split: " << par);
2731   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2732   DummyKey.head = "";
2733   DummyKey._tokensize = 0;
2734   DummyKey._dataStart = 0;
2735   DummyKey._dataEnd = par.length();
2736   DummyKey.disabled = true;
2737   int firstkeyIdx = li.getFirstKey();
2738   string s;
2739   if (firstkeyIdx >= 0) {
2740     KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2741     DummyKey._tokenstart = firstKey._tokenstart;
2742     int nextkeyIdx;
2743     if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2744       // Use dummy firstKey
2745       firstKey = DummyKey;
2746       (void) li.setNextKey(firstkeyIdx);
2747     }
2748     else {
2749       if (par.substr(firstKey._dataStart, 2) == "% ")
2750         li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2751     }
2752     nextkeyIdx = li.process(os, firstKey);
2753     while (nextkeyIdx >= 0) {
2754       // Check for a possible gap between the last
2755       // entry and this one
2756       int datastart = li.nextNotIgnored(firstKey._dataStart);
2757       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2758       if ((nextKey._tokenstart > datastart)) {
2759         // Handle the gap
2760         firstKey._dataStart = datastart;
2761         firstKey._dataEnd = par.length();
2762         (void) li.setNextKey(nextkeyIdx);
2763         // Fake the last opened parenthesis
2764         li.setForDefaultLang(firstKey);
2765         nextkeyIdx = li.process(os, firstKey);
2766       }
2767       else {
2768         if (nextKey.keytype != KeyInfo::isMain) {
2769           firstKey._dataStart = datastart;
2770           firstKey._dataEnd = nextKey._dataEnd+1;
2771           (void) li.setNextKey(nextkeyIdx);
2772           li.setForDefaultLang(firstKey);
2773           nextkeyIdx = li.process(os, firstKey);
2774         }
2775         else {
2776           nextkeyIdx = li.process(os, nextKey);
2777         }
2778       }
2779     }
2780     // Handle the remaining
2781     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2782     firstKey._dataEnd = par.length();
2783     // Check if ! empty
2784     if ((firstKey._dataStart < firstKey._dataEnd) &&
2785         (par[firstKey._dataStart] != '}')) {
2786       li.setForDefaultLang(firstKey);
2787       (void) li.process(os, firstKey);
2788     }
2789     s = os.str();
2790     if (s.empty()) {
2791       // return string definitelly impossible to match
2792       s = "\\foreignlanguage{ignore}{ }";
2793     }
2794   }
2795   else
2796     s = par;                            /* no known macros found */
2797   // LYXERR(Debug::INFO, "After split: " << s);
2798   return s;
2799 }
2800
2801 /*
2802  * Try to unify the language specs in the latexified text.
2803  * Resulting modified string is set to "", if
2804  * the searched tex does not contain all the features in the search pattern
2805  */
2806 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2807 {
2808         static Features regex_f;
2809         static int missed = 0;
2810         static bool regex_with_format = false;
2811
2812         int parlen = par.length();
2813
2814         while ((parlen > 0) && (par[parlen-1] == '\n')) {
2815                 parlen--;
2816         }
2817         if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2818                 // Happens to be there in case of description or labeling environment
2819                 parlen--;
2820         }
2821         string result;
2822         if (withformat) {
2823                 // Split the latex input into pieces which
2824                 // can be digested by our search engine
2825                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2826                 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2827                         // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2828                         string doclang = pbuf->params().language->polyglossia();
2829                         static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2830                         smatch sub;
2831                         bool toIgnoreLang = true;
2832                         for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2833                                 sub = *it;
2834                                 if (sub.str(2) != doclang) {
2835                                         toIgnoreLang = false;
2836                                         break;
2837                                 }
2838                         }
2839                         setIgnoreFormat("language", toIgnoreLang);
2840
2841                 }
2842                 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2843                 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2844         }
2845         else
2846                 result = par.substr(0, parlen);
2847         if (isPatternString) {
2848                 missed = 0;
2849                 if (withformat) {
2850                         regex_f = identifyFeatures(result);
2851                         string features = "";
2852                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2853                                 string a = it->first;
2854                                 regex_with_format = true;
2855                                 features += " " + a;
2856                                 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2857                         }
2858                         LYXERR(Debug::FIND, "Identified Features" << features);
2859
2860                 }
2861         } else if (regex_with_format) {
2862                 Features info = identifyFeatures(result);
2863                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2864                         string a = it->first;
2865                         bool b = it->second;
2866                         if (b && ! info[a]) {
2867                                 missed++;
2868                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2869                                 return "";
2870                         }
2871                 }
2872
2873         }
2874         else {
2875                 // LYXERR(Debug::INFO, "No regex formats");
2876         }
2877         return result;
2878 }
2879
2880
2881 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2882 static int identifyClosing(string & t)
2883 {
2884         int open_braces = 0;
2885         do {
2886                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2887                 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2888                         continue;
2889                 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2890                         continue;
2891                 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2892                         continue;
2893                 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2894                         ++open_braces;
2895                         continue;
2896                 }
2897                 break;
2898         } while (true);
2899         return open_braces;
2900 }
2901
2902 static int num_replaced = 0;
2903 static bool previous_single_replace = true;
2904
2905 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2906 {
2907 #if QTSEARCH
2908         // Handle \w properly
2909         QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2910         if (! opt.casesensitive) {
2911                 popts |= QRegularExpression::CaseInsensitiveOption;
2912         }
2913         regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2914         regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2915         regexError = "";
2916         if (regexp.isValid() && regexp2.isValid()) {
2917                 regexIsValid = true;
2918                 // Check '{', '}' pairs inside the regex
2919                 int balanced = 0;
2920                 int skip = 1;
2921                 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2922                         char c = par_as_string[i];
2923                         if (c == '\\') {
2924                                 skip = 2;
2925                                 continue;
2926                         }
2927                         if (c == '{')
2928                                 balanced++;
2929                         else if (c == '}') {
2930                                 balanced--;
2931                                 if (balanced < 0)
2932                                         break;
2933                                 }
2934                                 skip = 1;
2935                         }
2936                 if (balanced != 0) {
2937                         regexIsValid = false;
2938                         regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2939                 }
2940         }
2941         else {
2942                 regexIsValid = false;
2943                 if (!regexp.isValid())
2944                         regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2945                 else
2946                         regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2947         }
2948 #else
2949         if (opt.casesensitive) {
2950                 regexp = regex(regexp_str);
2951                 regexp2 = regex(regexp2_str);
2952         }
2953         else {
2954                 regexp = regex(regexp_str, std::regex_constants::icase);
2955                 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2956         }
2957 #endif
2958 }
2959
2960 static void modifyRegexForMatchWord(string &t)
2961 {
2962         string s("");
2963         regex wordre("(\\\\)*((\\.|\\\\b))");
2964         size_t lastpos = 0;
2965         smatch sub;
2966         for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
2967                 sub = *it;
2968                 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
2969                         continue;
2970                 }
2971                 else if (sub.str(2) == "\\\\b")
2972                         return;
2973                 if (lastpos < (size_t) sub.position(2))
2974                         s += t.substr(lastpos, sub.position(2) - lastpos);
2975                 s += "\\S";
2976                 lastpos = sub.position(2) + sub.length(2);
2977         }
2978         if (lastpos == 0) {
2979                 s = "\\b" + t + "\\b";
2980                 t = s;
2981                 return;
2982         }
2983         else if (lastpos < t.length())
2984                 s += t.substr(lastpos, t.length() - lastpos);
2985       t = "\\b" + s + "\\b";
2986 }
2987
2988 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
2989         : p_buf(&buf), p_first_buf(&buf), opt(opt)
2990 {
2991         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2992         docstring const & ds = stringifySearchBuffer(find_buf, opt);
2993         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2994         if (opt.replace_all && previous_single_replace) {
2995                 previous_single_replace = false;
2996                 num_replaced = 0;
2997         }
2998         else if (!opt.replace_all) {
2999                 num_replaced = 0;       // count number of replaced strings
3000                 previous_single_replace = true;
3001         }
3002         // When using regexp, braces are hacked already by escape_for_regex()
3003         par_as_string = normalize(ds);
3004         open_braces = 0;
3005         close_wildcards = 0;
3006
3007         size_t lead_size = 0;
3008         // correct the language settings
3009         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3010         opt.matchAtStart = false;
3011         if (!use_regexp) {
3012                 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3013                 if (opt.ignoreformat) {
3014                         lead_size = 0;
3015                 }
3016                 else {
3017                         lead_size = identifyLeading(par_as_string);
3018                 }
3019                 lead_as_string = par_as_string.substr(0, lead_size);
3020                 string lead_as_regex_string = string2regex(lead_as_string);
3021                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3022                 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3023                 /* Handle whole words too in this case
3024                 */
3025                 if (opt.matchword) {
3026                         par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3027                         opt.matchword = false;
3028                 }
3029                 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3030                 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3031                 CreateRegexp(opt, regexp_str, regexp2_str);
3032                 use_regexp = true;
3033                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3034                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3035                 return;
3036         }
3037
3038         if (!opt.ignoreformat) {
3039                 lead_size = identifyLeading(par_as_string);
3040                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3041                 lead_as_string = par_as_string.substr(0, lead_size);
3042                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3043         }
3044
3045         // Here we are using regexp
3046         LASSERT(use_regexp, /**/);
3047         {
3048                 string lead_as_regexp;
3049                 if (lead_size > 0) {
3050                         lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3051                         regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3052                         par_as_string = par_as_string_nolead;
3053                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3054                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3055                 }
3056                 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3057                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3058                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3059                 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3060                 ++close_wildcards;
3061                 size_t lng = par_as_string.size();
3062                 if (!opt.ignoreformat) {
3063                         // Remove extra '\}' at end if not part of \{\.\}
3064                         while(lng > 2) {
3065                                 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3066                                         if (lng >= 6) {
3067                                                 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3068                                                         break;
3069                                         }
3070                                         lng -= 2;
3071                                         open_braces++;
3072                                 }
3073                                 else
3074                                         break;
3075                         }
3076                         if (lng < par_as_string.size())
3077                                 par_as_string = par_as_string.substr(0,lng);
3078                 }
3079                 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3080                 if ((lng > 0) && (par_as_string[0] == '^')) {
3081                         par_as_string = par_as_string.substr(1);
3082                         --lng;
3083                         opt.matchAtStart = true;
3084                 }
3085                 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3086                 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3087                 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3088
3089                 // If entered regexp must match at begin of searched string buffer
3090                 // Kornel: Added parentheses to use $1 for size of the leading string
3091                 string regexp_str;
3092                 string regexp2_str;
3093                 {
3094                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3095                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
3096                         // so the convert has no effect in that case
3097                         for (int i = 7; i > 0; --i) {
3098                                 string orig = "\\\\" + std::to_string(i);
3099                                 string dest = "\\" + std::to_string(i+2);
3100                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
3101                         }
3102                         if (opt.matchword) {
3103                                 modifyRegexForMatchWord(par_as_string);
3104                                 opt.matchword = false;
3105                         }
3106                         regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3107                         regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3108                 }
3109                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3110                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3111                 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3112         }
3113 }
3114
3115 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3116 {
3117         MatchResult mres;
3118
3119         mres.searched_size = len;
3120         if (at_begin &&
3121                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3122                 return mres;
3123
3124         docstring docstr = stringifyFromForSearch(opt, cur, len);
3125         string str;
3126         str = normalize(docstr);
3127         if (!opt.ignoreformat) {
3128                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3129                 // remove closing '}' and '\n' to allow for use of '$' in regex
3130                 size_t lng = str.size();
3131                 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3132                         lng--;
3133                 if (lng != str.size()) {
3134                         str = str.substr(0, lng);
3135                 }
3136         }
3137         if (str.empty()) {
3138                 mres.match_len = -1;
3139                 return mres;
3140         }
3141         LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3142
3143         LASSERT(use_regexp, /**/);
3144         {
3145                 // use_regexp always true
3146                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3147 #if QTSEARCH
3148                 QString qstr = QString::fromStdString(str);
3149                 QRegularExpression const *p_regexp;
3150                 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3151                 if (at_begin) {
3152                         p_regexp = &regexp;
3153                 } else {
3154                         p_regexp = &regexp2;
3155                 }
3156                 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3157                 if (!match.hasMatch())
3158                         return mres;
3159 #else
3160                 regex const *p_regexp;
3161                 regex_constants::match_flag_type flags;
3162                 if (at_begin) {
3163                         flags = regex_constants::match_continuous;
3164                         p_regexp = &regexp;
3165                 } else {
3166                         flags = regex_constants::match_default;
3167                         p_regexp = &regexp2;
3168                 }
3169                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3170                 if (re_it == sregex_iterator())
3171                         return mres;
3172                 match_results<string::const_iterator> const & m = *re_it;
3173 #endif
3174                 // Whole found string, including the leading
3175                 // std: m[0].second - m[0].first
3176                 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3177                 //
3178                 // Size of the leading string
3179                 // std: m[1].second - m[1].first
3180                 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3181                 int leadingsize = 0;
3182 #if QTSEARCH
3183                 if (match.lastCapturedIndex() > 0) {
3184                         leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3185                 }
3186
3187 #else
3188                 if (m.size() > 2) {
3189                         leadingsize = m[1].second - m[1].first;
3190                 }
3191 #endif
3192 #if QTSEARCH
3193                 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3194                 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3195                 // because of different number of closing at end of string
3196                 // we have to 'unify' the length of the post-match.
3197                 // Done by ignoring closing parenthesis and linefeeds at string end
3198                 int matchend = match.capturedEnd(0);
3199                 size_t strsize = qstr.size();
3200                 if (!opt.ignoreformat) {
3201                         while (mres.match_len > 0) {
3202                                 QChar c = qstr.at(matchend - 1);
3203                                 if ((c == '\n') || (c == '}') || (c == '{')) {
3204                                         mres.match_len--;
3205                                         matchend--;
3206                                 }
3207                                 else
3208                                         break;
3209                         }
3210                         while (strsize > (size_t) match.capturedEnd(0)) {
3211                                 QChar c = qstr.at(strsize-1);
3212                                 if ((c == '\n') || (c == '}')) {
3213                                         --strsize;
3214                                 }
3215                                 else
3216                                         break;
3217                         }
3218                 }
3219                 // LYXERR0(qstr.toStdString());
3220                 mres.match2end = strsize - matchend;
3221                 mres.pos = match.capturedStart(2);
3222 #else
3223                 mres.match_prefix = m[2].second - m[2].first;
3224                 mres.match_len = m[0].second - m[2].second;
3225                 // ignore closing parenthesis and linefeeds at string end
3226                 size_t strend = m[0].second - m[0].first;
3227                 int matchend = strend;
3228                 size_t strsize = str.size();
3229                 if (!opt.ignoreformat) {
3230                         while (mres.match_len > 0) {
3231                                 char c = str.at(matchend - 1);
3232                                 if ((c == '\n') || (c == '}') || (c == '{')) {
3233                                         mres.match_len--;
3234                                         matchend--;
3235                                 }
3236                                 else
3237                                         break;
3238                         }
3239                         while (strsize > strend) {
3240                                 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3241                                         --strsize;
3242                                 }
3243                                 else
3244                                         break;
3245                         }
3246                 }
3247                 // LYXERR0(str);
3248                 mres.match2end = strsize - matchend;
3249                 mres.pos = m[2].first - m[0].first;;
3250 #endif
3251                 if (mres.match2end < 0)
3252                   mres.match_len = 0;
3253                 mres.leadsize = leadingsize;
3254 #if QTSEARCH
3255                 if (mres.match_len > 0) {
3256                   string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3257                   mres.result.push_back(a0);
3258                   for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3259                     mres.result.push_back(match.captured(i).toStdString());
3260                   }
3261                 }
3262 #else
3263                 if (mres.match_len > 0) {
3264                   string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3265                   mres.result.push_back(a0);
3266                   for (size_t i = 3; i < m.size(); i++) {
3267                     mres.result.push_back(m[i]);
3268                   }
3269                 }
3270 #endif
3271                 return mres;
3272         }
3273 }
3274
3275
3276 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3277 {
3278         MatchResult mres = findAux(cur, len, at_begin);
3279         int res = mres.match_len;
3280         LYXERR(Debug::FIND,
3281                "res=" << res << ", at_begin=" << at_begin
3282                << ", matchAtStart=" << opt.matchAtStart
3283                << ", inTexted=" << cur.inTexted());
3284         if (opt.matchAtStart) {
3285                 if (cur.pos() != 0)
3286                         mres.match_len = 0;
3287                 else if (mres.match_prefix > 0)
3288                         mres.match_len = 0;
3289                 return mres;
3290         }
3291         else
3292                 return mres;
3293 }
3294
3295 #if 0
3296 static bool simple_replace(string &t, string from, string to)
3297 {
3298   regex repl("(\\\\)*(" + from + ")");
3299   string s("");
3300   size_t lastpos = 0;
3301   smatch sub;
3302   for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3303     sub = *it;
3304     if ((sub.position(2) - sub.position(0)) % 2 == 1)
3305       continue;
3306     if (lastpos < (size_t) sub.position(2))
3307       s += t.substr(lastpos, sub.position(2) - lastpos);
3308     s += to;
3309     lastpos = sub.position(2) + sub.length(2);
3310   }
3311   if (lastpos == 0)
3312     return false;
3313   else if (lastpos < t.length())
3314     s += t.substr(lastpos, t.length() - lastpos);
3315   t = s;
3316   return true;
3317 }
3318 #endif
3319
3320 string MatchStringAdv::normalize(docstring const & s) const
3321 {
3322         string t;
3323         t = lyx::to_utf8(s);
3324         // Remove \n at begin
3325         while (!t.empty() && t[0] == '\n')
3326                 t = t.substr(1);
3327         // Remove \n at end
3328         while (!t.empty() && t[t.size() - 1] == '\n')
3329                 t = t.substr(0, t.size() - 1);
3330         size_t pos;
3331         // Handle all other '\n'
3332         while ((pos = t.find("\n")) != string::npos) {
3333                 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3334                         // Handle '\\\n'
3335                         if (isAlnumASCII(t[pos+1])) {
3336                                 t.replace(pos-2, 3, " ");
3337                         }
3338                         else {
3339                                 t.replace(pos-2, 3, "");
3340                         }
3341                 }
3342                 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3343                         // '\n' adjacent to non-alpha-numerics, discard
3344                         t.replace(pos, 1, "");
3345                 }
3346                 else {
3347                         // Replace all other \n with spaces
3348                         t.replace(pos, 1, " ");
3349                 }
3350         }
3351         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3352         // Kornel: Added textsl, textsf, textit, texttt and noun
3353         // + allow to seach for colored text too
3354         LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3355         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3356                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3357         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3358                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3359         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3360
3361         return t;
3362 }
3363
3364
3365 docstring stringifyFromCursor(DocIterator const & cur, int len)
3366 {
3367         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3368         if (cur.inTexted()) {
3369                 Paragraph const & par = cur.paragraph();
3370                 // TODO what about searching beyond/across paragraph breaks ?
3371                 // TODO Try adding a AS_STR_INSERTS as last arg
3372                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3373                         int(par.size()) : cur.pos() + len;
3374                 // OutputParams runparams(&cur.buffer()->params().encoding());
3375                 OutputParams runparams(encodings.fromLyXName("utf8"));
3376                 runparams.nice = true;
3377                 runparams.flavor = Flavor::XeTeX;
3378                 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3379                 // No side effect of file copying and image conversion
3380                 runparams.dryrun = true;
3381                 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3382                 if (ignoreFormats.getDeleted()) {
3383                         option |= AS_STR_SKIPDELETE;
3384                         runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3385                 }
3386                 else {
3387                         runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3388                 }
3389                 LYXERR(Debug::FIND, "Stringifying with cur: "
3390                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
3391                 return par.asString(cur.pos(), end,
3392                         option,
3393                         &runparams);
3394         } else if (cur.inMathed()) {
3395                 CursorSlice cs = cur.top();
3396                 MathData md = cs.cell();
3397                 MathData::const_iterator it_end =
3398                         (( len == -1 || cs.pos() + len > int(md.size()))
3399                          ? md.end()
3400                          : md.begin() + cs.pos() + len );
3401                 MathData md2;
3402                 for (MathData::const_iterator it = md.begin() + cs.pos();
3403                      it != it_end; ++it)
3404                         md2.push_back(*it);
3405                 docstring s = asString(md2);
3406                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3407                 return s;
3408         }
3409         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3410         return docstring();
3411 }
3412
3413
3414 /** Computes the LaTeX export of buf starting from cur and ending len positions
3415  * after cur, if len is positive, or at the paragraph or innermost inset end
3416  * if len is -1.
3417  */
3418 docstring latexifyFromCursor(DocIterator const & cur, int len)
3419 {
3420         /*
3421         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3422         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3423                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3424         */
3425         Buffer const & buf = *cur.buffer();
3426
3427         odocstringstream ods;
3428         otexstream os(ods);
3429         //OutputParams runparams(&buf.params().encoding());
3430         OutputParams runparams(encodings.fromLyXName("utf8"));
3431         runparams.nice = false;
3432         runparams.flavor = Flavor::XeTeX;
3433         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3434         // No side effect of file copying and image conversion
3435         runparams.dryrun = true;
3436         if (ignoreFormats.getDeleted()) {
3437                 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3438         }
3439         else {
3440                 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3441         }
3442
3443         if (cur.inTexted()) {
3444                 // @TODO what about searching beyond/across paragraph breaks ?
3445                 pos_type endpos = cur.paragraph().size();
3446                 if (len != -1 && endpos > cur.pos() + len)
3447                         endpos = cur.pos() + len;
3448                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3449                           string(), cur.pos(), endpos);
3450                 string s = lyx::to_utf8(ods.str());
3451                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3452                 return(lyx::from_utf8(s));
3453         } else if (cur.inMathed()) {
3454                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3455                 for (int s = cur.depth() - 1; s >= 0; --s) {
3456                         CursorSlice const & cs = cur[s];
3457                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3458                                 TeXMathStream ws(os);
3459                                 cs.asInsetMath()->asHullInset()->header_write(ws);
3460                                 break;
3461                         }
3462                 }
3463
3464                 CursorSlice const & cs = cur.top();
3465                 MathData md = cs.cell();
3466                 MathData::const_iterator it_end =
3467                         ((len == -1 || cs.pos() + len > int(md.size()))
3468                          ? md.end()
3469                          : md.begin() + cs.pos() + len);
3470                 MathData md2;
3471                 for (MathData::const_iterator it = md.begin() + cs.pos();
3472                      it != it_end; ++it)
3473                         md2.push_back(*it);
3474
3475                 ods << asString(md2);
3476                 // Retrieve the math environment type, and add '$' or '$]'
3477                 // or others (\end{equation}) accordingly
3478                 for (int s = cur.depth() - 1; s >= 0; --s) {
3479                         CursorSlice const & cs2 = cur[s];
3480                         InsetMath * inset = cs2.asInsetMath();
3481                         if (inset && inset->asHullInset()) {
3482                                 TeXMathStream ws(os);
3483                                 inset->asHullInset()->footer_write(ws);
3484                                 break;
3485                         }
3486                 }
3487                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3488         } else {
3489                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3490         }
3491         return ods.str();
3492 }
3493
3494 #if defined(ResultsDebug)
3495 // Debugging output
3496 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3497 {
3498         LYXERR0( "from:\t\t\t" << from);
3499         string status;
3500         if (mres.pos_len > 0) {
3501                 // Set in finalize
3502                 status = "FINALSEARCH";
3503         }
3504         else {
3505                 if (mres.match_len > 0) {
3506                         if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3507                                 status = "Good Match";
3508                         else
3509                                 status = "Matched in";
3510                 }
3511                 else
3512                         status = "MissedSearch";
3513         }
3514
3515         LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3516         if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3517                 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3518         if ((mres.pos > 0) || (mres.match_prefix > 0))
3519                 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3520         for (size_t i = 0; i < mres.result.size(); i++)
3521                 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3522 }
3523         #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3524 #else
3525         #define displayMres(s, txt, cur)
3526 #endif
3527
3528 /** Finalize an advanced find operation, advancing the cursor to the innermost
3529  ** position that matches, plus computing the length of the matching text to
3530  ** be selected
3531  ** Return the cur.pos() difference between start and end of found match
3532  **/
3533 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3534 {
3535         // Search the foremost position that matches (avoids find of entire math
3536         // inset when match at start of it)
3537         DocIterator old_cur(cur.buffer());
3538         MatchResult mres;
3539         static MatchResult fail = MatchResult();
3540         MatchResult max_match;
3541         // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3542         // Happens with e.g. hyperlinks
3543         // either one sees "http://www.bla.bla" or nothing
3544         // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3545         // and although we search for only 3 chars, we find the whole hyperlink inset
3546         bool at_begin = (expected.match_prefix == 0);
3547         if (!match.opt.forward && match.opt.ignoreformat) {
3548                 if (expected.pos > 0)
3549                         return fail;
3550         }
3551         LASSERT(at_begin, /**/);
3552         if (expected.match_len > 0 && at_begin) {
3553                 // Search for deepest match
3554                 old_cur = cur;
3555                 max_match = expected;
3556                 do {
3557                         size_t d = cur.depth();
3558                         cur.forwardPos();
3559                         if (!cur)
3560                                 break;
3561                         if (cur.depth() < d)
3562                                 break;
3563                         if (cur.depth() == d)
3564                                 break;
3565                         size_t lastd = d;
3566                         while (cur && cur.depth() > lastd) {
3567                                 lastd = cur.depth();
3568                                 mres = match(cur, -1, at_begin);
3569                                 displayMres(mres, "Checking innermost", cur);
3570                                 if (mres.match_len > 0)
3571                                         break;
3572                                 // maybe deeper?
3573                                 cur.forwardPos();
3574                         }
3575                         if (mres.match_len < expected.match_len)
3576                                 break;
3577                         max_match = mres;
3578                         old_cur = cur;;
3579                 } while(1);
3580                 cur = old_cur;
3581         }
3582         else {
3583                 // (expected.match_len <= 0)
3584                 mres = match(cur);      /* match valid only if not searching whole words */
3585                 displayMres(mres, "Start with negative match", cur);
3586                 max_match = mres;
3587         }
3588         if (max_match.match_len <= 0) return fail;
3589         LYXERR(Debug::FIND, "Ok");
3590
3591         // Compute the match length
3592         int len = 1;
3593         if (cur.pos() + len > cur.lastpos())
3594           return fail;
3595
3596         LASSERT(match.use_regexp, /**/);
3597         {
3598           int minl = 1;
3599           int maxl = cur.lastpos() - cur.pos();
3600           // Greedy behaviour while matching regexps
3601           while (maxl > minl) {
3602             MatchResult mres2;
3603             mres2 = match(cur, len, at_begin);
3604             displayMres(mres2, "Finalize loop", cur);
3605             int actual_match_len = mres2.match_len;
3606             if (actual_match_len >= max_match.match_len) {
3607               // actual_match_len > max_match _can_ happen,
3608               // if the search area splits
3609               // some following word so that the regex
3610               // (e.g. 'r.*r\b' matches 'r' from the middle of the
3611               // splitted word)
3612               // This means, the len value is too big
3613               actual_match_len = max_match.match_len;
3614               max_match = mres2;
3615               max_match.match_len = actual_match_len;
3616               maxl = len;
3617               if (maxl - minl < 4)
3618                 len = (int)((maxl + minl)/2);
3619               else
3620                 len = (int)(minl + (maxl - minl + 3)/4);
3621             }
3622             else {
3623               // (actual_match_len < max_match.match_len)
3624               minl = len + 1;
3625               len = (int)((maxl + minl)/2);
3626             }
3627           }
3628           len = minl;
3629           old_cur = cur;
3630           // Search for real start of matched characters
3631           while (len > 1) {
3632             MatchResult actual_match;
3633             do {
3634               cur.forwardPos();
3635             } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3636             if (cur.depth() < old_cur.depth()) {
3637               // Outer inset?
3638               LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3639               break;
3640             }
3641             if (cur.pos() != old_cur.pos()) {
3642               // OK, forwarded 1 pos in actual inset
3643               actual_match = match(cur, len-1, at_begin);
3644               if (actual_match.match_len == max_match.match_len) {
3645                 // Ha, got it! The shorter selection has the same match length
3646                 len--;
3647                 old_cur = cur;
3648                 max_match = actual_match;
3649               }
3650               else {
3651                 // OK, the shorter selection matches less chars, revert to previous value
3652                 cur = old_cur;
3653                 break;
3654               }
3655             }
3656             else {
3657               LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3658               actual_match = match(cur, len, at_begin);
3659               if (actual_match.match_len == max_match.match_len) {
3660                 old_cur = cur;
3661                 max_match = actual_match;
3662               }
3663             }
3664           }
3665           if (len == 0)
3666             return fail;
3667           else {
3668             max_match.pos_len = len;
3669             displayMres(max_match, "SEARCH RESULT", cur)
3670             return max_match;
3671           }
3672         }
3673 }
3674
3675 /// Finds forward
3676 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3677 {
3678         if (!cur)
3679                 return 0;
3680         bool repeat = false;
3681         DocIterator orig_cur;   // to be used if repeat not successful
3682         MatchResult orig_mres;
3683         while (!theApp()->longOperationCancelled() && cur) {
3684                 //(void) findAdvForwardInnermost(cur);
3685                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3686                 MatchResult mres = match(cur, -1, false);
3687                 string msg = "Starting";
3688                 if (repeat)
3689                         msg = "Repeated";
3690                 displayMres(mres, msg + " findForwardAdv", cur)
3691                 int match_len = mres.match_len;
3692                 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3693                         LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3694                         match_len = 0;
3695                 }
3696                 if (match_len <= 0) {
3697                         // This should exit nested insets, if any, or otherwise undefine the currsor.
3698                         cur.pos() = cur.lastpos();
3699                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3700                         cur.forwardPos();
3701                 }
3702                 else {  // match_len > 0
3703                         // Try to find the begin of searched string
3704                         int increment;
3705                         int firstInvalid = cur.lastpos() - cur.pos();
3706                         {
3707                                 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3708                                 int incrcur = (firstInvalid + 1 )*3/4;
3709                                 if (incrcur < incrmatch)
3710                                         increment = incrcur;
3711                                 else
3712                                         increment = incrmatch;
3713                                 if (increment < 1)
3714                                         increment = 1;
3715                         }
3716                         LYXERR(Debug::FIND, "Set increment to " << increment);
3717                         while (increment > 0) {
3718                                 DocIterator old_cur = cur;
3719                                 if (cur.pos() + increment >= cur.lastpos()) {
3720                                         increment /= 2;
3721                                         continue;
3722                                 }
3723                                 cur.pos() = cur.pos() + increment;
3724                                 MatchResult mres2 = match(cur, -1, false);
3725                                 displayMres(mres2, "findForwardAdv loop", cur)
3726                                 switch (interpretMatch(mres, mres2)) {
3727                                         case MatchResult::newIsTooFar:
3728                                                 // behind the expected match
3729                                                 firstInvalid = increment;
3730                                                 cur = old_cur;
3731                                                 increment /= 2;
3732                                                 break;
3733                                         case MatchResult::newIsBetter:
3734                                                 // not reached yet, but cur.pos()+increment is bettert
3735                                                 mres = mres2;
3736                                                 firstInvalid -= increment;
3737                                                 if (increment > firstInvalid*3/4)
3738                                                         increment = firstInvalid*3/4;
3739                                                 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3740                                                         if (increment >= mres2.match_prefix)
3741                                                                 increment = (mres2.match_prefix+1)*3/4;
3742                                                 }
3743                                                 break;
3744                                         default:
3745                                                 // Todo@
3746                                                 // Handle not like MatchResult::newIsTooFar
3747                                                 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3748                                                 firstInvalid--;
3749                                                 increment = increment*3/4;
3750                                                 cur = old_cur;
3751                                         break;
3752                                 }
3753                         }
3754                         if (mres.match_len > 0) {
3755                                 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3756                                         // The match seems to indicate some deeper level 
3757                                         repeat = true;
3758                                         orig_cur = cur;
3759                                         orig_mres = mres;
3760                                         cur.forwardPos();
3761                                         continue;
3762                                 }
3763                         }
3764                         else if (repeat) {
3765                                 // should never be reached.
3766                                 cur = orig_cur;
3767                                 mres = orig_mres;
3768                         }
3769                         // LYXERR0("Leaving first loop");
3770                         LYXERR(Debug::FIND, "Finalizing 1");
3771                         MatchResult found_match = findAdvFinalize(cur, match, mres);
3772                         if (found_match.match_len > 0) {
3773                                 LASSERT(found_match.pos_len > 0, /**/);
3774                                 match.FillResults(found_match);
3775                                 return found_match.pos_len;
3776                         }
3777                         else {
3778                                 // try next possible match
3779                                 cur.forwardPos();
3780                                 repeat = false;
3781                                 continue;
3782                         }
3783                 }
3784         }
3785         return 0;
3786 }
3787
3788
3789 /// Find the most backward consecutive match within same paragraph while searching backwards.
3790 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3791 {
3792         DocIterator cur_begin = cur;
3793         cur_begin.pos() = 0;
3794         DocIterator tmp_cur = cur;
3795         MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3796         Inset & inset = cur.inset();
3797         for (; cur != cur_begin; cur.backwardPos()) {
3798                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3799                 DocIterator new_cur = cur;
3800                 new_cur.backwardPos();
3801                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3802                         break;
3803                 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3804                 if (new_mr.match_len == mr.match_len)
3805                         break;
3806                 mr = new_mr;
3807         }
3808         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3809         return mr;
3810 }
3811
3812
3813 /// Finds backwards
3814 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3815 {
3816         if (! cur)
3817                 return 0;
3818         // Backup of original position
3819         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3820         if (cur == cur_begin)
3821                 return 0;
3822         cur.backwardPos();
3823         DocIterator cur_orig(cur);
3824         bool pit_changed = false;
3825         do {
3826                 cur.pos() = 0;
3827                 MatchResult found_match = match(cur, -1, false);
3828
3829                 if (found_match.match_len > 0) {
3830                         if (pit_changed)
3831                                 cur.pos() = cur.lastpos();
3832                         else
3833                                 cur.pos() = cur_orig.pos();
3834                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3835                         DocIterator cur_prev_iter;
3836                         do {
3837                                 found_match = match(cur);
3838                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3839                                        << (found_match.match_len > 0) << ", cur: " << cur);
3840                                 if (found_match.match_len > 0) {
3841                                         MatchResult found_mr = findMostBackwards(cur, match, found_match);
3842                                         if (found_mr.pos_len > 0) {
3843                                                 match.FillResults(found_mr);
3844                                                 return found_mr.pos_len;
3845                                         }
3846                                 }
3847
3848                                 // Stop if begin of document reached
3849                                 if (cur == cur_begin)
3850                                         break;
3851                                 cur_prev_iter = cur;
3852                                 cur.backwardPos();
3853                         } while (true);
3854                 }
3855                 if (cur == cur_begin)
3856                         break;
3857                 if (cur.pit() > 0)
3858                         --cur.pit();
3859                 else
3860                         cur.backwardPos();
3861                 pit_changed = true;
3862         } while (!theApp()->longOperationCancelled());
3863         return 0;
3864 }
3865
3866
3867 } // namespace
3868
3869
3870 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3871                                  DocIterator const & cur, int len)
3872 {
3873         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3874                 return docstring();
3875         if (!opt.ignoreformat)
3876                 return latexifyFromCursor(cur, len);
3877         else
3878                 return stringifyFromCursor(cur, len);
3879 }
3880
3881
3882 FindAndReplaceOptions::FindAndReplaceOptions(
3883         docstring const & _find_buf_name, bool _casesensitive,
3884         bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3885         docstring const & _repl_buf_name, bool _keep_case,
3886         SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3887         : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3888           forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3889           repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3890 {
3891 }
3892
3893
3894 namespace {
3895
3896
3897 /** Check if 'len' letters following cursor are all non-lowercase */
3898 static bool allNonLowercase(Cursor const & cur, int len)
3899 {
3900         pos_type beg_pos = cur.selectionBegin().pos();
3901         pos_type end_pos = cur.selectionBegin().pos() + len;
3902         if (len > cur.lastpos() + 1 - beg_pos) {
3903                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3904                 len = cur.lastpos() + 1 - beg_pos;
3905                 end_pos = beg_pos + len;
3906         }
3907         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3908                 if (isLowerCase(cur.paragraph().getChar(pos)))
3909                         return false;
3910         return true;
3911 }
3912
3913
3914 /** Check if first letter is upper case and second one is lower case */
3915 static bool firstUppercase(Cursor const & cur)
3916 {
3917         char_type ch1, ch2;
3918         pos_type pos = cur.selectionBegin().pos();
3919         if (pos >= cur.lastpos() - 1) {
3920                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3921                 return false;
3922         }
3923         ch1 = cur.paragraph().getChar(pos);
3924         ch2 = cur.paragraph().getChar(pos + 1);
3925         bool result = isUpperCase(ch1) && isLowerCase(ch2);
3926         LYXERR(Debug::FIND, "firstUppercase(): "
3927                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3928                << ch2 << "(" << char(ch2) << ")"
3929                << ", result=" << result << ", cur=" << cur);
3930         return result;
3931 }
3932
3933
3934 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3935  **
3936  ** \fixme What to do with possible further paragraphs in replace buffer ?
3937  **/
3938 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3939 {
3940         ParagraphList::iterator pit = buffer.paragraphs().begin();
3941         LASSERT(!pit->empty(), /**/);
3942         pos_type right = pos_type(1);
3943         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3944         right = pit->size();
3945         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3946 }
3947 } // namespace
3948
3949 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3950 {
3951   // Should replace the string "$" + std::to_string(matchnum) with replacement
3952   // if the char '$' is not prefixed with odd number of char '\\'
3953   static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3954   string s;
3955   size_t lastpos = 0;
3956   smatch sub;
3957   for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3958     sub = *it;
3959     if ((sub.position(2) - sub.position(0)) % 2 == 1)
3960       continue;
3961     int num = stoi(sub.str(3), nullptr, 10);
3962     if (num >= maxmatchnum)
3963       continue;
3964     if (lastpos < (size_t) sub.position(2))
3965       s += t.substr(lastpos, sub.position(2) - lastpos);
3966     s += replacements[num];
3967     lastpos = sub.position(2) + sub.length(2);
3968   }
3969   if (lastpos == 0)
3970     return false;
3971   else if (lastpos < t.length())
3972     s += t.substr(lastpos, t.length() - lastpos);
3973   t = s;
3974   return true;
3975 }
3976
3977 ///
3978 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3979 {
3980         Cursor & cur = bv->cursor();
3981         if (opt.repl_buf_name.empty()
3982             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3983             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3984                 return 0;
3985
3986         DocIterator sel_beg = cur.selectionBegin();
3987         DocIterator sel_end = cur.selectionEnd();
3988         if (&sel_beg.inset() != &sel_end.inset()
3989             || sel_beg.pit() != sel_end.pit()
3990             || sel_beg.idx() != sel_end.idx())
3991                 return 0;
3992         int sel_len = sel_end.pos() - sel_beg.pos();
3993         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3994                << ", sel_len: " << sel_len << endl);
3995         if (sel_len == 0)
3996                 return 0;
3997         LASSERT(sel_len > 0, return 0);
3998
3999         if (!matchAdv(sel_beg, sel_len).match_len)
4000                 return 0;
4001
4002         // Build a copy of the replace buffer, adapted to the KeepCase option
4003         Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4004         ostringstream oss;
4005         repl_buffer_orig.write(oss);
4006         string lyx = oss.str();
4007         if (matchAdv.valid_matches > 0) {
4008           replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4009         }
4010         Buffer repl_buffer("", false);
4011         repl_buffer.setUnnamed(true);
4012         LASSERT(repl_buffer.readString(lyx), return 0);
4013         if (opt.keep_case && sel_len >= 2) {
4014                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4015                 if (cur.inTexted()) {
4016                         if (firstUppercase(cur))
4017                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4018                         else if (allNonLowercase(cur, sel_len))
4019                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4020                 }
4021         }
4022         cap::cutSelection(cur, false);
4023         if (cur.inTexted()) {
4024                 repl_buffer.changeLanguage(
4025                         repl_buffer.language(),
4026                         cur.getFont().language());
4027                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4028                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4029                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4030                                         repl_buffer.params().documentClassPtr(),
4031                                         repl_buffer.params().authors(),
4032                                         bv->buffer().errorList("Paste"));
4033                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4034                 sel_len = repl_buffer.paragraphs().begin()->size();
4035         } else if (cur.inMathed()) {
4036                 odocstringstream ods;
4037                 otexstream os(ods);
4038                 // OutputParams runparams(&repl_buffer.params().encoding());
4039                 OutputParams runparams(encodings.fromLyXName("utf8"));
4040                 runparams.nice = false;
4041                 runparams.flavor = Flavor::XeTeX;
4042                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4043                 runparams.dryrun = true;
4044                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4045                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4046                 docstring repl_latex = ods.str();
4047                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4048                 string s;
4049                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4050                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4051                 repl_latex = from_utf8(s);
4052                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4053                 MathData ar(cur.buffer());
4054                 asArray(repl_latex, ar, Parse::NORMAL);
4055                 cur.insert(ar);
4056                 sel_len = ar.size();
4057                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4058         }
4059         if (cur.pos() >= sel_len)
4060                 cur.pos() -= sel_len;
4061         else
4062                 cur.pos() = 0;
4063         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4064         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4065         bv->processUpdateFlags(Update::Force);
4066         return 1;
4067 }
4068
4069
4070 /// Perform a FindAdv operation.
4071 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4072 {
4073         DocIterator cur;
4074         int pos_len = 0;
4075
4076         // e.g., when invoking word-findadv from mini-buffer wither with
4077         //       wrong options syntax or before ever opening advanced F&R pane
4078         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4079                 return false;
4080
4081         try {
4082                 MatchStringAdv matchAdv(bv->buffer(), opt);
4083 #if QTSEARCH
4084                 if (!matchAdv.regexIsValid) {
4085                         bv->message(lyx::from_utf8(matchAdv.regexError));
4086                         return(false);
4087                 }
4088 #endif
4089                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4090                 if (length > 0)
4091                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4092                 num_replaced += findAdvReplace(bv, opt, matchAdv);
4093                 cur = bv->cursor();
4094                 if (opt.forward)
4095                         pos_len = findForwardAdv(cur, matchAdv);
4096                 else
4097                         pos_len = findBackwardsAdv(cur, matchAdv);
4098         } catch (exception & ex) {
4099                 bv->message(from_utf8(ex.what()));
4100                 return false;
4101         }
4102
4103         if (pos_len == 0) {
4104                 if (num_replaced > 0) {
4105                         switch (num_replaced)
4106                         {
4107                                 case 1:
4108                                         bv->message(_("One match has been replaced."));
4109                                         break;
4110                                 case 2:
4111                                         bv->message(_("Two matches have been replaced."));
4112                                         break;
4113                                 default:
4114                                         bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4115                                         break;
4116                         }
4117                         num_replaced = 0;
4118                 }
4119                 else {
4120                         bv->message(_("Match not found."));
4121                 }
4122                 return false;
4123         }
4124
4125         if (num_replaced > 0)
4126                 bv->message(_("Match has been replaced."));
4127         else
4128                 bv->message(_("Match found."));
4129
4130         if (cur.pos() + pos_len > cur.lastpos()) {
4131                 // Prevent crash in bv->putSelectionAt()
4132                 // Should never happen, maybe LASSERT() here?
4133                 pos_len = cur.lastpos() - cur.pos();
4134         }
4135         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4136         bv->putSelectionAt(cur, pos_len, !opt.forward);
4137
4138         return true;
4139 }
4140
4141
4142 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4143 {
4144         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4145            << opt.casesensitive << ' '
4146            << opt.matchword << ' '
4147            << opt.forward << ' '
4148            << opt.expandmacros << ' '
4149            << opt.ignoreformat << ' '
4150            << opt.replace_all << ' '
4151            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4152            << opt.keep_case << ' '
4153            << int(opt.scope) << ' '
4154            << int(opt.restr);
4155
4156         LYXERR(Debug::FIND, "built: " << os.str());
4157
4158         return os;
4159 }
4160
4161
4162 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4163 {
4164         // LYXERR(Debug::FIND, "parsing");
4165         string s;
4166         string line;
4167         getline(is, line);
4168         while (line != "EOSS") {
4169                 if (! s.empty())
4170                         s = s + "\n";
4171                 s = s + line;
4172                 if (is.eof())   // Tolerate malformed request
4173                         break;
4174                 getline(is, line);
4175         }
4176         // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4177         opt.find_buf_name = from_utf8(s);
4178         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4179         is.get();       // Waste space before replace string
4180         s = "";
4181         getline(is, line);
4182         while (line != "EOSS") {
4183                 if (! s.empty())
4184                         s = s + "\n";
4185                 s = s + line;
4186                 if (is.eof())   // Tolerate malformed request
4187                         break;
4188                 getline(is, line);
4189         }
4190         // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4191         opt.repl_buf_name = from_utf8(s);
4192         is >> opt.keep_case;
4193         int i;
4194         is >> i;
4195         opt.scope = FindAndReplaceOptions::SearchScope(i);
4196         is >> i;
4197         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4198
4199         /*
4200         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4201                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4202                << opt.scope << ' ' << opt.restr);
4203         */
4204         return is;
4205 }
4206
4207 } // namespace lyx