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