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