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