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