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