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