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