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