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