]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
GuiParagraph: apply pending changes when setting "immediate apply" (#11592)
[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 ((submath.position(2) - submath.position(0)) %2 == 1) {
1766       // prefixed by odd count of '\\'
1767       continue;
1768     }
1769     if (math_end_waiting) {
1770       size_t pos = submath.position(size_t(2));
1771       if ((math_end == "$") &&
1772           (submath.str(2) == "$")) {
1773         mi.insert("$", math_pos, pos + 1);
1774         math_end_waiting = false;
1775       }
1776       else if ((math_end == "\\]") &&
1777                (submath.str(2) == "\\]")) {
1778         mi.insert("\\]", math_pos, pos + 2);
1779         math_end_waiting = false;
1780       }
1781       else if ((submath.str(3).compare("end") == 0) &&
1782           (submath.str(4).compare(math_end) == 0)) {
1783         mi.insert(math_end, math_pos, pos + submath.str(2).length());
1784         math_end_waiting = false;
1785       }
1786       else
1787         continue;
1788     }
1789     else {
1790       if (submath.str(3).compare("begin") == 0) {
1791         math_end_waiting = true;
1792         math_end = submath.str(4);
1793         math_pos = submath.position(size_t(2));
1794       }
1795       else if (submath.str(2).compare("\\[") == 0) {
1796         math_end_waiting = true;
1797         math_end = "\\]";
1798         math_pos = submath.position(size_t(2));
1799       }
1800       else if (submath.str(2) == "$") {
1801         size_t pos = submath.position(size_t(2));
1802         math_end_waiting = true;
1803         math_end = "$";
1804         math_pos = pos;
1805       }
1806     }
1807   }
1808   // Ignore language if there is math somewhere in pattern-string
1809   if (isPatternString) {
1810     for (auto s: usedText) {
1811       // Remove entries created in previous search runs
1812       keys.erase(s);
1813     }
1814     usedText = vector<string>();
1815     if (! mi.empty()) {
1816       // Disable language
1817       keys["foreignlanguage"].disabled = true;
1818       disableLanguageOverride = true;
1819     }
1820     else
1821       disableLanguageOverride = false;
1822   }
1823   else {
1824     if (disableLanguageOverride) {
1825       keys["foreignlanguage"].disabled = true;
1826     }
1827   }
1828   math_pos = mi.getFirstPos();
1829   for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1830     sub = *it;
1831     if ((sub.position(2) - sub.position(0)) %2 == 1) {
1832       // prefixed by odd count of '\\'
1833       continue;
1834     }
1835     string key = sub.str(5);
1836     if (key == "") {
1837       if (sub.str(2)[0] == '\\')
1838         key = sub.str(2)[1];
1839       else {
1840         key = sub.str(2);
1841         if (key == "$") {
1842           size_t k_pos = sub.position(size_t(2));
1843           if ((k_pos > 0) && (interval_.par[k_pos - 1] == '\\')) {
1844             // Escaped '$', ignoring
1845             continue;
1846           }
1847         }
1848       }
1849     }
1850     if (keys.find(key) != keys.end()) {
1851       if (keys[key].keytype == KeyInfo::headRemove) {
1852         KeyInfo found1 = keys[key];
1853         found1.disabled = true;
1854         found1.head = "\\" + key + "{";
1855         found1._tokenstart = sub.position(size_t(2));
1856         found1._tokensize = found1.head.length();
1857         found1._dataStart = found1._tokenstart + found1.head.length();
1858         int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1859         found1._dataEnd = endpos;
1860         removeHead(found1);
1861         continue;
1862       }
1863     }
1864     if (evaluatingRegexp) {
1865       if (sub.str(3).compare("endregexp") == 0) {
1866         evaluatingRegexp = false;
1867         // found._tokenstart already set
1868         found._dataEnd = sub.position(size_t(2)) + 13;
1869         found._dataStart = found._dataEnd;
1870         found._tokensize = found._dataEnd - found._tokenstart;
1871         found.parenthesiscount = 0;
1872         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1873       }
1874       else {
1875         continue;
1876       }
1877     }
1878     else {
1879       if (evaluatingMath) {
1880         if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1881           continue;
1882         evaluatingMath = false;
1883         mi.incrEntry();
1884         math_pos = mi.getStartPos();
1885       }
1886       if (keys.find(key) == keys.end()) {
1887         found = KeyInfo(KeyInfo::isStandard, 0, true);
1888         LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1889         found = KeyInfo(KeyInfo::isText, 0, false);
1890         if (isPatternString) {
1891           found.keytype = KeyInfo::isChar;
1892           found.disabled = false;
1893           found.used = true;
1894         }
1895         keys[key] = found;
1896         usedText.push_back(key);
1897       }
1898       else
1899         found = keys[key];
1900       if (key.compare("regexp") == 0) {
1901         evaluatingRegexp = true;
1902         found._tokenstart = sub.position(size_t(2));
1903         found._tokensize = 0;
1904         continue;
1905       }
1906     }
1907     // Handle the other params of key
1908     if (found.keytype == KeyInfo::isIgnored)
1909       continue;
1910     else if (found.keytype == KeyInfo::isMath) {
1911       if (size_t(sub.position(size_t(2))) == math_pos) {
1912         found = keys[key];
1913         found._tokenstart = sub.position(size_t(2));
1914         found._tokensize = mi.getSize();
1915         found._dataEnd = found._tokenstart + found._tokensize;
1916         found._dataStart = found._dataEnd;
1917         found.parenthesiscount = 0;
1918         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1919         evaluatingMath = true;
1920       }
1921       else {
1922         // begin|end of unknown env, discard
1923         // First handle tables
1924         // longtable|tabular
1925         bool discardComment;
1926         found = keys[key];
1927         found.keytype = KeyInfo::doRemove;
1928         if ((sub.str(7).compare("longtable") == 0) ||
1929             (sub.str(7).compare("tabular") == 0)) {
1930           discardComment = true;        /* '%' */
1931         }
1932         else {
1933           discardComment = false;
1934           static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1935           smatch sub2;
1936           string token = sub.str(7);
1937           if (regex_match(token, sub2, removeArgs)) {
1938             found.keytype = KeyInfo::removeWithArg;
1939           }
1940         }
1941         // discard spaces before pos(2)
1942         int pos = sub.position(size_t(2));
1943         int count;
1944         for (count = 0; pos - count > 0; count++) {
1945           char c = interval_.par[pos-count-1];
1946           if (discardComment) {
1947             if ((c != ' ') && (c != '%'))
1948               break;
1949           }
1950           else if (c != ' ')
1951             break;
1952         }
1953         found._tokenstart = pos - count;
1954         if (sub.str(3).compare(0, 5, "begin") == 0) {
1955           size_t pos1 = pos + sub.str(2).length();
1956           if (sub.str(7).compare("cjk") == 0) {
1957             pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1958             if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1959               pos1 += 2;
1960             found.keytype = KeyInfo::isMain;
1961             found._dataStart = pos1;
1962             found._dataEnd = interval_.par.length();
1963             found.disabled = keys["foreignlanguage"].disabled;
1964             found.used = keys["foreignlanguage"].used;
1965             found._tokensize = pos1 - found._tokenstart;
1966             found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1967           }
1968           else {
1969             // Swallow possible optional params
1970             while (interval_.par[pos1] == '[') {
1971               pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1972             }
1973             // Swallow also the eventual parameter
1974             if (interval_.par[pos1] == '{') {
1975               found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1976             }
1977             else {
1978               found._dataEnd = pos1;
1979             }
1980             found._dataStart = found._dataEnd;
1981             found._tokensize = count + found._dataEnd - pos;
1982             found.parenthesiscount = 0;
1983             found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1984             found.disabled = true;
1985           }
1986         }
1987         else {
1988           // Handle "\end{...}"
1989           found._dataStart = pos + sub.str(2).length();
1990           found._dataEnd = found._dataStart;
1991           found._tokensize = count + found._dataEnd - pos;
1992           found.parenthesiscount = 0;
1993           found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1994           found.disabled = true;
1995         }
1996       }
1997     }
1998     else if (found.keytype != KeyInfo::isRegex) {
1999       found._tokenstart = sub.position(size_t(2));
2000       if (found.parenthesiscount == 0) {
2001         // Probably to be discarded
2002         size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2003         char following = interval_.par[following_pos];
2004         if (following == ' ')
2005           found.head = "\\" + sub.str(5) + " ";
2006         else if (following == '=') {
2007           // like \uldepth=1000pt
2008           found.head = sub.str(2);
2009         }
2010         else
2011           found.head = "\\" + key;
2012         found._tokensize = found.head.length();
2013         found._dataEnd = found._tokenstart + found._tokensize;
2014         found._dataStart = found._dataEnd;
2015       }
2016       else {
2017         int params = found._tokenstart + key.length() + 1;
2018         if (evaluatingOptional) {
2019           if (size_t(found._tokenstart) > optionalEnd) {
2020             evaluatingOptional = false;
2021           }
2022           else {
2023             found.disabled = true;
2024           }
2025         }
2026         int optend = params;
2027         while (interval_.par[optend] == '[') {
2028           // discard optional parameters
2029           optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2030         }
2031         if (optend > params) {
2032           key += interval_.par.substr(params, optend-params);
2033           evaluatingOptional = true;
2034           optionalEnd = optend;
2035         }
2036         string token = sub.str(7);
2037         int closings;
2038         if (interval_.par[optend] != '{') {
2039           closings = 0;
2040           found.parenthesiscount = 0;
2041           found.head = "\\" + key;
2042         }
2043         else
2044           closings = found.parenthesiscount;
2045         if (found.parenthesiscount == 1) {
2046           found.head = "\\" + key + "{";
2047         }
2048         else if (found.parenthesiscount > 1) {
2049           if (token != "") {
2050             found.head = sub.str(2) + "{";
2051             closings = found.parenthesiscount - 1;
2052           }
2053           else {
2054             found.head = "\\" + key + "{";
2055           }
2056         }
2057         found._tokensize = found.head.length();
2058         found._dataStart = found._tokenstart + found.head.length();
2059         if (found.keytype == KeyInfo::doRemove) {
2060           if (closings > 0) {
2061             size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2062             if (endpar >= interval_.par.length())
2063               found._dataStart = interval_.par.length();
2064             else
2065               found._dataStart = endpar;
2066             found._tokensize = found._dataStart - found._tokenstart;
2067           }
2068           else {
2069             found._dataStart = found._tokenstart + found._tokensize;
2070           } 
2071           closings = 0;
2072         }
2073         if (interval_.par.substr(found._dataStart-1, 15).compare("\\endarguments{}") == 0) {
2074           found._dataStart += 15;
2075         }
2076         size_t endpos;
2077         if (closings < 1)
2078           endpos = found._dataStart - 1;
2079         else
2080           endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2081         if (found.keytype == KeyInfo::isList) {
2082           // Check if it really is list env
2083           static regex const listre("^([a-z]+)$");
2084           smatch sub2;
2085           if (!regex_match(token, sub2, listre)) {
2086             // Change the key of this entry. It is not in a list/item environment
2087             found.keytype = KeyInfo::endArguments;
2088           }
2089         }
2090         if (found.keytype == KeyInfo::noMain) {
2091           evaluatingCode = true;
2092           codeEnd = endpos;
2093           codeStart = found._dataStart;
2094         }
2095         else if (evaluatingCode) {
2096           if (size_t(found._dataStart) > codeEnd)
2097             evaluatingCode = false;
2098           else if (found.keytype == KeyInfo::isMain) {
2099             // Disable this key, treate it as standard
2100             found.keytype = KeyInfo::isStandard;
2101             found.disabled = true;
2102             if ((codeEnd +1 >= interval_.par.length()) &&
2103                 (found._tokenstart == codeStart)) {
2104               // trickery, because the code inset starts
2105               // with \selectlanguage ...
2106               codeEnd = endpos;
2107               if (entries_.size() > 1) {
2108                 entries_[entries_.size()-1]._dataEnd = codeEnd;
2109               }
2110             }
2111           }
2112         }
2113         if ((endpos == interval_.par.length()) &&
2114             (found.keytype == KeyInfo::doRemove)) {
2115           // Missing closing => error in latex-input?
2116           // therefore do not delete remaining data
2117           found._dataStart -= 1;
2118           found._dataEnd = found._dataStart;
2119         }
2120         else
2121           found._dataEnd = endpos;
2122       }
2123       if (isPatternString) {
2124         keys[key].used = true;
2125       }
2126     }
2127     entries_.push_back(found);
2128   }
2129 }
2130
2131 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2132 {
2133   stringstream s(keysstring);
2134   string key;
2135   const char delim = '|';
2136   while (getline(s, key, delim)) {
2137     KeyInfo keyII(keyI);
2138     if (isPatternString) {
2139       keyII.used = false;
2140     }
2141     else if ( !keys[key].used)
2142       keyII.disabled = true;
2143     keys[key] = keyII;
2144   }
2145 }
2146
2147 void LatexInfo::buildKeys(bool isPatternString)
2148 {
2149
2150   static bool keysBuilt = false;
2151   if (keysBuilt && !isPatternString) return;
2152
2153   // Keys to ignore in any case
2154   makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2155   // Known standard keys with 1 parameter.
2156   // Split is done, if not at start of region
2157   makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2158   makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2159   makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2160   makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2161   makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2162   makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2163
2164   makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2165           KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2166   makeKey("section*|subsection*|subsubsection*|paragraph*",
2167           KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2168   makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2169   makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2170   // Regex
2171   makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2172
2173   // Split is done, if not at start of region
2174   makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2175   makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2176
2177   // Split is done always.
2178   makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2179
2180   // Known charaters
2181   // No split
2182   makeKey("backslash|textbackslash|slash",  KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2183   makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2184   makeKey("textasciiacute|texemdash",       KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2185   makeKey("dots|ldots",                     KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2186   makeKey("guillemotright|guillemotleft",   KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2187   // Spaces
2188   makeKey("quad|qquad|hfill|dotfill",               KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2189   makeKey("textvisiblespace|nobreakspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2190   makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2191   makeKey("thickspace|medspace|thinspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2192   // Skip
2193   // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2194   // Custom space/skip, remove the content (== length value)
2195   makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2196   // Found in fr/UserGuide.lyx
2197   makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2198   // quotes
2199   makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2200   makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2201   // Known macros to remove (including their parameter)
2202   // No split
2203   makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2204   makeKey("addtocounter|setlength",                 KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2205   // handle like standard keys with 1 parameter.
2206   makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2207
2208   // Ignore deleted text
2209   makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2210   // but preserve added text
2211   makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2212
2213   // Macros to remove, but let the parameter survive
2214   // No split
2215   makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2216
2217   // Remove language spec from content of these insets
2218   makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2219
2220   // Same effect as previous, parameter will survive (because there is no one anyway)
2221   // No split
2222   makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2223   // Remove table decorations
2224   makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2225   // Discard shape-header.
2226   // For footnote or shortcut too, because of lang settings
2227   // and wrong handling if used 'KeyInfo::noMain'
2228   makeKey("circlepar|diamondpar|heartpar|nutpar",  KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2229   makeKey("trianglerightpar|hexagonpar|starpar",   KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2230   makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2231   makeKey("triangleleftpar|shapepar|dropuppar",    KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2232   makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics",     KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2233   makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2234   // like ('tiny{}' or '\tiny ' ... )
2235   makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2236
2237   // Survives, like known character
2238   // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2239   makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2240   makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2241
2242   makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2243   makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2244   makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2245
2246   makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2247   // Remove RTL/LTR marker
2248   makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2249   makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2250   makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2251   makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2252   makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2253   makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2254   makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2255   if (isPatternString) {
2256     // Allow the first searched string to rebuild the keys too
2257     keysBuilt = false;
2258   }
2259   else {
2260     // no need to rebuild again
2261     keysBuilt = true;
2262   }
2263 }
2264
2265 /*
2266  * Keep the list of actual opened parentheses actual
2267  * (e.g. depth == 4 means there are 4 '{' not processed yet)
2268  */
2269 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2270 {
2271   int skip = 0;
2272   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2273     char c;
2274     c = par[i];
2275     skip = 0;
2276     if (c == '\\') skip = 1;
2277     else if (c == '{') {
2278       handleOpenP(i);
2279     }
2280     else if (c == '}') {
2281       handleCloseP(i, closingAllowed);
2282     }
2283   }
2284 }
2285
2286 #if (0)
2287 string Intervall::show(int lastpos)
2288 {
2289   int idx = 0;                          /* int intervalls */
2290   string s;
2291   int i = 0;
2292   for (idx = 0; idx <= ignoreidx; idx++) {
2293     while (i < lastpos) {
2294       int printsize;
2295       if (i <= borders[idx].low) {
2296         if (borders[idx].low > lastpos)
2297           printsize = lastpos - i;
2298         else
2299           printsize = borders[idx].low - i;
2300         s += par.substr(i, printsize);
2301         i += printsize;
2302         if (i >= borders[idx].low)
2303           i = borders[idx].upper;
2304       }
2305       else {
2306         i = borders[idx].upper;
2307         break;
2308       }
2309     }
2310   }
2311   if (lastpos > i) {
2312     s += par.substr(i, lastpos-i);
2313   }
2314   return s;
2315 }
2316 #endif
2317
2318 void Intervall::output(ostringstream &os, int lastpos)
2319 {
2320   // get number of chars to output
2321   int idx = 0;                          /* int intervalls */
2322   int i = 0;
2323   int printed = 0;
2324   string startTitle = titleValue;
2325   for (idx = 0; idx <= ignoreidx; idx++) {
2326     if (i < lastpos) {
2327       if (i <= borders[idx].low) {
2328         int printsize;
2329         if (borders[idx].low > lastpos)
2330           printsize = lastpos - i;
2331         else
2332           printsize = borders[idx].low - i;
2333         if (printsize > 0) {
2334           os << startTitle << par.substr(i, printsize);
2335           i += printsize;
2336           printed += printsize;
2337           startTitle = "";
2338         }
2339         handleParentheses(i, false);
2340         if (i >= borders[idx].low)
2341           i = borders[idx].upper;
2342       }
2343       else {
2344         i = borders[idx].upper;
2345       }
2346     }
2347     else
2348       break;
2349   }
2350   if (lastpos > i) {
2351     os << startTitle << par.substr(i, lastpos-i);
2352     printed += lastpos-i;
2353   }
2354   handleParentheses(lastpos, false);
2355   int startindex;
2356   if (keys["foreignlanguage"].disabled)
2357     startindex = actualdeptindex-langcount;
2358   else
2359     startindex = actualdeptindex;
2360   for (int i = startindex; i > 0; --i) {
2361     os << "}";
2362   }
2363   if (hasTitle && (printed > 0))
2364     os << "}";
2365   if (! isPatternString_)
2366     os << "\n";
2367   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2368 }
2369
2370 void LatexInfo::processRegion(int start, int region_end)
2371 {
2372   while (start < region_end) {          /* Let {[} and {]} survive */
2373     int cnt = interval_.isOpeningPar(start);
2374     if (cnt == 1) {
2375       // Closing is allowed past the region
2376       int closing = interval_.findclosing(start+1, interval_.par.length());
2377       interval_.addIntervall(start, start+1);
2378       interval_.addIntervall(closing, closing+1);
2379     }
2380     else if (cnt == 3)
2381       start += 2;
2382     start = interval_.nextNotIgnored(start+1);
2383   }
2384 }
2385
2386 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2387 {
2388   if (actual.parenthesiscount == 0) {
2389     // "{\tiny{} ...}" ==> "{{} ...}"
2390     interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2391   }
2392   else {
2393     // Remove header hull, that is "\url{abcd}" ==> "abcd"
2394     interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2395     interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2396   }
2397 }
2398
2399 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2400 {
2401   int nextKeyIdx = 0;
2402   switch (actual.keytype)
2403   {
2404     case KeyInfo::isTitle: {
2405       removeHead(actual);
2406       nextKeyIdx = getNextKey();
2407       break;
2408     }
2409     case KeyInfo::cleanToStart: {
2410       actual._dataEnd = actual._dataStart;
2411       nextKeyIdx = getNextKey();
2412       // Search for end of arguments
2413       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2414       if (tmpIdx > 0) {
2415         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2416           entries_[i].disabled = true;
2417         }
2418         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2419       }
2420       while (interval_.par[actual._dataEnd] == ' ')
2421         actual._dataEnd++;
2422       interval_.addIntervall(0, actual._dataEnd+1);
2423       interval_.actualdeptindex = 0;
2424       interval_.depts[0] = actual._dataEnd+1;
2425       interval_.closes[0] = -1;
2426       break;
2427     }
2428     case KeyInfo::isText:
2429       interval_.par[actual._tokenstart] = '#';
2430       //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2431       nextKeyIdx = getNextKey();
2432       break;
2433     case KeyInfo::noContent: {          /* char like "\hspace{2cm}" */
2434       if (actual.disabled)
2435         interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2436       else
2437         interval_.addIntervall(actual._dataStart, actual._dataEnd);
2438     }
2439       // fall through
2440     case KeyInfo::isChar: {
2441       nextKeyIdx = getNextKey();
2442       break;
2443     }
2444     case KeyInfo::isSize: {
2445       if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2446         if (actual.parenthesiscount == 0)
2447           interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2448         else {
2449           interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2450         }
2451         nextKeyIdx = getNextKey();
2452       } else {
2453         // Here _dataStart points to '{', so correct it
2454         actual._dataStart += 1;
2455         actual._tokensize += 1;
2456         actual.parenthesiscount = 1;
2457         if (interval_.par[actual._dataStart] == '}') {
2458           // Determine the end if used like '{\tiny{}...}'
2459           actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2460           interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2461         }
2462         else {
2463           // Determine the end if used like '\tiny{...}'
2464           actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2465         }
2466         // Split on this key if not at start
2467         int start = interval_.nextNotIgnored(previousStart);
2468         if (start < actual._tokenstart) {
2469           interval_.output(os, actual._tokenstart);
2470           interval_.addIntervall(start, actual._tokenstart);
2471         }
2472         // discard entry if at end of actual
2473         nextKeyIdx = process(os, actual);
2474       }
2475       break;
2476     }
2477     case KeyInfo::endArguments: {
2478       // Remove trailing '{}' too
2479       actual._dataStart += 1;
2480       actual._dataEnd += 1;
2481       interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2482       nextKeyIdx = getNextKey();
2483       break;
2484     }
2485     case KeyInfo::noMain:
2486       // fall through
2487     case KeyInfo::isStandard: {
2488       if (actual.disabled) {
2489         removeHead(actual);
2490         processRegion(actual._dataStart, actual._dataStart+1);
2491         nextKeyIdx = getNextKey();
2492       } else {
2493         // Split on this key if not at datastart of calling entry
2494         int start = interval_.nextNotIgnored(previousStart);
2495         if (start < actual._tokenstart) {
2496           interval_.output(os, actual._tokenstart);
2497           interval_.addIntervall(start, actual._tokenstart);
2498         }
2499         // discard entry if at end of actual
2500         nextKeyIdx = process(os, actual);
2501       }
2502       break;
2503     }
2504     case KeyInfo::removeWithArg: {
2505       nextKeyIdx = getNextKey();
2506       // Search for end of arguments
2507       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2508       if (tmpIdx > 0) {
2509         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2510           entries_[i].disabled = true;
2511         }
2512         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2513       }
2514       interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2515       break;
2516     }
2517     case KeyInfo::doRemove: {
2518       // Remove the key with all parameters and following spaces
2519       size_t pos;
2520       for (pos = actual._dataEnd+1; pos < interval_.par.length(); pos++) {
2521         if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2522           break;
2523       }
2524       // Remove also enclosing parentheses [] and {}
2525       int numpars = 0;
2526       int spaces = 0;
2527       while (actual._tokenstart > numpars) {
2528         if (pos+numpars >= interval_.par.size())
2529           break;
2530         else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2531           numpars++;
2532         else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2533           numpars++;
2534         else
2535           break;
2536       }
2537       if (numpars > 0) {
2538         if (interval_.par[pos+numpars] == ' ')
2539           spaces++;
2540       }
2541
2542       interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2543       nextKeyIdx = getNextKey();
2544       break;
2545     }
2546     case KeyInfo::isList: {
2547       // Discard space before _tokenstart
2548       int count;
2549       for (count = 0; count < actual._tokenstart; count++) {
2550         if (interval_.par[actual._tokenstart-count-1] != ' ')
2551           break;
2552       }
2553       nextKeyIdx = getNextKey();
2554       int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2555       if (tmpIdx > 0) {
2556         // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2557         // with arguments
2558         // How else can we catch this one?
2559         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2560           entries_[i].disabled = true;
2561         }
2562         actual._dataEnd = entries_[tmpIdx]._dataEnd;
2563       }
2564       else if (nextKeyIdx > 0) {
2565         // Ignore any lang entries inside data region
2566         for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2567           if (entries_[i].keytype == KeyInfo::isMain)
2568             entries_[i].disabled = true;
2569         }
2570       }
2571       if (actual.disabled) {
2572         interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2573       }
2574       else {
2575         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2576       }
2577       if (interval_.par[actual._dataEnd+1] == '[') {
2578         int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2579         if ((interval_.par[actual._dataEnd+2] == '{') &&
2580             (interval_.par[posdown-1] == '}')) {
2581           interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2582           interval_.addIntervall(posdown-1, posdown+1);
2583         }
2584         else {
2585           interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2586           interval_.addIntervall(posdown, posdown+1);
2587         }
2588         int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2589         if (blk > posdown) {
2590           // Discard at most 1 space after empty item
2591           int count;
2592           for (count = 0; count < 1; count++) {
2593             if (interval_.par[blk+count] != ' ')
2594               break;
2595           }
2596           if (count > 0)
2597             interval_.addIntervall(blk, blk+count);
2598         }
2599       }
2600       break;
2601     }
2602     case KeyInfo::isSectioning: {
2603       // Discard spaces before _tokenstart
2604       int count;
2605       int val = actual._tokenstart;
2606       for (count = 0; count < actual._tokenstart;) {
2607         val = interval_.previousNotIgnored(val-1);
2608         if (val < 0 || interval_.par[val] != ' ')
2609           break;
2610         else {
2611           count = actual._tokenstart - val;
2612         }
2613       }
2614       if (actual.disabled) {
2615         removeHead(actual, count);
2616         nextKeyIdx = getNextKey();
2617       } else {
2618         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2619         nextKeyIdx = process(os, actual);
2620       }
2621       break;
2622     }
2623     case KeyInfo::isMath: {
2624       // Same as regex, use the content unchanged
2625       nextKeyIdx = getNextKey();
2626       break;
2627     }
2628     case KeyInfo::isRegex: {
2629       // DO NOT SPLIT ON REGEX
2630       // Do not disable
2631       nextKeyIdx = getNextKey();
2632       break;
2633     }
2634     case KeyInfo::isIgnored: {
2635       // Treat like a character for now
2636       nextKeyIdx = getNextKey();
2637       break;
2638     }
2639     case KeyInfo::isMain: {
2640       if (interval_.par.substr(actual._dataStart, 2) == "% ")
2641         interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2642       if (actual._tokenstart > 0) {
2643         int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2644         if ((prev >= 0) && interval_.par[prev] == '%')
2645           interval_.addIntervall(prev, prev+1);
2646       }
2647       if (actual.disabled) {
2648         removeHead(actual);
2649         interval_.langcount++;
2650         if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2651             (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2652           // Discard also the space before math-equation
2653           interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2654         }
2655         nextKeyIdx = getNextKey();
2656         // interval.resetOpenedP(actual._dataStart-1);
2657       }
2658       else {
2659         if (actual._tokenstart < 26) {
2660           // for the first (and maybe dummy) language
2661           interval_.setForDefaultLang(actual);
2662         }
2663         interval_.resetOpenedP(actual._dataStart-1);
2664       }
2665       break;
2666     }
2667     case KeyInfo::invalid:
2668     case KeyInfo::headRemove:
2669       // These two cases cannot happen, already handled
2670       // fall through
2671     default: {
2672       // LYXERR(Debug::INFO, "Unhandled keytype");
2673       nextKeyIdx = getNextKey();
2674       break;
2675     }
2676   }
2677   return nextKeyIdx;
2678 }
2679
2680 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2681 {
2682   int end = interval_.nextNotIgnored(actual._dataEnd);
2683   int oldStart = actual._dataStart;
2684   int nextKeyIdx = getNextKey();
2685   while (true) {
2686     if ((nextKeyIdx < 0) ||
2687         (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2688         (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2689       if (oldStart <= end) {
2690         processRegion(oldStart, end);
2691         oldStart = end+1;
2692       }
2693       break;
2694     }
2695     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2696
2697     if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2698       (void) dispatch(os, actual._dataStart, nextKey);
2699       end = nextKey._tokenstart;
2700       break;
2701     }
2702     processRegion(oldStart, nextKey._tokenstart);
2703     nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2704
2705     oldStart = nextKey._dataEnd+1;
2706   }
2707   // now nextKey is either invalid or is outside of actual._dataEnd
2708   // output the remaining and discard myself
2709   if (oldStart <= end) {
2710     processRegion(oldStart, end);
2711   }
2712   if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2713     end += 1;
2714     // This is the normal case.
2715     // But if using the firstlanguage, the closing may be missing
2716   }
2717   // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2718   int output_end;
2719   if (actual._dataEnd < end)
2720     output_end = interval_.nextNotIgnored(actual._dataEnd);
2721   else if (interval_.par.size() > (size_t) end)
2722     output_end = interval_.nextNotIgnored(end);
2723   else
2724     output_end = interval_.par.size();
2725   if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2726     interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2727   }
2728   // Remove possible empty data
2729   int dstart = interval_.nextNotIgnored(actual._dataStart);
2730   while (interval_.isOpeningPar(dstart) == 1) {
2731     interval_.addIntervall(dstart, dstart+1);
2732     int dend = interval_.findclosing(dstart+1, output_end);
2733     interval_.addIntervall(dend, dend+1);
2734     dstart = interval_.nextNotIgnored(dstart+1);
2735   }
2736   if (dstart < output_end)
2737     interval_.output(os, output_end);
2738   interval_.addIntervall(actual._tokenstart, end);
2739   return nextKeyIdx;
2740 }
2741
2742 string splitOnKnownMacros(string par, bool isPatternString)
2743 {
2744   ostringstream os;
2745   LatexInfo li(par, isPatternString);
2746   // LYXERR(Debug::INFO, "Berfore split: " << par);
2747   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2748   DummyKey.head = "";
2749   DummyKey._tokensize = 0;
2750   DummyKey._dataStart = 0;
2751   DummyKey._dataEnd = par.length();
2752   DummyKey.disabled = true;
2753   int firstkeyIdx = li.getFirstKey();
2754   string s;
2755   if (firstkeyIdx >= 0) {
2756     KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2757     DummyKey._tokenstart = firstKey._tokenstart;
2758     int nextkeyIdx;
2759     if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2760       // Use dummy firstKey
2761       firstKey = DummyKey;
2762       (void) li.setNextKey(firstkeyIdx);
2763     }
2764     else {
2765       if (par.substr(firstKey._dataStart, 2) == "% ")
2766         li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2767     }
2768     nextkeyIdx = li.process(os, firstKey);
2769     while (nextkeyIdx >= 0) {
2770       // Check for a possible gap between the last
2771       // entry and this one
2772       int datastart = li.nextNotIgnored(firstKey._dataStart);
2773       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2774       if ((nextKey._tokenstart > datastart)) {
2775         // Handle the gap
2776         firstKey._dataStart = datastart;
2777         firstKey._dataEnd = par.length();
2778         (void) li.setNextKey(nextkeyIdx);
2779         // Fake the last opened parenthesis
2780         li.setForDefaultLang(firstKey);
2781         nextkeyIdx = li.process(os, firstKey);
2782       }
2783       else {
2784         if (nextKey.keytype != KeyInfo::isMain) {
2785           firstKey._dataStart = datastart;
2786           firstKey._dataEnd = nextKey._dataEnd+1;
2787           (void) li.setNextKey(nextkeyIdx);
2788           li.setForDefaultLang(firstKey);
2789           nextkeyIdx = li.process(os, firstKey);
2790         }
2791         else {
2792           nextkeyIdx = li.process(os, nextKey);
2793         }
2794       }
2795     }
2796     // Handle the remaining
2797     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2798     firstKey._dataEnd = par.length();
2799     // Check if ! empty
2800     if ((firstKey._dataStart < firstKey._dataEnd) &&
2801         (par[firstKey._dataStart] != '}')) {
2802       li.setForDefaultLang(firstKey);
2803       (void) li.process(os, firstKey);
2804     }
2805     s = os.str();
2806     if (s.empty()) {
2807       // return string definitelly impossible to match
2808       s = "\\foreignlanguage{ignore}{ }";
2809     }
2810   }
2811   else
2812     s = par;                            /* no known macros found */
2813   // LYXERR(Debug::INFO, "After split: " << s);
2814   return s;
2815 }
2816
2817 /*
2818  * Try to unify the language specs in the latexified text.
2819  * Resulting modified string is set to "", if
2820  * the searched tex does not contain all the features in the search pattern
2821  */
2822 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2823 {
2824         static Features regex_f;
2825         static int missed = 0;
2826         static bool regex_with_format = false;
2827
2828         int parlen = par.length();
2829
2830         while ((parlen > 0) && (par[parlen-1] == '\n')) {
2831                 parlen--;
2832         }
2833         if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2834                 // Happens to be there in case of description or labeling environment
2835                 parlen--;
2836         }
2837         string result;
2838         if (withformat) {
2839                 // Split the latex input into pieces which
2840                 // can be digested by our search engine
2841                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2842                 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2843                 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2844         }
2845         else
2846                 result = par.substr(0, parlen);
2847         if (isPatternString) {
2848                 missed = 0;
2849                 if (withformat) {
2850                         regex_f = identifyFeatures(result);
2851                         string features = "";
2852                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2853                                 string a = it->first;
2854                                 regex_with_format = true;
2855                                 features += " " + a;
2856                                 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2857                         }
2858                         LYXERR(Debug::FIND, "Identified Features" << features);
2859
2860                 }
2861         } else if (regex_with_format) {
2862                 Features info = identifyFeatures(result);
2863                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2864                         string a = it->first;
2865                         bool b = it->second;
2866                         if (b && ! info[a]) {
2867                                 missed++;
2868                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2869                                 return "";
2870                         }
2871                 }
2872         }
2873         else {
2874                 // LYXERR(Debug::INFO, "No regex formats");
2875         }
2876         return result;
2877 }
2878
2879
2880 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2881 static int identifyClosing(string & t)
2882 {
2883         int open_braces = 0;
2884         do {
2885                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2886                 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2887                         continue;
2888                 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2889                         continue;
2890                 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2891                         continue;
2892                 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2893                         ++open_braces;
2894                         continue;
2895                 }
2896                 break;
2897         } while (true);
2898         return open_braces;
2899 }
2900
2901 static int num_replaced = 0;
2902 static bool previous_single_replace = true;
2903
2904 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2905         : p_buf(&buf), p_first_buf(&buf), opt(opt)
2906 {
2907         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2908         docstring const & ds = stringifySearchBuffer(find_buf, opt);
2909         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2910         if (opt.replace_all && previous_single_replace) {
2911                 previous_single_replace = false;
2912                 num_replaced = 0;
2913         }
2914         else if (!opt.replace_all) {
2915                 num_replaced = 0;       // count number of replaced strings
2916                 previous_single_replace = true;
2917         }
2918         // When using regexp, braces are hacked already by escape_for_regex()
2919         par_as_string = normalize(ds, !use_regexp);
2920         open_braces = 0;
2921         close_wildcards = 0;
2922
2923         size_t lead_size = 0;
2924         // correct the language settings
2925         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2926         if (opt.ignoreformat) {
2927                 if (!use_regexp) {
2928                         // if par_as_string_nolead were emty,
2929                         // the following call to findAux will always *find* the string
2930                         // in the checked data, and thus always using the slow
2931                         // examining of the current text part.
2932                         par_as_string_nolead = par_as_string;
2933                 }
2934         } else {
2935                 lead_size = identifyLeading(par_as_string);
2936                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2937                 lead_as_string = par_as_string.substr(0, lead_size);
2938                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2939         }
2940
2941         if (!use_regexp) {
2942                 open_braces = identifyClosing(par_as_string);
2943                 identifyClosing(par_as_string_nolead);
2944                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2945                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2946         } else {
2947                 string lead_as_regexp;
2948                 if (lead_size > 0) {
2949                         // @todo No need to search for \regexp{} insets in leading material
2950                         static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\\])" };
2951                         lead_as_regexp = std::regex_replace(par_as_string.substr(0, lead_size), specialChars,  R"(\$&)" );
2952                         // lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2953                         par_as_string = par_as_string_nolead;
2954                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2955                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2956                 }
2957                 LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
2958                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2959                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2960                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2961                 if (
2962                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2963                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2964                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2965                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2966                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2967                         || regex_replace(par_as_string, par_as_string,
2968                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2969                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2970                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2971                         ) {
2972                         ++close_wildcards;
2973                 }
2974                 if (!opt.ignoreformat) {
2975                         // Remove extra '\}' at end if not part of \{\.\}
2976                         size_t lng = par_as_string.size();
2977                         while(lng > 2) {
2978                                 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
2979                                         if (lng >= 6) {
2980                                                 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
2981                                                         break;
2982                                         }
2983                                         lng -= 2;
2984                                         open_braces++;
2985                                 }
2986                                 else
2987                                         break;
2988                         }
2989                         if (lng < par_as_string.size())
2990                                 par_as_string = par_as_string.substr(0,lng);
2991                         /*
2992                         // save '\.'
2993                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2994                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2995                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2996                         // replace '[^...]' with '[^...\}\{\\]'
2997                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2998                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2999                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
3000                         // restore '\.'
3001                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
3002                         */
3003                 }
3004                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3005                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
3006                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
3007                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3008
3009                 // If entered regexp must match at begin of searched string buffer
3010                 // Kornel: Added parentheses to use $1 for size of the leading string
3011                 string regexp_str;
3012                 string regexp2_str;
3013                 {
3014                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3015                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
3016                         // so the convert has no effect in that case
3017                         for (int i = 7; i > 0; --i) {
3018                                 string orig = "\\\\" + std::to_string(i);
3019                                 string dest = "\\" + std::to_string(i+2);
3020                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
3021                         }
3022                         regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3023                         regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3024                 }
3025                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3026                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3027 #if QTSEARCH
3028                 // Handle \w properly
3029                 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3030                 if (! opt.casesensitive) {
3031                         popts |= QRegularExpression::CaseInsensitiveOption;
3032                 }
3033                 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3034                 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3035                 regexError = "";
3036                 if (regexp.isValid() && regexp2.isValid()) {
3037                         regexIsValid = true;
3038                         // Check '{', '}' pairs inside the regex
3039                         int balanced = 0;
3040                         int skip = 1;
3041                         for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3042                                 char c = par_as_string[i];
3043                                 if (c == '\\') {
3044                                         skip = 2;
3045                                         continue;
3046                                 }
3047                                 if (c == '{')
3048                                         balanced++;
3049                                 else if (c == '}') {
3050                                         balanced--;
3051                                         if (balanced < 0)
3052                                                 break;
3053                                 }
3054                                 skip = 1;
3055                         }
3056                         if (balanced != 0) {
3057                                 regexIsValid = false;
3058                                 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3059                         }
3060                 }
3061                 else {
3062                         regexIsValid = false;
3063                         if (!regexp.isValid())
3064                                 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3065                         if (!regexp2.isValid())
3066                                 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3067                 }
3068 #else
3069                 if (opt.casesensitive) {
3070                         regexp = regex(regexp_str);
3071                         regexp2 = regex(regexp2_str);
3072                 }
3073                 else {
3074                         regexp = regex(regexp_str, std::regex_constants::icase);
3075                         regexp2 = regex(regexp2_str, std::regex_constants::icase);
3076                 }
3077 #endif
3078         }
3079 }
3080
3081 #if 0
3082 // Count number of characters in string
3083 // {]} ==> 1
3084 // \&  ==> 1
3085 // --- ==> 1
3086 // \\[a-zA-Z]+ ==> 1
3087 #if QTSEARCH
3088 static int computeSize(QStringRef s, int len)
3089 #define isLyxAlpha(arg) arg.isLetter()
3090 #else
3091 static int computeSize(string s, int len)
3092 #define isLyxAlpha(arg) isalpha(arg)
3093 #endif
3094 {
3095         if (len == 0)
3096                 return 0;
3097         int skip = 1;
3098         int count = 0;
3099         for (int i = 0; i < len; i += skip, count++) {
3100                 if (s.at(i) == '\\') {
3101                         skip = 2;
3102                         if (i + 1 < len && isLyxAlpha(s.at(i+1))) {
3103                                 for (int j = 2;  i+j < len; j++) {
3104                                         if (! isLyxAlpha(s.at(i+j))) {
3105                                                 if (s.at(i+j) == ' ')
3106                                                         skip++;
3107                                                 else if (s.at(i+j) == '{') {
3108                                                         if (i+j+1 < len && s.at(i+j+1) == '}')
3109                                                                 skip += 2;
3110                                                         else if (i + j + 1 >= len)
3111                                                                 skip++;
3112                                                 }
3113                                                 break;
3114                                         }
3115                                         skip++;
3116                                 }
3117                         }
3118                 }
3119                 else if (s.at(i) == '{') {
3120                         if (i + 1 < len && s.at(i+1) == '}')
3121                                 skip = 2;
3122                         else
3123                                 skip = 3;
3124                 }
3125                 else if (s.at(i) == '-') {
3126                         if (i+1 < len && s.at(i+1) == '-') {
3127                                 if (i + 2 < len && s.at(i+2) == '-')
3128                                         skip = 3;
3129                                 else
3130                                         skip = 2;
3131                         }
3132                         else
3133                                 skip = 1;
3134                 }
3135                 else {
3136                         skip = 1;
3137                 }
3138         }
3139         return count;
3140 }
3141 #endif
3142
3143 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3144 {
3145         MatchResult mres;
3146
3147         if (at_begin &&
3148                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3149                 return mres;
3150
3151         docstring docstr = stringifyFromForSearch(opt, cur, len);
3152         string str;
3153         if (use_regexp || opt.casesensitive)
3154                 str = normalize(docstr, true);
3155         else
3156                 str = normalize(lowercase(docstr), true);
3157         if (!opt.ignoreformat) {
3158                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3159         }
3160         if (str.empty()) {
3161                 mres.match_len = -1;
3162                 return mres;
3163         }
3164         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
3165         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
3166
3167         if (use_regexp) {
3168                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3169 #if QTSEARCH
3170                 QString qstr = QString::fromStdString(str);
3171                 QRegularExpression const *p_regexp;
3172                 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3173                 if (at_begin) {
3174                         p_regexp = &regexp;
3175                 } else {
3176                         p_regexp = &regexp2;
3177                 }
3178                 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3179                 if (!match.hasMatch())
3180                         return mres;
3181                 // Check braces on segments that matched all (.*?) subexpressions,
3182                 // except the last "padding" one inserted by lyx.
3183                 for (int i = 3; i < match.lastCapturedIndex(); ++i)
3184                         if (!braces_match(match.captured(i), open_braces))
3185                                 return mres;
3186 #else
3187                 regex const *p_regexp;
3188                 regex_constants::match_flag_type flags;
3189                 if (at_begin) {
3190                         flags = regex_constants::match_continuous;
3191                         p_regexp = &regexp;
3192                 } else {
3193                         flags = regex_constants::match_default;
3194                         p_regexp = &regexp2;
3195                 }
3196                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3197                 if (re_it == sregex_iterator())
3198                         return mres;
3199                 match_results<string::const_iterator> const & m = *re_it;
3200                 // Check braces on segments that matched all (.*?) subexpressions,
3201                 // except the last "padding" one inserted by lyx.
3202                 for (size_t i = 3; i < m.size() - 1; ++i)
3203                         if (!braces_match(m[i], open_braces))
3204                                 return mres;
3205 #endif
3206                 // Exclude from the returned match length any length
3207                 // due to close wildcards added at end of regexp
3208                 // and also the length of the leading (e.g. '\emph{}')
3209                 //
3210                 // Whole found string, including the leading: m[0].second - m[0].first
3211                 // Size of the leading string: m[1].second - m[1].first
3212                 int leadingsize = 0;
3213                 int result;
3214 #if QTSEARCH
3215                 if (match.lastCapturedIndex() > 0) {
3216                         leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3217                 }
3218                 int lastidx = match.lastCapturedIndex();
3219                 for (int i = 0; i <= lastidx; i++) {
3220                         LYXERR(Debug::FIND, "Match " << i << " is " << match.capturedEnd(i) - match.capturedStart(i) << " long");
3221                 }
3222                 if (close_wildcards == 0)
3223                         result = match.capturedEnd(0) - match.capturedStart(0);
3224                 else
3225                         result =  match.capturedStart(lastidx + 1 - close_wildcards) - match.capturedStart(0);
3226
3227 #else
3228                 if (m.size() > 2) {
3229                         leadingsize = m[1].second - m[1].first;
3230                 }
3231                 for (size_t i = 0; i < m.size(); i++) {
3232                         LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
3233                 }
3234                 if (close_wildcards == 0)
3235                         result = m[0].second - m[0].first;
3236                 else
3237                         result =  m[m.size() - close_wildcards].first - m[0].first;
3238 #endif
3239                 if (result > leadingsize)
3240                         result -= leadingsize;
3241                 else
3242                         result = 0;
3243 #if QTSEARCH
3244                 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3245                 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3246                 // because of different number of closing at end of string
3247                 // we have to 'unify' the length of the post-match.
3248                 // Done by ignoring closing parenthesis and linefeeds at string end
3249                 int matchend = match.capturedEnd(0);
3250                 while (mres.match_len > 0) {
3251                   QChar c = qstr.at(matchend - 1);
3252                   if ((c == '\n') || (c == '}') || (c == '{')) {
3253                     mres.match_len--;
3254                     matchend--;
3255                   }
3256                   else
3257                     break;
3258                 }
3259                 size_t strsize = qstr.size();
3260                 while (strsize > (size_t) match.capturedEnd(0)) {
3261                         QChar c = qstr.at(strsize-1);
3262                         if ((c == '\n') || (c == '}')) {
3263                                 --strsize;
3264                         }
3265                         else
3266                                 break;
3267                 }
3268                 // LYXERR0(qstr.toStdString());
3269                 mres.match2end = strsize - matchend;
3270                 mres.pos = match.capturedStart(2);
3271 #else
3272                 mres.match_prefix = m[2].second - m[2].first;
3273                 mres.match_len = m[0].second - m[2].second;
3274                 // ignore closing parenthesis and linefeeds at string end
3275                 size_t strend = m[0].second - m[0].first;
3276                 int matchend = strend;
3277                 while (mres.match_len > 0) {
3278                   char c = str.at(matchend - 1);
3279                   if ((c == '\n') || (c == '}') || (c == '{')) {
3280                     mres.match_len--;
3281                     matchend--;
3282                   }
3283                   else
3284                     break;
3285                 }
3286                 size_t strsize = str.size();
3287                 while (strsize > strend) {
3288                         if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3289                                 --strsize;
3290                         }
3291                         else
3292                                 break;
3293                 }
3294                 // LYXERR0(str);
3295                 mres.match2end = strsize - matchend;
3296                 mres.pos = m[2].first - m[0].first;;
3297 #endif
3298                 if (mres.match2end < 0)
3299                   mres.match_len = 0;
3300                 mres.leadsize = leadingsize;
3301                 return mres;
3302         }
3303
3304         // else !use_regexp: but all code paths above return
3305         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
3306                                  << par_as_string << "', str='" << str << "'");
3307         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
3308                                  << lead_as_string << "', par_as_string_nolead='"
3309                                  << par_as_string_nolead << "'");
3310
3311         if (at_begin) {
3312                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3313                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3314                 if (str.substr(0, par_as_string.size()) == par_as_string) {
3315                         mres.match_len = par_as_string.size();
3316                         mres.match2end = str.size();
3317                         mres.pos = 0;
3318                         return mres;
3319                 }
3320         } else {
3321                 // Start the search _after_ the leading part
3322                 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3323                 if (pos != string::npos) {
3324                         mres.match_len = par_as_string.size();
3325                         mres.match2end = str.size() - pos;
3326                         mres.pos = pos;
3327                         return mres;
3328                 }
3329         }
3330         return mres;
3331 }
3332
3333
3334 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3335 {
3336         MatchResult mres = findAux(cur, len, at_begin);
3337         int res = mres.match_len;
3338         LYXERR(Debug::FIND,
3339                "res=" << res << ", at_begin=" << at_begin
3340                << ", matchword=" << opt.matchword
3341                << ", inTexted=" << cur.inTexted());
3342         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
3343                 return mres;
3344         if ((len > 0) && (res < len)) {
3345           mres.match_len = 0;
3346           return mres;
3347         }
3348         Paragraph const & par = cur.paragraph();
3349         bool ws_left = (cur.pos() > 0)
3350                 ? par.isWordSeparator(cur.pos() - 1)
3351                 : true;
3352         bool ws_right;
3353         if (len < 0)
3354                 ws_right = true;
3355         else {
3356                 ws_right = (cur.pos() + len < par.size())
3357                 ? par.isWordSeparator(cur.pos() + len)
3358                 : true;
3359         }
3360         LYXERR(Debug::FIND,
3361                "cur.pos()=" << cur.pos() << ", res=" << res
3362                << ", separ: " << ws_left << ", " << ws_right
3363                << ", len: " << len
3364                << endl);
3365         if (ws_left && ws_right) {
3366           // Check for word separators inside the found 'word'
3367           for (int i = 0; i < len; i++) {
3368             if (par.isWordSeparator(cur.pos() + i)) {
3369               mres.match_len = 0;
3370               return mres;
3371             }
3372           }
3373           return mres;
3374         }
3375         mres.match_len = 0;
3376         return mres;
3377 }
3378
3379 static bool simple_replace(string &t, string from, string to)
3380 {
3381   regex repl("(\\\\)*(" + from + ")");
3382   string s("");
3383   size_t lastpos = 0;
3384   smatch sub;
3385   for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3386     sub = *it;
3387     if ((sub.position(2) - sub.position(0)) % 2 == 1)
3388       continue;
3389     if (lastpos < (size_t) sub.position(2))
3390       s += t.substr(lastpos, sub.position(2) - lastpos);
3391     s += to;
3392     lastpos = sub.position(2) + sub.length(2);
3393   }
3394   if (lastpos == 0)
3395     return false;
3396   else if (lastpos < t.length())
3397     s += t.substr(lastpos, t.length() - lastpos);
3398   t = s;
3399   return true;
3400 }
3401
3402 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
3403 {
3404         string t;
3405         t = lyx::to_utf8(s);
3406         // Remove \n at begin
3407         while (!t.empty() && t[0] == '\n')
3408                 t = t.substr(1);
3409         // Remove \n at end
3410         while (!t.empty() && t[t.size() - 1] == '\n')
3411                 t = t.substr(0, t.size() - 1);
3412         size_t pos;
3413         // Handle all other '\n'
3414         while ((pos = t.find("\n")) != string::npos) {
3415                 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3416                         // Handle '\\\n'
3417                         if (isAlnumASCII(t[pos+1])) {
3418                                 t.replace(pos-2, 3, " ");
3419                         }
3420                         else {
3421                                 t.replace(pos-2, 3, "");
3422                         }
3423                 }
3424                 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3425                         // '\n' adjacent to non-alpha-numerics, discard
3426                         t.replace(pos, 1, "");
3427                 }
3428                 else {
3429                         // Replace all other \n with spaces
3430                         t.replace(pos, 1, " ");
3431                 }
3432         }
3433         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3434         // Kornel: Added textsl, textsf, textit, texttt and noun
3435         // + allow to seach for colored text too
3436         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3437         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3438                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3439         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3440                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3441         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3442         // FIXME - check what preceeds the brace
3443         if (hack_braces) {
3444                 if (opt.ignoreformat)
3445                         while (regex_replace(t, t, "\\{", "_x_<")
3446                                || regex_replace(t, t, "\\}", "_x_>"))
3447                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3448                 else {
3449                         simple_replace(t, "\\\\\\{", "_x_<");
3450                         simple_replace(t, "\\\\\\}", "_x_>");
3451                         LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3452                 }
3453         }
3454
3455         return t;
3456 }
3457
3458
3459 docstring stringifyFromCursor(DocIterator const & cur, int len)
3460 {
3461         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3462         if (cur.inTexted()) {
3463                 Paragraph const & par = cur.paragraph();
3464                 // TODO what about searching beyond/across paragraph breaks ?
3465                 // TODO Try adding a AS_STR_INSERTS as last arg
3466                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3467                         int(par.size()) : cur.pos() + len;
3468                 // OutputParams runparams(&cur.buffer()->params().encoding());
3469                 OutputParams runparams(encodings.fromLyXName("utf8"));
3470                 runparams.nice = true;
3471                 runparams.flavor = Flavor::XeTeX;
3472                 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3473                 // No side effect of file copying and image conversion
3474                 runparams.dryrun = true;
3475                 runparams.for_search = true;
3476                 LYXERR(Debug::FIND, "Stringifying with cur: "
3477                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
3478                 return par.asString(cur.pos(), end,
3479                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3480                         &runparams);
3481         } else if (cur.inMathed()) {
3482                 CursorSlice cs = cur.top();
3483                 MathData md = cs.cell();
3484                 MathData::const_iterator it_end =
3485                         (( len == -1 || cs.pos() + len > int(md.size()))
3486                          ? md.end()
3487                          : md.begin() + cs.pos() + len );
3488                 MathData md2;
3489                 for (MathData::const_iterator it = md.begin() + cs.pos();
3490                      it != it_end; ++it)
3491                         md2.push_back(*it);
3492                 docstring s = asString(md2);
3493                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3494                 return s;
3495         }
3496         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3497         return docstring();
3498 }
3499
3500
3501 /** Computes the LaTeX export of buf starting from cur and ending len positions
3502  * after cur, if len is positive, or at the paragraph or innermost inset end
3503  * if len is -1.
3504  */
3505 docstring latexifyFromCursor(DocIterator const & cur, int len)
3506 {
3507         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3508         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3509                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3510         Buffer const & buf = *cur.buffer();
3511
3512         odocstringstream ods;
3513         otexstream os(ods);
3514         //OutputParams runparams(&buf.params().encoding());
3515         OutputParams runparams(encodings.fromLyXName("utf8"));
3516         runparams.nice = false;
3517         runparams.flavor = Flavor::XeTeX;
3518         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3519         // No side effect of file copying and image conversion
3520         runparams.dryrun = true;
3521         runparams.for_search = true;
3522
3523         if (cur.inTexted()) {
3524                 // @TODO what about searching beyond/across paragraph breaks ?
3525                 pos_type endpos = cur.paragraph().size();
3526                 if (len != -1 && endpos > cur.pos() + len)
3527                         endpos = cur.pos() + len;
3528                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3529                           string(), cur.pos(), endpos);
3530                 string s = lyx::to_utf8(ods.str());
3531                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3532                 return(lyx::from_utf8(s));
3533         } else if (cur.inMathed()) {
3534                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3535                 for (int s = cur.depth() - 1; s >= 0; --s) {
3536                         CursorSlice const & cs = cur[s];
3537                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3538                                 TeXMathStream ws(os);
3539                                 cs.asInsetMath()->asHullInset()->header_write(ws);
3540                                 break;
3541                         }
3542                 }
3543
3544                 CursorSlice const & cs = cur.top();
3545                 MathData md = cs.cell();
3546                 MathData::const_iterator it_end =
3547                         ((len == -1 || cs.pos() + len > int(md.size()))
3548                          ? md.end()
3549                          : md.begin() + cs.pos() + len);
3550                 MathData md2;
3551                 for (MathData::const_iterator it = md.begin() + cs.pos();
3552                      it != it_end; ++it)
3553                         md2.push_back(*it);
3554
3555                 ods << asString(md2);
3556                 // Retrieve the math environment type, and add '$' or '$]'
3557                 // or others (\end{equation}) accordingly
3558                 for (int s = cur.depth() - 1; s >= 0; --s) {
3559                         CursorSlice const & cs2 = cur[s];
3560                         InsetMath * inset = cs2.asInsetMath();
3561                         if (inset && inset->asHullInset()) {
3562                                 TeXMathStream ws(os);
3563                                 inset->asHullInset()->footer_write(ws);
3564                                 break;
3565                         }
3566                 }
3567                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3568         } else {
3569                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3570         }
3571         return ods.str();
3572 }
3573
3574 #if 0
3575 // Debugging output
3576 static void displayMResult(MatchResult &mres, int increment)
3577 {
3578   LYXERR0( "pos: " << mres.pos << " increment " << increment);
3579   LYXERR0( "leadsize: " << mres.leadsize);
3580   LYXERR0( "match_len: " << mres.match_len);
3581   LYXERR0( "match_prefix: " << mres.match_prefix);
3582   LYXERR0( "match2end: " << mres.match2end);
3583 }
3584         #define displayMres(s,i) displayMResult(s,i);
3585 #else
3586         #define displayMres(s,i)
3587 #endif
3588
3589 static bool findAdvForwardInnermost(DocIterator & cur)
3590 {
3591         size_t d;
3592         DocIterator old_cur(cur.buffer());
3593         int forwardCount = 0;
3594         do {
3595                 d = cur.depth();
3596                 old_cur = cur;
3597                 cur.forwardPos();
3598                 if (!cur) {
3599                         break;
3600                 }
3601                 if (cur.depth() > d) {
3602                         forwardCount++;
3603                         continue;
3604                 }
3605                 if (cur.depth() == d)
3606                         break;
3607         } while(1);
3608         cur = old_cur;
3609         if (forwardCount > 0) {
3610                 LYXERR(Debug::FIND, "Forwarded " << forwardCount << " step(s) (searching for innermost match)");
3611                 return true;;
3612         }
3613         else
3614                 return false;
3615 }
3616
3617 /** Finalize an advanced find operation, advancing the cursor to the innermost
3618  ** position that matches, plus computing the length of the matching text to
3619  ** be selected
3620  **/
3621 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, int expected_len, int prefix_len = 0)
3622 {
3623         // Search the foremost position that matches (avoids find of entire math
3624         // inset when match at start of it)
3625         DocIterator old_cur(cur.buffer());
3626         MatchResult mres;
3627         int max_match;
3628         // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3629         // Happens with e.g. hyperlinks
3630         // either one sees "http://www.bla.bla" or nothing
3631         // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3632         // and although we search for only 3 chars, we find the whole hyperlink inset
3633         bool at_begin = (prefix_len == 0);
3634         if (findAdvForwardInnermost(cur)) {
3635                 mres = match(cur, -1, at_begin);
3636                 displayMres(mres, 0);
3637                 if (expected_len > 0) {
3638                         if (mres.match_len < expected_len)
3639                                 return 0;
3640                 }
3641                 else {
3642                         if (mres.match_len <= 0)
3643                                 return 0;
3644                 }
3645                 max_match = mres.match_len;
3646         }
3647         else if (expected_len < 0) {
3648                 mres = match(cur);      /* match valid only if not searching whole words */
3649                 displayMres(mres, 0);
3650                 max_match = mres.match_len;
3651         }
3652         else {
3653                 max_match = expected_len;
3654         }
3655         if (max_match <= 0) return 0;
3656         LYXERR(Debug::FIND, "Ok");
3657
3658         // Compute the match length
3659         int len = 1;
3660         if (cur.pos() + len > cur.lastpos())
3661           return 0;
3662         // regexp should use \w+, \S+, or \b(some string)\b
3663         // to search for whole words
3664         if (match.opt.matchword && !match.use_regexp) {
3665           LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3666           while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3667             ++len;
3668             LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3669           }
3670           // Length of matched text (different from len param)
3671           int old_match = match(cur, len, at_begin).match_len;
3672           if (old_match < 0)
3673             old_match = 0;
3674           int new_match;
3675           // Greedy behaviour while matching regexps
3676           while ((new_match = match(cur, len + 1, at_begin).match_len) > old_match) {
3677             ++len;
3678             old_match = new_match;
3679             LYXERR(Debug::FIND, "verifying   match with len = " << len);
3680           }
3681           if (old_match == 0)
3682             len = 0;
3683         }
3684         else {
3685           int minl = 1;
3686           int maxl = cur.lastpos() - cur.pos();
3687           // Greedy behaviour while matching regexps
3688           while (maxl > minl) {
3689             MatchResult mres2;
3690             mres2 = match(cur, len, at_begin);
3691             displayMres(mres2, len);
3692             int actual_match = mres2.match_len;
3693             if (actual_match >= max_match) {
3694               // actual_match > max_match _can_ happen,
3695               // if the search area splits
3696               // some following word so that the regex
3697               // (e.g. 'r.*r\b' matches 'r' from the middle of the
3698               // splitted word)
3699               // This means, the len value is too big
3700               maxl = len;
3701               if (maxl - minl < 4)
3702                 len = (int)((maxl + minl)/2);
3703               else
3704                 len = (int)(minl + (maxl - minl + 3)/4);
3705             }
3706             else {
3707               // (actual_match < max_match)
3708               minl = len + 1;
3709               len = (int)((maxl + minl)/2);
3710             }
3711           }
3712           old_cur = cur;
3713           // Search for real start of matched characters
3714           while (len > 1) {
3715             int actual_match;
3716             do {
3717               cur.forwardPos();
3718             } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3719             if (cur.depth() < old_cur.depth()) {
3720               // Outer inset?
3721               LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3722               break;
3723             }
3724             if (cur.pos() != old_cur.pos()) {
3725               // OK, forwarded 1 pos in actual inset
3726               actual_match = match(cur, len-1, at_begin).match_len;
3727               if (actual_match == max_match) {
3728                 // Ha, got it! The shorter selection has the same match length
3729                 len--;
3730                 old_cur = cur;
3731               }
3732               else {
3733                 // OK, the shorter selection matches less chars, revert to previous value
3734                 cur = old_cur;
3735                 break;
3736               }
3737             }
3738             else {
3739               LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3740               actual_match = match(cur, len, at_begin).match_len;
3741               if (actual_match == max_match)
3742                 old_cur = cur;
3743             }
3744           }
3745         }
3746         return len;
3747 }
3748
3749 /// Finds forward
3750 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
3751 {
3752         if (!cur)
3753                 return 0;
3754         while (!theApp()->longOperationCancelled() && cur) {
3755                 (void) findAdvForwardInnermost(cur);
3756                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3757                 MatchResult mres = match(cur, -1, false);
3758                 displayMres(mres,-1)
3759                 int match_len = mres.match_len;
3760                 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3761                         LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3762                         match_len = 0;
3763                 }
3764                 if (match_len > 0) {
3765                         // Try to find the begin of searched string
3766                         int increment;
3767                         int firstInvalid = 100000;
3768                         if (mres.match_prefix + mres.pos - mres.leadsize > 1)
3769                           increment = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3770                         else
3771                           increment = 10;
3772                         LYXERR(Debug::FIND, "Set increment to " << increment);
3773                         while (increment > 0) {
3774                                 DocIterator old_cur = cur;
3775                                 for (int i = 0; i < increment && cur; cur.forwardPos(), i++) {
3776                                 }
3777                                 if (! cur || (cur.pit() > old_cur.pit())) {
3778                                         // Are we outside of the paragraph?
3779                                         // This can happen if moving past some UTF8-encoded chars
3780                                         cur = old_cur;
3781                                         increment /= 2;
3782                                 }
3783                                 else {
3784                                         MatchResult mres2 = match(cur, -1, false);
3785                                         displayMres(mres2,increment)
3786                                         switch (interpretMatch(mres, mres2)) {
3787                                         case MatchResult::newIsTooFar:
3788                                           // behind the expected match
3789                                           firstInvalid = increment;
3790                                           cur = old_cur;
3791                                           increment /= 2;
3792                                           break;
3793                                         case MatchResult::newIsBetter:
3794                                           // not reached ye, but cur.pos()+increment is bettert
3795                                           mres = mres2;
3796                                           firstInvalid -= increment;
3797                                           if (increment > firstInvalid*3/4)
3798                                             increment = firstInvalid*3/4;
3799                                           if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3800                                             if (increment >= mres2.match_prefix)
3801                                               increment = (mres2.match_prefix+1)*3/4;
3802                                           }
3803                                           break;
3804                                         default:
3805                                           // Todo@
3806                                           // Handle not like MatchResult::newIsTooFar
3807                                           // LYXERR0( "Something is wrong: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3808                                           firstInvalid--;
3809                                           increment = increment*3/4;
3810                                           cur = old_cur;
3811                                           break;
3812                                         }
3813                                 }
3814                         }
3815                         // LYXERR0("Leaving first loop");
3816                         {
3817                           LYXERR(Debug::FIND, "Finalizing 1");
3818                           int len = findAdvFinalize(cur, match, mres.match_len, mres.match_prefix);
3819                           if (len > 0)
3820                             return len;
3821                           else {
3822                             // try next possible match
3823                             cur.forwardPos();
3824                             continue;
3825                           }
3826                         }
3827                         // The following code is newer reached
3828                         // but parts of it may be needed in future
3829                         int match_len_zero_count = 0;
3830                         MatchResult mres3;
3831                         for (int i = 0; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
3832                                 if (i++ > 3) {
3833                                         mres3 = match(cur, -1, false);
3834                                         displayMres(mres3, 1)
3835                                         int remaining_len = mres3.match_len;
3836                                         if (remaining_len <= 0) {
3837                                                 // Apparently the searched string is not in the remaining part
3838                                                 break;
3839                                         }
3840                                         else {
3841                                                 i = 0;
3842                                         }
3843                                 }
3844                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
3845                                 mres3 = match(cur, 1);
3846                                 displayMres(mres3, 1)
3847                                 int match_len3 = mres3.match_len;
3848                                 if (match_len3 < 0)
3849                                         continue;
3850                                 mres3 = match(cur);
3851                                 displayMres(mres3, 1)
3852                                 int match_len2 = mres3.match_len;
3853                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
3854                                 if (match_len2 > 0) {
3855                                         // Sometimes in finalize we understand it wasn't a match
3856                                         // and we need to continue the outest loop
3857                                         LYXERR(Debug::FIND, "Finalizing 2");
3858                                         int len = findAdvFinalize(cur, match, mres.match_len);
3859                                         if (len > 0) {
3860                                                 return len;
3861                                         }
3862                                 }
3863                                 if (match_len2 > 0)
3864                                         match_len_zero_count = 0;
3865                                 else if (match_len2 == 0)
3866                                         match_len_zero_count++;
3867                                 if (match_len2 < 0) {
3868                                         if (++match_len_zero_count > 3) {
3869                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
3870                                         }
3871                                         break;
3872                                 }
3873                         }
3874                         if (!cur)
3875                                 return 0;
3876                 }
3877                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
3878                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
3879                         cur.forwardPar();
3880                 } else {
3881                         // This should exit nested insets, if any, or otherwise undefine the currsor.
3882                         cur.pos() = cur.lastpos();
3883                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3884                         cur.forwardPos();
3885                 }
3886         }
3887         return 0;
3888 }
3889
3890
3891 /// Find the most backward consecutive match within same paragraph while searching backwards.
3892 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3893 {
3894         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3895         DocIterator tmp_cur = cur;
3896         int len = findAdvFinalize(tmp_cur, match, -1);
3897         Inset & inset = cur.inset();
3898         for (; cur != cur_begin; cur.backwardPos()) {
3899                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3900                 DocIterator new_cur = cur;
3901                 new_cur.backwardPos();
3902                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3903                         break;
3904                 int new_len = findAdvFinalize(new_cur, match, -1);
3905                 if (new_len == len)
3906                         break;
3907                 len = new_len;
3908         }
3909         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3910         return len;
3911 }
3912
3913
3914 /// Finds backwards
3915 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3916 {
3917         if (! cur)
3918                 return 0;
3919         // Backup of original position
3920         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3921         if (cur == cur_begin)
3922                 return 0;
3923         cur.backwardPos();
3924         DocIterator cur_orig(cur);
3925         bool pit_changed = false;
3926         do {
3927                 cur.pos() = 0;
3928                 bool found_match = (match(cur, -1, false).match_len > 0);
3929
3930                 if (found_match) {
3931                         if (pit_changed)
3932                                 cur.pos() = cur.lastpos();
3933                         else
3934                                 cur.pos() = cur_orig.pos();
3935                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3936                         DocIterator cur_prev_iter;
3937                         do {
3938                                 found_match = (match(cur).match_len > 0);
3939                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3940                                        << found_match << ", cur: " << cur);
3941                                 if (found_match)
3942                                         return findMostBackwards(cur, match);
3943
3944                                 // Stop if begin of document reached
3945                                 if (cur == cur_begin)
3946                                         break;
3947                                 cur_prev_iter = cur;
3948                                 cur.backwardPos();
3949                         } while (true);
3950                 }
3951                 if (cur == cur_begin)
3952                         break;
3953                 if (cur.pit() > 0)
3954                         --cur.pit();
3955                 else
3956                         cur.backwardPos();
3957                 pit_changed = true;
3958         } while (!theApp()->longOperationCancelled());
3959         return 0;
3960 }
3961
3962
3963 } // namespace
3964
3965
3966 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3967                                  DocIterator const & cur, int len)
3968 {
3969         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3970                 return docstring();
3971         if (!opt.ignoreformat)
3972                 return latexifyFromCursor(cur, len);
3973         else
3974                 return stringifyFromCursor(cur, len);
3975 }
3976
3977
3978 FindAndReplaceOptions::FindAndReplaceOptions(
3979         docstring const & _find_buf_name, bool _casesensitive,
3980         bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3981         docstring const & _repl_buf_name, bool _keep_case,
3982         SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3983         : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3984           forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3985           repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3986 {
3987 }
3988
3989
3990 namespace {
3991
3992
3993 /** Check if 'len' letters following cursor are all non-lowercase */
3994 static bool allNonLowercase(Cursor const & cur, int len)
3995 {
3996         pos_type beg_pos = cur.selectionBegin().pos();
3997         pos_type end_pos = cur.selectionBegin().pos() + len;
3998         if (len > cur.lastpos() + 1 - beg_pos) {
3999                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
4000                 len = cur.lastpos() + 1 - beg_pos;
4001                 end_pos = beg_pos + len;
4002         }
4003         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4004                 if (isLowerCase(cur.paragraph().getChar(pos)))
4005                         return false;
4006         return true;
4007 }
4008
4009
4010 /** Check if first letter is upper case and second one is lower case */
4011 static bool firstUppercase(Cursor const & cur)
4012 {
4013         char_type ch1, ch2;
4014         pos_type pos = cur.selectionBegin().pos();
4015         if (pos >= cur.lastpos() - 1) {
4016                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
4017                 return false;
4018         }
4019         ch1 = cur.paragraph().getChar(pos);
4020         ch2 = cur.paragraph().getChar(pos + 1);
4021         bool result = isUpperCase(ch1) && isLowerCase(ch2);
4022         LYXERR(Debug::FIND, "firstUppercase(): "
4023                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4024                << ch2 << "(" << char(ch2) << ")"
4025                << ", result=" << result << ", cur=" << cur);
4026         return result;
4027 }
4028
4029
4030 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4031  **
4032  ** \fixme What to do with possible further paragraphs in replace buffer ?
4033  **/
4034 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4035 {
4036         ParagraphList::iterator pit = buffer.paragraphs().begin();
4037         LASSERT(!pit->empty(), /**/);
4038         pos_type right = pos_type(1);
4039         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4040         right = pit->size();
4041         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4042 }
4043
4044 } // namespace
4045
4046 ///
4047 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4048 {
4049         Cursor & cur = bv->cursor();
4050         if (opt.repl_buf_name.empty()
4051             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4052             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4053                 return 0;
4054
4055         DocIterator sel_beg = cur.selectionBegin();
4056         DocIterator sel_end = cur.selectionEnd();
4057         if (&sel_beg.inset() != &sel_end.inset()
4058             || sel_beg.pit() != sel_end.pit()
4059             || sel_beg.idx() != sel_end.idx())
4060                 return 0;
4061         int sel_len = sel_end.pos() - sel_beg.pos();
4062         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4063                << ", sel_len: " << sel_len << endl);
4064         if (sel_len == 0)
4065                 return 0;
4066         LASSERT(sel_len > 0, return 0);
4067
4068         if (!matchAdv(sel_beg, sel_len).match_len)
4069                 return 0;
4070
4071         // Build a copy of the replace buffer, adapted to the KeepCase option
4072         Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4073         ostringstream oss;
4074         repl_buffer_orig.write(oss);
4075         string lyx = oss.str();
4076         Buffer repl_buffer("", false);
4077         repl_buffer.setUnnamed(true);
4078         LASSERT(repl_buffer.readString(lyx), return 0);
4079         if (opt.keep_case && sel_len >= 2) {
4080                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4081                 if (cur.inTexted()) {
4082                         if (firstUppercase(cur))
4083                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4084                         else if (allNonLowercase(cur, sel_len))
4085                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4086                 }
4087         }
4088         cap::cutSelection(cur, false);
4089         if (cur.inTexted()) {
4090                 repl_buffer.changeLanguage(
4091                         repl_buffer.language(),
4092                         cur.getFont().language());
4093                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4094                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4095                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4096                                         repl_buffer.params().documentClassPtr(),
4097                                         bv->buffer().errorList("Paste"));
4098                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4099                 sel_len = repl_buffer.paragraphs().begin()->size();
4100         } else if (cur.inMathed()) {
4101                 odocstringstream ods;
4102                 otexstream os(ods);
4103                 // OutputParams runparams(&repl_buffer.params().encoding());
4104                 OutputParams runparams(encodings.fromLyXName("utf8"));
4105                 runparams.nice = false;
4106                 runparams.flavor = Flavor::XeTeX;
4107                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4108                 runparams.dryrun = true;
4109                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4110                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4111                 docstring repl_latex = ods.str();
4112                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4113                 string s;
4114                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4115                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4116                 repl_latex = from_utf8(s);
4117                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4118                 MathData ar(cur.buffer());
4119                 asArray(repl_latex, ar, Parse::NORMAL);
4120                 cur.insert(ar);
4121                 sel_len = ar.size();
4122                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4123         }
4124         if (cur.pos() >= sel_len)
4125                 cur.pos() -= sel_len;
4126         else
4127                 cur.pos() = 0;
4128         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4129         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4130         bv->processUpdateFlags(Update::Force);
4131         return 1;
4132 }
4133
4134
4135 /// Perform a FindAdv operation.
4136 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
4137 {
4138         DocIterator cur;
4139         int match_len = 0;
4140
4141         // e.g., when invoking word-findadv from mini-buffer wither with
4142         //       wrong options syntax or before ever opening advanced F&R pane
4143         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4144                 return false;
4145
4146         try {
4147                 MatchStringAdv matchAdv(bv->buffer(), opt);
4148 #if QTSEARCH
4149                 if (!matchAdv.regexIsValid) {
4150                         bv->message(lyx::from_utf8(matchAdv.regexError));
4151                         return(false);
4152                 }
4153 #endif
4154                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4155                 if (length > 0)
4156                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4157                 num_replaced += findAdvReplace(bv, opt, matchAdv);
4158                 cur = bv->cursor();
4159                 if (opt.forward)
4160                         match_len = findForwardAdv(cur, matchAdv);
4161                 else
4162                         match_len = findBackwardsAdv(cur, matchAdv);
4163         } catch (exception & ex) {
4164                 bv->message(from_utf8(ex.what()));
4165                 return false;
4166         }
4167
4168         if (match_len == 0) {
4169                 if (num_replaced > 0) {
4170                         switch (num_replaced)
4171                         {
4172                                 case 1:
4173                                         bv->message(_("One match has been replaced."));
4174                                         break;
4175                                 case 2:
4176                                         bv->message(_("Two matches have been replaced."));
4177                                         break;
4178                                 default:
4179                                         bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4180                                         break;
4181                         }
4182                         num_replaced = 0;
4183                 }
4184                 else {
4185                         bv->message(_("Match not found."));
4186                 }
4187                 return false;
4188         }
4189
4190         if (num_replaced > 0)
4191                 bv->message(_("Match has been replaced."));
4192         else
4193                 bv->message(_("Match found."));
4194
4195         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
4196         bv->putSelectionAt(cur, match_len, !opt.forward);
4197
4198         return true;
4199 }
4200
4201
4202 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4203 {
4204         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4205            << opt.casesensitive << ' '
4206            << opt.matchword << ' '
4207            << opt.forward << ' '
4208            << opt.expandmacros << ' '
4209            << opt.ignoreformat << ' '
4210            << opt.replace_all << ' '
4211            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4212            << opt.keep_case << ' '
4213            << int(opt.scope) << ' '
4214            << int(opt.restr);
4215
4216         LYXERR(Debug::FIND, "built: " << os.str());
4217
4218         return os;
4219 }
4220
4221
4222 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4223 {
4224         LYXERR(Debug::FIND, "parsing");
4225         string s;
4226         string line;
4227         getline(is, line);
4228         while (line != "EOSS") {
4229                 if (! s.empty())
4230                         s = s + "\n";
4231                 s = s + line;
4232                 if (is.eof())   // Tolerate malformed request
4233                         break;
4234                 getline(is, line);
4235         }
4236         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4237         opt.find_buf_name = from_utf8(s);
4238         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4239         is.get();       // Waste space before replace string
4240         s = "";
4241         getline(is, line);
4242         while (line != "EOSS") {
4243                 if (! s.empty())
4244                         s = s + "\n";
4245                 s = s + line;
4246                 if (is.eof())   // Tolerate malformed request
4247                         break;
4248                 getline(is, line);
4249         }
4250         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4251         opt.repl_buf_name = from_utf8(s);
4252         is >> opt.keep_case;
4253         int i;
4254         is >> i;
4255         opt.scope = FindAndReplaceOptions::SearchScope(i);
4256         is >> i;
4257         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4258
4259         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4260                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4261                << opt.scope << ' ' << opt.restr);
4262         return is;
4263 }
4264
4265 } // namespace lyx