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