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