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