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