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