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