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