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