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