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